瀏覽代碼

连接问题

rambo 4 月之前
父節點
當前提交
e87b4a879e

+ 101 - 41
python/mcu/DeviceControl.py

@@ -1,5 +1,6 @@
 import asyncio
 import datetime
+from cv2 import log
 import serial.tools.list_ports
 import time, json
 from .SerialIns import SerialIns
@@ -17,7 +18,9 @@ from .OtherSet import OtherSet
 from .DebugUart import DebugUart
 from .LineControl import LineControl
 import copy
+import logging
 from mcu.capture.smart_shooter_class import SmartShooter
+logger = logging.getLogger(__name__)
 # mcu命令
 class DeviceControl(BaseClass, metaclass=SingletonType):
     lock = threading.Lock()
@@ -130,6 +133,7 @@ class DeviceControl(BaseClass, metaclass=SingletonType):
         await asyncio.sleep(0.01)
         for k, v in data.items():
             print("k:{},v:{}".format(k, v))
+            logger.info("k:{},v:{}".format(k, v))
             data[k] = self.setOtherMaxMinValue(k, v)
         self.set_to_mcu_other_info(data)
         self.msg_type = "set_other_mcu_info"
@@ -174,11 +178,13 @@ class DeviceControl(BaseClass, metaclass=SingletonType):
             return False
         if self.init_state ==True:
             print("已经初始化过,请勿重复初始化")
+            logger.info("已经初始化过,请勿重复初始化")
             self.sendSocketMessage(msg="设备初始化完成", device_status=2)
             return False
         self.serial_ins.clearn_flush()
         self.to_init_device_origin_point(device_name="mcu",is_force=is_force)
         print("MCU 开始循环~")
+        logger.info("MCU 开始循环~")
         while 1:
             await asyncio.sleep(1)
             if not self.serial_ins or not self.connect_state:
@@ -198,12 +204,15 @@ class DeviceControl(BaseClass, metaclass=SingletonType):
                 # self.close_other_window()
             except BaseException as e:
                 print("121231298908", e)
+                logger.info("121231298908", e)
                 break
 
         self.is_running = False
         self.connect_state = False
         print("MCU 循环退出~")
+        logger.info("MCU 循环退出~")
         print("串口未连接,请检查")
+        logger.info("串口未连接,请检查")
         self.sendSocketMessage(
             code=1, msg="MCU串口未连接,请检查", device_status=-1
         )
@@ -319,9 +328,11 @@ class DeviceControl(BaseClass, metaclass=SingletonType):
             # if self.serial_ins:
             #     self.serial_ins.write_cmd(data)
             print("发送获取偏移量")
+            logger.info("发送获取偏移量")
         except Exception as e:
             print(e)
             print("getDeviationInfo", "暂未获取到self.command")
+            logger.info("getDeviationInfo暂未获取到self.command")
 
     def set_deviation(self, device_name, _type=0, deviation=0):
         # turntable----0 angle_ratio   1 turntable_steering_deviation
@@ -381,11 +392,13 @@ class DeviceControl(BaseClass, metaclass=SingletonType):
         data = [self.command["get_other_info"], 1]
         self.add_send_data_queue(data)
         print("发送获取其他信息")
+        logger.info("发送获取其他信息")
 
     def add_send_data_queue(self, data):
         self.lock.acquire()
         if self.serial_ins:
             print("send_data_queue  append  :{}".format(data))
+            logger.info("send_data_queue  append  %s",data)
             self.send_data_queue.append(data)
         self.lock.release()
     async def send_all_cmd(self):
@@ -423,8 +436,10 @@ class DeviceControl(BaseClass, metaclass=SingletonType):
                 self.init_state = True
                 self.sendSocketMessage(msg=data, device_status=2)
             print("115  print_mcu_error_data:", data)
+            logger.info("115  print_mcu_error_data:%s", data)
         except BaseException as e:
             print("117 error {}".format(e))
+            logger.info("117 error %s",e)
         return
 
     def get_from_mcu_move_respond_data(self, receive_data):
