socket_server.py 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143
  1. import json
  2. import asyncio
  3. from models import *
  4. from .connect_manager import ConnectionManager
  5. from .message_handler import *
  6. from mcu.DeviceControl import DeviceControl,checkMcuConnection
  7. from mcu.BlueToothMode import BlueToothMode
  8. from mcu.capture.smart_shooter_class import SmartShooter
  9. import time
  10. from .socket_client import socket_manager
  11. from sqlalchemy.exc import NoResultFound
  12. import os, datetime
  13. conn_manager = ConnectionManager()
  14. active_connections = set()
  15. device_ctrl = DeviceControl(websocket_manager=conn_manager)
  16. blue_tooth = BlueToothMode(websocket_manager=conn_manager)
  17. smart_shooter = SmartShooter(websocket_manager=conn_manager)
  18. from utils.common import message_queue
  19. async def updateDataRecord(PhotoFilename, id):
  20. await asyncio.sleep(0.01)
  21. create_time = datetime.datetime.fromtimestamp(os.path.getctime(PhotoFilename))
  22. data = {"id": id, "image_path": PhotoFilename, "photo_create_time": create_time}
  23. # record_model = PhotoRecord(**data)
  24. session = SqlQuery()
  25. record_model = CRUD(PhotoRecord)
  26. model = record_model.read(session, conditions={"id": id})
  27. if model == None:
  28. print(f"smart shooter 拍照记录更新失败,记录id:{id},不存在")
  29. else:
  30. # 走编辑逻辑
  31. record_model.updateConditions(session, conditions={"id": id}, **data)
  32. print(f"smart shooter 拍照记录更新成功,记录id:{id}")
  33. @app.websocket("/ws")
  34. async def websocket_endpoint(websocket: WebSocket):
  35. await conn_manager.connect(websocket)
  36. active_connections.add(websocket)
  37. smart_shooter.websocket = websocket
  38. try:
  39. # await socket_manager.connect()
  40. async def handler_messages():
  41. while True:
  42. try:
  43. byteDats = await websocket.receive()
  44. socket_type = byteDats.get("type")
  45. if socket_type == "websocket.disconnect":
  46. smart_shooter.stop_listen = True
  47. device_ctrl.close_connect()
  48. device_ctrl.mcu_exit = True
  49. device_ctrl.clearMyInstance()
  50. diviceList = blue_tooth.devices
  51. if len(diviceList) == 0:
  52. blue_tooth.bluetooth_exit = True
  53. blue_tooth.clearMyInstance()
  54. break
  55. diviceAddress = list(diviceList.keys())[0]
  56. if diviceAddress != "":
  57. print(diviceList.get(diviceAddress))
  58. diviceName = diviceList[diviceAddress]["name"]
  59. blue_tooth.disconnect_device(diviceAddress, diviceName)
  60. blue_tooth.bluetooth_exit = True
  61. blue_tooth.clearMyInstance()
  62. break
  63. print("byteDats", byteDats)
  64. await handlerSend(
  65. conn_manager, json.dumps(byteDats), websocket, smart_shooter
  66. )
  67. except Exception as e:
  68. print(e)
  69. break
  70. # async def checkConnMcu():
  71. # await checkMcuConnection(device_ctrl)
  72. # async def connectBlueTooth():
  73. # await blue_tooth.main_func()
  74. async def send_message():
  75. while True:
  76. try:
  77. message = await message_queue.get()
  78. await websocket.send_json(message)
  79. except Exception as e:
  80. print(e)
  81. break
  82. async def MsgCallback(msg):
  83. msg_id = msg.get("msg_id")
  84. match msg_id:
  85. case "PhotoUpdated":
  86. PhotoFilename = msg.get("PhotoFilename")
  87. PhotoLocation = msg.get("PhotoLocation")
  88. PhotoOrigin = msg.get("PhotoOrigin")
  89. if (PhotoFilename != "" and PhotoFilename != None) and (
  90. PhotoLocation == "Local Disk"
  91. ):
  92. # temp_photo_name = PhotoFilename
  93. # 更新拍照记录
  94. print("PhotoFilename", PhotoFilename, PhotoOrigin)
  95. if PhotoOrigin != "" and PhotoOrigin != "external":
  96. goods_art_no, id = PhotoOrigin.split(",")
  97. await updateDataRecord(PhotoFilename, id)
  98. data = conn_manager.jsonMessage(
  99. code=0,
  100. msg=f"照片获取成功",
  101. data={"photo_file_name": PhotoFilename},
  102. msg_type="smart_shooter_photo_take",
  103. )
  104. await conn_manager.send_personal_message(data, websocket)
  105. case "LiveviewUpdated":
  106. CameraLiveviewImage = msg.get("CameraLiveviewImage", None)
  107. # base64_to_image(CameraLiveviewImage, "liveview.jpg")
  108. # print("收到直播画面:CameraLiveviewImage")
  109. data = conn_manager.jsonMessage(
  110. code=1,
  111. msg=f"预览数据发送",
  112. data={"smart_shooter_preview": CameraLiveviewImage},
  113. msg_type="smart_shooter_enable_preview",
  114. )
  115. await conn_manager.send_personal_message(data, websocket)
  116. smart_shooter.callback_listen = MsgCallback
  117. async def runListen():
  118. await smart_shooter.connect_listen()
  119. await asyncio.gather(
  120. handler_messages(), send_message(), runListen()
  121. )
  122. except WebSocketDisconnect:
  123. # socket_manager.close()
  124. print("Client disconnected")
  125. finally:
  126. active_connections.discard(websocket)
  127. # if websocket:
  128. # await websocket.close()
  129. @app.on_event("shutdown")
  130. async def shutdown_event():
  131. print("Shutting down...")
  132. # socket_manager.close()
  133. # 清理操作
  134. for connection in list(active_connections):
  135. try:
  136. await connection.close()
  137. except Exception as e:
  138. print(f"Error closing connection: {e}")