socket_server.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267
  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. import traceback
  14. import logging
  15. from utils import common
  16. from utils.common import message_queue
  17. logger = logging.getLogger(__name__)
  18. conn_manager = ConnectionManager()
  19. active_connections = set()
  20. device_ctrl = DeviceControl(websocket_manager=conn_manager)
  21. blue_tooth = BlueToothMode(websocket_manager=conn_manager)
  22. smart_shooter = SmartShooter(websocket_manager=conn_manager)
  23. async def updateDataRecord(PhotoFilename, id):
  24. await asyncio.sleep(0.01)
  25. create_time = datetime.datetime.fromtimestamp(os.path.getctime(PhotoFilename))
  26. data = {"id": id, "image_path": PhotoFilename, "photo_create_time": create_time}
  27. # record_model = PhotoRecord(**data)
  28. session = SqlQuery()
  29. record_model = CRUD(PhotoRecord)
  30. model = record_model.read(session, conditions={"id": id,"delete_time": None})
  31. if model == None:
  32. print(f"smart shooter 拍照记录更新失败,记录id:{id},不存在")
  33. else:
  34. # 走编辑逻辑
  35. settings.syncPhotoRecord(data,action_type=3)
  36. record_model.updateConditions(session, conditions={"id": id}, **data)
  37. print(f"smart shooter 拍照记录更新成功,记录id:{id}")
  38. session.close()
  39. @app.websocket("/ws")
  40. async def websocket_endpoint(websocket: WebSocket):
  41. # await websocket.accept()
  42. main_loop = asyncio.get_running_loop()
  43. smart_shooter.main_loop = main_loop # <--- 添加这一行
  44. await conn_manager.connect(websocket)
  45. active_connections.add(websocket)
  46. smart_shooter.websocket = websocket
  47. device_ctrl.websocket = websocket
  48. blue_tooth.websocket = websocket
  49. common.websocket_manager = conn_manager
  50. common.websocket = websocket
  51. # 启动 smart_shooter.connect_listen 服务
  52. listen_task = None
  53. tasks = set()
  54. send_task = None # <--- 新增
  55. try:
  56. # 初始化回调函数
  57. smart_shooter.callback_listen = MsgCallback
  58. # 创建任务来并发处理不同类型的消息
  59. handler_task = asyncio.create_task(handler_messages(websocket))
  60. # send_task = asyncio.create_task(send_message(websocket))
  61. send_task = asyncio.create_task(send_message(websocket)) # <--- 启动消费者
  62. loop = asyncio.get_event_loop()
  63. listen_task = loop.run_in_executor(None, smart_shooter.connect_listen)
  64. # send_task = loop.run_in_executor(None, send_message(websocket))
  65. # 创建任务来启动 connect_listen
  66. # listen_task = asyncio.create_task(restart_smart_shooter_listener())
  67. # 等待所有任务完成
  68. await asyncio.gather(handler_task,listen_task, return_exceptions=True)
  69. except WebSocketDisconnect:
  70. print("Client disconnected")
  71. except asyncio.CancelledError:
  72. print("Connection cancelled")
  73. finally:
  74. # 确保任务被正确取消和清理
  75. tasks_to_cancel = []
  76. if handler_task and not handler_task.done():
  77. tasks_to_cancel.append(handler_task)
  78. if send_task and not send_task.done():
  79. tasks_to_cancel.append(send_task)
  80. # 取消所有待处理的任务
  81. for task in tasks_to_cancel:
  82. task.cancel()
  83. # 等待任务取消完成
  84. if tasks_to_cancel:
  85. await asyncio.gather(*tasks_to_cancel, return_exceptions=True)
  86. # 清理连接
  87. active_connections.discard(websocket)
  88. print("WebSocket connection cleaned up")
  89. async def start_smart_shooter_listen():
  90. """启动 smart_shooter 监听服务"""
  91. loop = asyncio.get_event_loop()
  92. # 在执行器中运行 connect_listen 方法
  93. try:
  94. loop.create_task(None, smart_shooter.connect_listen())
  95. except Exception as e:
  96. print(f"Smart shooter listen error: {e}")
  97. async def handler_messages(websocket):
  98. while True:
  99. try:
  100. byteDats = await websocket.receive()
  101. socket_type = byteDats.get("type")
  102. if socket_type == "websocket.disconnect":
  103. print("socket_type===>", byteDats)
  104. if byteDats.get("code") == 1006:
  105. continue
  106. logger.info("socket强制断开")
  107. diviceList = blue_tooth.devices
  108. if len(diviceList) == 0:
  109. blue_tooth.bluetooth_exit = True
  110. blue_tooth.clearMyInstance()
  111. break
  112. diviceAddress = (
  113. ""
  114. if len(list(diviceList.keys())) == 0
  115. else list(diviceList.keys())[0]
  116. )
  117. if diviceAddress != "":
  118. print(diviceList.get(diviceAddress))
  119. diviceName = diviceList[diviceAddress]["name"]
  120. blue_tooth.disconnect_device(diviceAddress, diviceName)
  121. blue_tooth.bluetooth_exit = True
  122. blue_tooth.clearMyInstance()
  123. print("所有设备已断开连接")
  124. break
  125. print("byteDats", byteDats)
  126. # 使用create_task来避免阻塞消息处理循环
  127. asyncio.create_task(
  128. handlerSend(
  129. conn_manager, json.dumps(byteDats), websocket, smart_shooter
  130. )
  131. )
  132. except Exception as e:
  133. print("socket error",e)
  134. break
  135. async def message_generator():
  136. """异步生成器,用于从队列中获取消息"""
  137. while True:
  138. try:
  139. # 使用asyncio.wait_for设置合理的超时时间
  140. message = await message_queue.get()
  141. yield message
  142. except asyncio.TimeoutError:
  143. # 超时继续,允许其他协程运行
  144. await asyncio.sleep(0.01)
  145. # print("超时继续,允许其他协程运行")
  146. continue
  147. except Exception as e:
  148. print("消息生成器错误", e)
  149. break
  150. async def send_message(websocket):
  151. """使用异步生成器发送消息"""
  152. print("构建消息监听 send_message")
  153. while True:
  154. try:
  155. # 1. 异步等待消息,不会阻塞其他协程
  156. data = await message_queue.get()
  157. # 2. 发送消息
  158. if common.websocket_manager:
  159. # 假设 broadcast 或 send_personal_message 是异步方法
  160. await common.websocket_manager.send_personal_message(data,common.websocket)
  161. # 或者根据你的 ConnectionManager 实现调用具体发送方法
  162. message_queue.task_done()
  163. except Exception as e:
  164. print(f"消息消费错误: {e}")
  165. await asyncio.sleep(1) # 防止死循环报错
  166. async def MsgCallback(msg):
  167. msg_id = msg.get("msg_id")
  168. match msg_id:
  169. case "PhotoUpdated":
  170. PhotoFilename = msg.get("PhotoFilename")
  171. PhotoLocation = msg.get("PhotoLocation")
  172. PhotoOrigin = msg.get("PhotoOrigin")
  173. if (PhotoFilename != "" and PhotoFilename != None) and (
  174. PhotoLocation == "Local Disk"
  175. ):
  176. # temp_photo_name = PhotoFilename
  177. # 更新拍照记录
  178. logger.info(f"PhotoUpdated,{PhotoFilename}--{PhotoOrigin}")
  179. goods_art_no = None
  180. id = None
  181. try:
  182. if PhotoOrigin != "" and PhotoOrigin not in ["external", "ui"]:
  183. goods_art_no, id = PhotoOrigin.split(",")
  184. # 创建任务来处理数据库更新,避免阻塞回调
  185. await updateDataRecord(PhotoFilename, id)
  186. except Exception as e:
  187. print("拍照更新异常", e)
  188. data = conn_manager.jsonMessage(
  189. code=0,
  190. msg=f"照片获取成功",
  191. data={
  192. "photo_file_name": PhotoFilename,
  193. "goods_art_no": goods_art_no,
  194. },
  195. msg_type="smart_shooter_photo_take",
  196. )
  197. await conn_manager.send_personal_message(data, smart_shooter.websocket)
  198. case "LiveviewUpdated":
  199. CameraLiveviewImage = msg.get("CameraLiveviewImage", None)
  200. # base64_to_image(CameraLiveviewImage, "liveview.jpg")
  201. # print("收到直播画面:CameraLiveviewImage")
  202. data = conn_manager.jsonMessage(
  203. code=1,
  204. msg=f"预览数据发送",
  205. data={"smart_shooter_preview": CameraLiveviewImage},
  206. msg_type="smart_shooter_enable_preview",
  207. )
  208. await conn_manager.send_personal_message(data, smart_shooter.websocket)
  209. # case _:
  210. # print("收到未知数据:{}".format(msg))
  211. # @app.on_event("startup")
  212. # async def startup_event():
  213. # loop = asyncio.get_event_loop()
  214. # loop.run_in_executor(None, await smart_shooter.connect_listen)
  215. # print("监听服务已启动")
  216. @app.on_event("shutdown")
  217. async def shutdown_event():
  218. print("Shutting down...")
  219. # socket_manager.close()
  220. # 清理操作
  221. for connection in list(active_connections):
  222. try:
  223. await connection.close()
  224. except Exception as e:
  225. print(f"Error closing connection: {e}")
  226. smart_shooter.stop_listen = True
  227. smart_shooter.is_init_while = False
  228. device_ctrl.close_connect()
  229. device_ctrl.close_lineConnect()
  230. device_ctrl.mcu_exit = True
  231. device_ctrl.p_list = []
  232. device_ctrl.temp_ports_dict = {}
  233. device_ctrl.clearMyInstance()
  234. diviceList = blue_tooth.devices
  235. if len(diviceList) == 0:
  236. blue_tooth.bluetooth_exit = True
  237. blue_tooth.clearMyInstance()
  238. diviceAddress = "" if len(list(diviceList.keys()))==0 else list(diviceList.keys())[0]
  239. if diviceAddress != "":
  240. print(diviceList.get(diviceAddress))
  241. diviceName = diviceList[diviceAddress]["name"]
  242. blue_tooth.disconnect_device(diviceAddress, diviceName)
  243. blue_tooth.bluetooth_exit = True
  244. blue_tooth.clearMyInstance()
  245. print("所有设备已断开连接")