socket_server.py 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261
  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 websocket.accept()
  36. await conn_manager.connect(websocket)
  37. active_connections.add(websocket)
  38. smart_shooter.websocket = websocket
  39. # 启动 smart_shooter.connect_listen 服务
  40. listen_task = None
  41. tasks = set()
  42. try:
  43. # 初始化回调函数
  44. smart_shooter.callback_listen = MsgCallback
  45. # 创建任务来并发处理不同类型的消息
  46. handler_task = asyncio.create_task(handler_messages(websocket))
  47. send_task = asyncio.create_task(send_message(websocket))
  48. loop = asyncio.get_event_loop()
  49. listen_task = loop.run_in_executor(None, smart_shooter.connect_listen)
  50. # send_task = loop.run_in_executor(None, send_message(websocket))
  51. # 创建任务来启动 connect_listen
  52. # listen_task = asyncio.create_task(restart_smart_shooter_listener())
  53. # 等待所有任务完成
  54. await asyncio.gather(handler_task, listen_task, send_task)
  55. except WebSocketDisconnect:
  56. print("Client disconnected")
  57. finally:
  58. # 确保任务被正确取消
  59. if listen_task and not listen_task.done():
  60. listen_task.cancel()
  61. active_connections.discard(websocket)
  62. async def start_smart_shooter_listen():
  63. """启动 smart_shooter 监听服务"""
  64. loop = asyncio.get_event_loop()
  65. # 在执行器中运行 connect_listen 方法
  66. try:
  67. loop.create_task(None, smart_shooter.connect_listen())
  68. except Exception as e:
  69. print(f"Smart shooter listen error: {e}")
  70. async def handler_messages(websocket):
  71. while True:
  72. try:
  73. byteDats = await websocket.receive()
  74. socket_type = byteDats.get("type")
  75. if socket_type == "websocket.disconnect":
  76. smart_shooter.stop_listen = True
  77. smart_shooter.is_init_while = False
  78. device_ctrl.close_connect()
  79. device_ctrl.close_lineConnect()
  80. device_ctrl.mcu_exit = True
  81. device_ctrl.p_list = []
  82. device_ctrl.temp_ports_dict = {}
  83. device_ctrl.clearMyInstance()
  84. diviceList = blue_tooth.devices
  85. if len(diviceList) == 0:
  86. blue_tooth.bluetooth_exit = True
  87. blue_tooth.clearMyInstance()
  88. break
  89. diviceAddress = (
  90. ""
  91. if len(list(diviceList.keys())) == 0
  92. else list(diviceList.keys())[0]
  93. )
  94. if diviceAddress != "":
  95. print(diviceList.get(diviceAddress))
  96. diviceName = diviceList[diviceAddress]["name"]
  97. blue_tooth.disconnect_device(diviceAddress, diviceName)
  98. blue_tooth.bluetooth_exit = True
  99. blue_tooth.clearMyInstance()
  100. print("所有设备已断开连接")
  101. break
  102. print("byteDats", byteDats)
  103. # 使用create_task来避免阻塞消息处理循环
  104. asyncio.create_task(
  105. handlerSend(
  106. conn_manager, json.dumps(byteDats), websocket, smart_shooter
  107. )
  108. )
  109. except Exception as e:
  110. print(e)
  111. break
  112. # async def send_message(websocket):
  113. # print("构建消息监听 send_message")
  114. # while True:
  115. # try:
  116. # # 使用wait()而不是直接get()来避免阻塞
  117. # # 从异步队列中获取消息(在新事件循环中运行)
  118. # message = await message_queue.get()
  119. # # 发送消息
  120. # await websocket.send_json(message)
  121. # message_queue.task_done()
  122. # except asyncio.QueueEmpty:
  123. # continue
  124. # except asyncio.TimeoutError:
  125. # # 超时继续循环,避免永久阻塞
  126. # continue
  127. # except Exception as e:
  128. # print("socket报错",e)
  129. # break
  130. async def message_generator():
  131. """异步生成器,用于从队列中获取消息"""
  132. while True:
  133. try:
  134. # 使用asyncio.wait_for设置合理的超时时间
  135. message = await asyncio.wait_for(message_queue.get(), timeout=0.1)
  136. print("获取消息中",message)
  137. yield message
  138. except asyncio.TimeoutError:
  139. # 超时继续,允许其他协程运行
  140. await asyncio.sleep(0.01)
  141. # print("超时继续,允许其他协程运行")
  142. continue
  143. except Exception as e:
  144. print("消息生成器错误", e)
  145. break
  146. async def send_message(websocket):
  147. """使用异步生成器发送消息"""
  148. print("构建消息监听 send_message")
  149. async for message in message_generator():
  150. try:
  151. # 检查WebSocket连接状态
  152. if websocket.client_state.name != "CONNECTED":
  153. print("WebSocket连接已断开,停止发送消息")
  154. break
  155. print("发送消息中。。。。。")
  156. # 发送消息
  157. await websocket.send_json(message)
  158. message_queue.task_done()
  159. print("消息发送完成...")
  160. except Exception as e:
  161. print("socket报错", e)
  162. break
  163. async def MsgCallback(msg):
  164. msg_id = msg.get("msg_id")
  165. match msg_id:
  166. case "PhotoUpdated":
  167. PhotoFilename = msg.get("PhotoFilename")
  168. PhotoLocation = msg.get("PhotoLocation")
  169. PhotoOrigin = msg.get("PhotoOrigin")
  170. if (PhotoFilename != "" and PhotoFilename != None) and (
  171. PhotoLocation == "Local Disk"
  172. ):
  173. # temp_photo_name = PhotoFilename
  174. # 更新拍照记录
  175. print("PhotoFilename", PhotoFilename, PhotoOrigin)
  176. goods_art_no = None
  177. try:
  178. if PhotoOrigin != "" and PhotoOrigin not in ["external", "ui"]:
  179. goods_art_no, id = PhotoOrigin.split(",")
  180. # 创建任务来处理数据库更新,避免阻塞回调
  181. await updateDataRecord(PhotoFilename, id)
  182. except Exception as e:
  183. print("拍照更新异常", e)
  184. data = conn_manager.jsonMessage(
  185. code=0,
  186. msg=f"照片获取成功",
  187. data={
  188. "photo_file_name": PhotoFilename,
  189. "goods_art_no": goods_art_no,
  190. },
  191. msg_type="smart_shooter_photo_take",
  192. )
  193. await conn_manager.send_personal_message(data, smart_shooter.websocket)
  194. case "LiveviewUpdated":
  195. CameraLiveviewImage = msg.get("CameraLiveviewImage", None)
  196. # base64_to_image(CameraLiveviewImage, "liveview.jpg")
  197. # print("收到直播画面:CameraLiveviewImage")
  198. data = conn_manager.jsonMessage(
  199. code=1,
  200. msg=f"预览数据发送",
  201. data={"smart_shooter_preview": CameraLiveviewImage},
  202. msg_type="smart_shooter_enable_preview",
  203. )
  204. await conn_manager.send_personal_message(data, smart_shooter.websocket)
  205. # case _:
  206. # print("收到未知数据:{}".format(msg))
  207. # @app.on_event("startup")
  208. # async def startup_event():
  209. # loop = asyncio.get_event_loop()
  210. # loop.run_in_executor(None, await smart_shooter.connect_listen)
  211. # print("监听服务已启动")
  212. @app.on_event("shutdown")
  213. async def shutdown_event():
  214. print("Shutting down...")
  215. # socket_manager.close()
  216. # 清理操作
  217. for connection in list(active_connections):
  218. try:
  219. await connection.close()
  220. except Exception as e:
  221. print(f"Error closing connection: {e}")
  222. smart_shooter.stop_listen = True
  223. smart_shooter.is_init_while = False
  224. device_ctrl.close_connect()
  225. device_ctrl.close_lineConnect()
  226. device_ctrl.mcu_exit = True
  227. device_ctrl.p_list = []
  228. device_ctrl.temp_ports_dict = {}
  229. device_ctrl.clearMyInstance()
  230. diviceList = blue_tooth.devices
  231. if len(diviceList) == 0:
  232. blue_tooth.bluetooth_exit = True
  233. blue_tooth.clearMyInstance()
  234. diviceAddress = "" if len(list(diviceList.keys()))==0 else list(diviceList.keys())[0]
  235. if diviceAddress != "":
  236. print(diviceList.get(diviceAddress))
  237. diviceName = diviceList[diviceAddress]["name"]
  238. blue_tooth.disconnect_device(diviceAddress, diviceName)
  239. blue_tooth.bluetooth_exit = True
  240. blue_tooth.clearMyInstance()
  241. print("所有设备已断开连接")