@@ -442,6 +457,7 @@ class DeviceControl(BaseClass, metaclass=SingletonType):
         message = {"type": "connect_sign", "data": connect_flag}
         self.sendSocketMessage(msg="接收链接信息", data=message)
         print("接收链接信息")
+        logger.info("接收链接信息")
         return
 
     def to_init_device_origin_point(self, device_name, is_force=False):
@@ -512,6 +528,7 @@ class DeviceControl(BaseClass, metaclass=SingletonType):
         receive_data = self.serial_ins.read_cmd(out_time=1)
         if receive_data is False:
             print("------------------------------------------------4657564654")
+            logger.info("------------------------------------------------4657564654")
             self.connect_state = False
             return False
         if not receive_data:
@@ -651,6 +668,7 @@ class DeviceControl(BaseClass, metaclass=SingletonType):
             self.sendSocketMessage(msg="接收偏移量信息", data=get_deviation_data)
             self.msg_type = "mcu"
             print("接收偏移量信息")
+            logger.info("接收偏移量信息")
         return
 
     def initDeviationInfo(self, get_deviation_data):
@@ -748,6 +766,7 @@ class DeviceControl(BaseClass, metaclass=SingletonType):
         self.last_mcu_other_info_data["num"] += 1
         for k, v in self.last_mcu_other_info_data["data"].items():
             print("k:{},v:{}".format(k, v))
