cd_recording_status_websocket.py 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. #!/usr/bin/env python3
  2. import asyncio
  3. import json
  4. from os import path
  5. import time
  6. import websockets
  7. from utils import expand_dir, get_current_yyyy_mm_dd_date, log
  8. import config as const
  9. from input import get_cachefile_content
  10. from recording import (
  11. is_valid_cd_record_checkfile,
  12. get_is_recording_active,
  13. get_cd_count,
  14. get_cd_marker_count,
  15. get_full_rec_time,
  16. get_track_rec_time,
  17. )
  18. # Simulated CD status (you can replace this with real logic)
  19. cd_number = 3
  20. track_number = 7
  21. start_time = time.time()
  22. track_start = time.time() - 37 # Simulate track started 37s ago
  23. def get_inactive_recording_status() -> dict:
  24. return {
  25. "recording": False,
  26. "cd": 0,
  27. "track": 0,
  28. "cd_time": "00:00",
  29. "track_time": "00:00",
  30. }
  31. async def status_sender(websocket):
  32. while True:
  33. if path.isfile(expand_dir(const.CD_RECORD_CACHEFILE)):
  34. cachefile_content = get_cachefile_content(const.CD_RECORD_CACHEFILE)
  35. if is_valid_cd_record_checkfile(
  36. cachefile_content, get_current_yyyy_mm_dd_date()
  37. ):
  38. is_recording_active = get_is_recording_active(cachefile_content)
  39. status = {
  40. "recording": is_recording_active,
  41. "cd": get_cd_count(is_recording_active, cachefile_content),
  42. "track": get_cd_count(
  43. is_recording_active, cachefile_content
  44. ),
  45. "cd_time": get_full_rec_time(
  46. is_recording_active, cachefile_content
  47. ),
  48. "track_time": get_track_rec_time(
  49. is_recording_active, cachefile_content
  50. ),
  51. }
  52. else:
  53. status = get_inactive_recording_status()
  54. else:
  55. status = get_inactive_recording_status()
  56. await websocket.send(json.dumps(status))
  57. await asyncio.sleep(0.3)
  58. async def handler(websocket):
  59. log(f"Client connected: {websocket.remote_address}")
  60. try:
  61. await status_sender(websocket)
  62. except websockets.exceptions.ConnectionClosed:
  63. log("Client disconnected")
  64. async def main():
  65. log("Starting CD Rec status WebSocket server on ws://localhost:8765")
  66. async with websockets.serve(handler, "localhost", 8765):
  67. await asyncio.Future() # Run forever
  68. if __name__ == "__main__":
  69. asyncio.run(main())