socket_server.py 10 KB

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