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