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