cd_recording_status_websocket.py 2.4 KB

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