socket_server.py 11 KB

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