socket_server.py 11 KB

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