+            logger.info("k:%s,v:%s",k, v)
         self.msg_type = "get_mcu_other_info"
         self.sendSocketMessage(
             code=0,
@@ -859,6 +878,7 @@ class DeviceControl(BaseClass, metaclass=SingletonType):
             if self.mcu_move_state == 2:
                 self.is_just_init_time = True
                 print("is_just_init_time")
+                logger.info("设备初始化完成")
                 message = {
                     "_type": "is_just_init_time",
                     "plugins_mode": "mcu",
@@ -897,6 +917,7 @@ class DeviceControl(BaseClass, metaclass=SingletonType):
     def remove_port(self, port_name):
         """移除串口"""
         print("remove", port_name)
+        logger.info("串口被移除")
         data = {
             "_type": "remove_port",
             "plugins_mode": "auto_select_com",
@@ -908,19 +929,11 @@ class DeviceControl(BaseClass, metaclass=SingletonType):
         # port_value :串口基础信息
         # todo 根据prot_value 信息自动进行连接
         print("add port_name", port_name)
+        logger.info("add port_name %s", port_name)
         print("self.port_name",self.port_name)
+        logger.info("self.port_name %s", self.port_name)
         if self.port_name == port_name:
-            self.sendSocketMessage(
-                0,
-                msg="串口:{} 无法识别,调试".format(port_name).format(port_name),
-                data=message_data,
-                device_status=2,
-            )
-            self.connect_state = True
-            self.is_running = True
-            print("MCU 已连接")
-            self.port_name = port_name
-            return True
+            return False
         # 对没有连接的设备进行尝试连接
         message_data = {
             "_type": "show_info",
@@ -951,15 +964,18 @@ class DeviceControl(BaseClass, metaclass=SingletonType):
                 device_status=-1,
             )
             print("串口:{} 被占用".format(port_name))
+            logger.info("串口:%s 被占用",port_name)
             return False
 
         await asyncio.sleep(2)
         print("开始发送命令")
+        logger.info("开始发送命令")
         data = [90, 1]
         try:
             serial_handle.flushInput()  # 尝试重置输入缓冲区
         except serial.SerialTimeoutException:
             print("超时错误:无法在规定时间内重置输入缓冲区。")
+            logger.info("超时错误:无法在规定时间内重置输入缓冲区。")
             self.sendSocketMessage(
                 1,
                 msg="超时错误:无法在规定时间内重置输入缓冲区。",
@@ -968,7 +984,7 @@ class DeviceControl(BaseClass, metaclass=SingletonType):
             serial_handle.close()
             return False
         print("尝试写入数据")
-
+        logger.info("尝试写入数据")
         buf = bytearray(b"")
         buf.extend([0x55, 0x55, (0xFF & len(data))])
         buf.extend(data)
@@ -978,27 +994,34 @@ class DeviceControl(BaseClass, metaclass=SingletonType):
             serial_handle.write(buf)
         except serial.SerialTimeoutException:
             print("写入数据错误")
+            logger.info("写入数据错误")
             serial_handle.close()
             return False
 
         await asyncio.sleep(0.3)
         receive_data = self.read_cmd(serial_handle)
         print("尝试接收命令", receive_data)
+        logger.info("尝试接收命令,%s", receive_data)
         device_id = 0
 
         if receive_data:
             print("receive_data", receive_data)
+            logger.info("receive_data %s", receive_data)
             if receive_data[0] == 90:
                 connect_flag = receive_data[1]
                 device_id = receive_data[2]
 
         print("关闭串口:{}".format(port_name))
+        logger.info("关闭串口:%s",port_name)
         serial_handle.close()
         loop = asyncio.get_event_loop()
         print("device_id============>>>", device_id)
+        logger.info("device_id============>>>%s", device_id)
         if device_id > 0:
             if device_id == 1:
-                await self.to_connect_com(port_name)
+                state,_=self.to_connect_com(port_name)
+                if not state:
+                    return False
                 message_data = {
                     "_type": "show_info",
                     "plugins_mode": "auto_select_com",
@@ -1016,20 +1039,16 @@ class DeviceControl(BaseClass, metaclass=SingletonType):
                         "port_name": port_name,
                     },
                 }
-                self.sendSocketMessage(
-                    msg="MCU连接成功", data=message_data, device_status=2
-                )
-                await asyncio.sleep(2)
-                # 异步处理
-                loop.create_task(self.initDevice(),name="initDevice")
+                return True
             elif device_id == 2:
                 # 有线接收器
                 self.connected_ports_dict[port_name] = "Line_Control"
                 print("device_id", device_id)
-                loop.create_task(
-                    self.line_control.to_connect_com(port_name),
-                    name="line_control_to_connect_com",
-                )
+                logger.info("device_id %s", device_id)
+                state = await self.line_control.to_connect_com(port_name)
+                if not state:
+                    return False
+                return True
                 # message_data = {
                 #     "_type": "show_info",
                 #     "plugins_mode": "auto_select_com",
@@ -1058,9 +1077,10 @@ class DeviceControl(BaseClass, metaclass=SingletonType):
             #         # 异步循环获取设备信息
             #         self.to_get_mcu_base_info()
             # asyncio.gather(getBaseInfo())
-            return True
+
         else:
             print("串口无法识别")
+            logger.info("串口无法识别")
             self.sendSocketMessage(
                 code=1,
                 msg="串口无法识别,请重新插拔拍照机USB", data=message_data, device_status=-1
@@ -1074,11 +1094,12 @@ class DeviceControl(BaseClass, metaclass=SingletonType):
         # 连接不上,记录为其他列表
     def clearMyInstance(self):
         SingletonType.clear_instance()
-    async def to_connect_com(self, port_name):
+    def to_connect_com(self, port_name):
         # 关闭串口
         print("to_connect_com", port_name)
+        logger.info("to_connect_com %s", port_name)
         self.close_connect()
-        await asyncio.sleep(0.3)
+        time.sleep(0.3)
         self.connect_state = False
         try:
             self.serial_ins = SerialIns(port_name=port_name, baud=115200, timeout=0.1)
@@ -1118,17 +1139,24 @@ class DeviceControl(BaseClass, metaclass=SingletonType):
         cmd = 90
         data = [cmd, 1]
         print("405  发送 连接请求  -----------------------------------------")
+        logger.info("405  发送 连接请求  -----------------------------------------")
         print(self.serial_ins)
+        logger.info(self.serial_ins)
         # self.serial_ins.clearn_flush()
         self.serial_ins.write_cmd(data)
 
         # 延迟接收数据
-        await asyncio.sleep(0.3)
+        time.sleep(0.3)
         receive_data = self.serial_ins.read_cmd(out_time=1)
         if receive_data:
             print(
                 "409  receive_data--90:{}".format(self.change_hex_to_int(receive_data))
             )
+            logger.info(
+                "409  receive_data--90:%s",str(self.change_hex_to_int(receive_data))
+            )
+        else:
+            return False, None
         if receive_data:
             # receive_data[2]=1 表示为MCU设备编号
             if receive_data[0] == 90 and receive_data[2] == 1:
@@ -1141,6 +1169,7 @@ class DeviceControl(BaseClass, metaclass=SingletonType):
                 except:
                     mcu_has_been_set = 99  # 未知状态
                 print("MCU初始化信息{}".format(mcu_has_been_set))
+                logger.info("MCU初始化信息%s",str(mcu_has_been_set))
                 message_data = {
                     "_type": "show_info",
                     "plugins_mode": "mcu",
@@ -1152,10 +1181,25 @@ class DeviceControl(BaseClass, metaclass=SingletonType):
                 self.connect_state = True
                 self.is_running = True
                 print("MCU 已连接")
+                logger.info("MCU 已连接")
                 self.port_name = port_name
-                return
-
+                # time.sleep(2)
+                loop = asyncio.get_event_loop()
+                # # 异步处理
+                loop.create_task(self.initDevice(), name="initDevice")
+                return True, None
         print("MCU 连接失败")
+        logger.info("MCU 连接失败")
+        for port in self.p_list:
+            logger.info(
+                "MCU 连接失败处理list移除操作,self port name %s,p_list:%s",
+                port_name,
+                self.p_list,
+            )
+            if port == port_name:
+                logger.info("MCU 连接失败处理list移除操作,移除 %s", port_name)
+                self.p_list.remove(port)
+                self.remove_port(port)
         message_data = {
             "_type": "show_info",
             "plugins_mode": "mcu",
@@ -1163,6 +1207,7 @@ class DeviceControl(BaseClass, metaclass=SingletonType):
         }
         self.sendSocketMessage(msg="MCU 连接失败", data=message_data, device_status=-1)
         self.close_connect()
+        return False, None
 
     def close_connect(self):
         self.port_name = ""
@@ -1174,8 +1219,8 @@ class DeviceControl(BaseClass, metaclass=SingletonType):
             # self.p_list = []
             # self.temp_ports_dict = {}
             self.init_state = False
-            self.is_init_while = False
             print("关闭MCU")
+            logger.info("关闭MCU")
         self.line_control.port_name = ""
         self.line_control.close_connect()
 
@@ -1246,6 +1291,7 @@ class DeviceControl(BaseClass, metaclass=SingletonType):
         此处输入单位为 毫米,以及度  需要先缩小,再放大
         """
         print("移动",time.time())
+        logger.info("移动,%s",time.time())
         speed = settings.moveSpeed()
 
         cmd = 1
@@ -1254,6 +1300,7 @@ class DeviceControl(BaseClass, metaclass=SingletonType):
         #     print("F非MCU设备,禁止处理")
         #     return
         print("正在执行",device_name)
+        logger.info("正在执行 %s",device_name)
         match device_name:
             case "camera_high_motor":
                 # value 单位毫米
@@ -1321,6 +1368,7 @@ class DeviceControl(BaseClass, metaclass=SingletonType):
 
         value = int(abs(value * 10))  # 此处value赋值后,单位为mm以及0.1度
         print("准备执行",device_name, value)
+        logger.info("准备执行,%s %s",device_name, value)
         data = [
             cmd,
             device_id,
@@ -1362,6 +1410,7 @@ class DeviceControl(BaseClass, metaclass=SingletonType):
     def check_before_action(self):
         if self.state != 2:
             print("check_before_action 设备正在运行中~")
+            logger.info("check_before_action 设备正在运行中~")
             self.sendSocketMessage(
                 code=1, msg="设备正在运行中", device_status=1
             )
@@ -1390,6 +1439,7 @@ class DeviceControl(BaseClass, metaclass=SingletonType):
         _is_debug = 1 if settings.IS_DEBUG == "true" else 0
         is_deviation = 0 if settings.IS_DEBUG == "true" else 1
         print("控制设备==>_is_debug", _is_debug)
+        logger.info("控制设备==>_is_debug %s", _is_debug)
         match device_name:
             case "camera_high_motor":
                 # 相机电机
@@ -1458,6 +1508,7 @@ class DeviceControl(BaseClass, metaclass=SingletonType):
             #     self.photograph(goods_art_no=None)
     def checkDevice(self):
         print("检查设备是否运行中")
+        logger.info("检查设备是否运行中")
         if not self.is_running:
             self.sendSocketMessage(
                 code=1, msg="mcu设备未连接,请先连接设备", device_status=0
@@ -1535,6 +1586,7 @@ class DeviceControl(BaseClass, metaclass=SingletonType):
                 # await asyncio.sleep(0.01)
                 if self.is_stop_action == True:
                     print("停止命令接收,立即终止")
+                    logger.info("停止命令接收,立即终止")
                     break
                 # action_is_take_picture = action["take_picture"]
                 record_id = action["record_id"]
@@ -1555,6 +1607,7 @@ class DeviceControl(BaseClass, metaclass=SingletonType):
                 if self.action_state != 1:
                     # 异常终止
                     print("action异常终止")
+                    logger.info("action异常终止")
                     break
                 self.msg_type = "photo_take"
                 if not await program_item.run(total_len):
@@ -1616,6 +1669,7 @@ class DeviceControl(BaseClass, metaclass=SingletonType):
         if self.checkDevice() == False:
             return
         print("检查完成", config_info)
+        logger.info("检查完成 %s", config_info)
         if config_info:
             self.action_state = 1
             self.msg_type = "mcu"
@@ -1631,6 +1685,7 @@ class DeviceControl(BaseClass, metaclass=SingletonType):
             if self.action_state != 1:
                 # 异常终止
                 print("action异常终止")
+                logger.info("action异常终止")
                 return
             self.msg_type = "photo_take"
             program_item.smart_shooter = smart_shooter
@@ -1658,8 +1713,10 @@ class DeviceControl(BaseClass, metaclass=SingletonType):
     async def only_take_photo(self, goods_art_no, image_index, record_id):
         await asyncio.sleep(0.1)
         print("only_take_photo=====>",goods_art_no, image_index, record_id)
+        logger.info("only_take_photo=====> %s %s %s",goods_art_no, image_index, record_id)
         if goods_art_no == "":
             print("only_take_photo 数据查询异常")
+            logger.info("only_take_photo 数据查询异常")
             return
         # 关闭led
         self.controlDevice("laser_position", 0)
@@ -1686,12 +1743,12 @@ async def checkMcuConnection(device_ctrl: DeviceControl):
         device_ctrl.device_status = 2
         device_ctrl.sendSocketMessage(code=0, msg="MCU连接成功", data=message)
         return
-    if device_ctrl.is_init_while:
-        device_ctrl.sendSocketMessage(
-            code=0, msg="MCU<<<---连接成功--->>>,is_init_while", data=message
-        )
-        return
-    device_ctrl.is_init_while = True
+    # if device_ctrl.is_init_while == True:
+    #     device_ctrl.sendSocketMessage(
+    #         code=0, msg="MCU<<<---连接成功--->>>,is_init_while", data={}
+    #     )
+    #     return
+    # device_ctrl.is_init_while = True
     """实时检测串口是否连接"""
     while True:
         await asyncio.sleep(1)
@@ -1699,7 +1756,8 @@ async def checkMcuConnection(device_ctrl: DeviceControl):
             break
         ports_dict = device_ctrl.scan_serial_port()
         device_ctrl.temp_ports_dict = ports_dict
-        print("device_ctrl.p_list", device_ctrl.p_list)
+        # print("device_ctrl.p_list", device_ctrl.p_list)
+        # logger.info("device_ctrl.p_list %s", device_ctrl.p_list)
         if not ports_dict:
             # 全部清空 移除所有串口
             if device_ctrl.p_list:
@@ -1715,17 +1773,19 @@ async def checkMcuConnection(device_ctrl: DeviceControl):
                 if _port_name not in device_ctrl.p_list:
                     try:
                         flag = await device_ctrl.add_port_by_linkage(_port_name)
-                        if flag == False:
+                        if not flag:
                             continue
                         device_ctrl.p_list.append(_port_name)
                     except BaseException as e:
                         print("串口不存在{} {}".format(_port_name, e))
+                        logger.info("串口不存在{} {}".format(_port_name, e))
         # if not device_ctrl.connect_state:
         #     print("串口未连接,请检查")
         #     device_ctrl.sendSocketMessage(
         #         code=1, msg="串口未连接,请检查", device_status=-1
         #     )
-    device_ctrl.is_init_while = False
-    device_ctrl.p_list = []
-    device_ctrl.temp_ports_dict = {}
+    # device_ctrl.is_init_while = False
+    # device_ctrl.p_list = []
+    # device_ctrl.temp_ports_dict = {}
     print("MCU断开连接,已释放")
+    logger.info("MCU断开连接,已释放")

+ 2 - 0
python/mcu/LineControl.py

@@ -25,6 +25,7 @@ class LineControl(BaseClass):
         self.photo_take_state = 0
 
     async def to_connect_com(self, port_name):
+        self.port_name = port_name
         self.close_connect()
         await asyncio.sleep(0.5)
         try:
@@ -60,6 +61,7 @@ class LineControl(BaseClass):
                 )
                 self.serial_ins = None
                 self.connect_state = False
+                return False
         except:
             message = {
                 "_type": "show_info",

+ 3 - 0
python/mcu/SerialIns.py

@@ -1,7 +1,9 @@
 #!usr/bin/python3
 import serial.tools.list_ports
 import time
+import logging
 
+logger = logging.getLogger(__name__)
 
 # https://blog.csdn.net/weixin_44289254/article/details/121583562
 
@@ -67,6 +69,7 @@ class SerialIns(object):
             buf.extend([0xFF & ~sum(data)])
             # 55 55 02 5a 01 a4
             print("send buf  {}".format(self.change_hex_to_int(buf)))
+            logger.info("正在发送命令======>>>>> send buf  %s", self.change_hex_to_int(buf))
             try:
                 self.serial_handle.write(buf)
                 return True

+ 7 - 2
python/mcu/capture/smart_shooter_class.py

@@ -9,7 +9,9 @@ import base64
 import zmq, sys, time
 from utils.SingletonType import SingletonType
 
+import logging
 
+logger = logging.getLogger(__name__)
 # 定义为单例模式,避免被重复实例化
 class SmartShooter(metaclass=SingletonType):
     SET_REQ = "tcp://127.0.0.1:54544"
@@ -26,7 +28,7 @@ class SmartShooter(metaclass=SingletonType):
         # 实时预览状态
         self.perview_state = False
         self.callback_listen = None
-        self.listen_init = False
+        self.listen_init = None
         self.websocket = None
         # loop = asyncio.get_event_loop()
         # loop.create_task(
@@ -379,13 +381,13 @@ class SmartShooter(metaclass=SingletonType):
             return False, msg_send
 
     def connect_listen(self):
-        time.sleep(5)
         print("smart shooter connect_listen", self.connect_status, self.listen_init)
         if self.connect_status == True or self.listen_init == True:
             return True
         # 发起监听
         sub_socket, context = self.__create_listen()
         print("构建监听", self.connect_status)
+        logger.info("构建监听,%s", self.connect_status)
         while True:
             self.listen_init = True
             if self.callback_listen == None:
@@ -408,12 +410,15 @@ class SmartShooter(metaclass=SingletonType):
                 asyncio.run(self.callback_listen(json_msg))
             except zmq.Again:
                 print("接收超时,继续监听...")
+                logger.info("接收超时,继续监听...")
                 continue
             except Exception as e:
                 self.connect_status = False
                 print(f"发生错误: {e}")
                 break
         self.listen_init = False
+        self.connect_status = False
+        self.stop_listen = False
         sub_socket.close()
         context.term()
         print("smart shooter连接断开")

+ 56 - 12
python/sockets/socket_server.py

@@ -43,19 +43,20 @@ async def websocket_endpoint(websocket: WebSocket):
     smart_shooter.websocket = websocket
 
     # 启动 smart_shooter.connect_listen 服务
+    listen_task = None
     tasks = set()
     try:
-        # 创建任务来启动 connect_listen
-        listen_task = asyncio.get_event_loop().run_in_executor(
-            None, smart_shooter.connect_listen
-        )
-
+        # 初始化回调函数
+        smart_shooter.callback_listen = MsgCallback
         # 创建任务来并发处理不同类型的消息
         handler_task = asyncio.create_task(handler_messages(websocket))
         send_task = asyncio.create_task(send_message(websocket))
-
+        loop = asyncio.get_event_loop()
+        listen_task = loop.run_in_executor(None, smart_shooter.connect_listen)
+        # 创建任务来启动 connect_listen
+        # listen_task = asyncio.create_task(restart_smart_shooter_listener())
         # 等待所有任务完成
-        await asyncio.gather(listen_task, handler_task, send_task)
+        await asyncio.gather(handler_task, send_task, listen_task)
 
     except WebSocketDisconnect:
         print("Client disconnected")
@@ -66,12 +67,35 @@ async def websocket_endpoint(websocket: WebSocket):
         active_connections.discard(websocket)
 
 
+async def restart_smart_shooter_listener():
+    """重启smart shooter监听器"""
+    loop = asyncio.get_event_loop()
+    if not hasattr(smart_shooter, "_listen_tasks"):
+        smart_shooter._listen_tasks = set()
+    while True:
+        if getattr(smart_shooter, "listen_init", False):
+            print("listen_init=====>", getattr(smart_shooter, "listen_init", False))
+            break
+        listen_task = loop.run_in_executor(None, smart_shooter.connect_listen)
+        smart_shooter._listen_tasks.add(listen_task)
+        # if smart_shooter.listen_init == False:
+        #     break
+        try:
+            await listen_task
+            # 正常结束后等待重启
+            await asyncio.sleep(1)
+        except Exception as e:
+            await asyncio.sleep(1)
+        finally:
+            smart_shooter._listen_tasks.discard(listen_task)
+
+
 async def start_smart_shooter_listen():
     """启动 smart_shooter 监听服务"""
     loop = asyncio.get_event_loop()
     # 在执行器中运行 connect_listen 方法
     try:
-        await loop.run_in_executor(None, smart_shooter.connect_listen())
+        loop.create_task(None, smart_shooter.connect_listen())
     except Exception as e:
         print(f"Smart shooter listen error: {e}")
 
@@ -94,7 +118,11 @@ async def handler_messages(websocket):
                     blue_tooth.bluetooth_exit = True
                     blue_tooth.clearMyInstance()
                     break
-                diviceAddress = list(diviceList.keys())[0]
+                diviceAddress = (
+                    ""
+                    if len(list(diviceList.keys())) == 0
+                    else list(diviceList.keys())[0]
+                )
                 if diviceAddress != "":
                     print(diviceList.get(diviceAddress))
                     diviceName = diviceList[diviceAddress]["name"]
@@ -166,9 +194,6 @@ async def MsgCallback(msg):
             await conn_manager.send_personal_message(data, smart_shooter.websocket)
 
 
-# 初始化回调函数
-smart_shooter.callback_listen = MsgCallback
-
 # @app.on_event("startup")
 # async def startup_event():
 #     loop = asyncio.get_event_loop()
@@ -186,3 +211,22 @@ async def shutdown_event():
             await connection.close()
         except Exception as e:
             print(f"Error closing connection: {e}")
+    smart_shooter.stop_listen = True
+    smart_shooter.is_init_while = False
+    device_ctrl.close_connect()
+    device_ctrl.mcu_exit = True
+    device_ctrl.p_list = []
+    device_ctrl.temp_ports_dict = {}
+    device_ctrl.clearMyInstance()
+    diviceList = blue_tooth.devices
+    if len(diviceList) == 0:
+        blue_tooth.bluetooth_exit = True
+        blue_tooth.clearMyInstance()
+    diviceAddress = "" if len(list(diviceList.keys()))==0 else list(diviceList.keys())[0]
+    if diviceAddress != "":
+        print(diviceList.get(diviceAddress))
+        diviceName = diviceList[diviceAddress]["name"]
+        blue_tooth.disconnect_device(diviceAddress, diviceName)
+    blue_tooth.bluetooth_exit = True
+    blue_tooth.clearMyInstance()
+    print("所有设备已断开连接")