socket_server.py 10 KB

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