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