浏览代码

refactor(mcu): 优化设备控制和通信功能

- 移除 sendSocketMessage 方法中的 msg_type 参数以简化接口
- 更新 config.ini 配置文件的格式和环境设置
- 在 DeviceControl 中添加时间戳到错误数据并优化消息类型处理
- 为 ProgramItem 类添加相机焦距距离配置功能
- 优化 socket_server 中的数据库查询逻辑和消息发送机制
- 重构 getActionInfo 函数以改进记录信息获取方式
- 添加调试输出选项到个人消息发送功能
rambo 3 周之前
父节点
当前提交
ebe647dbc1
共有 6 个文件被更改,包括 101 次插入80 次删除
  1. 15 15
      python/config.ini
  2. 2 5
      python/mcu/BaseClass.py
  3. 6 3
      python/mcu/DeviceControl.py
  4. 40 29
      python/mcu/ProgramItem.py
  5. 10 6
      python/sockets/connect_manager.py
  6. 28 22
      python/sockets/socket_server.py

+ 15 - 15
python/config.ini

@@ -1,31 +1,31 @@
 [app]
 # 应用名称
-app_name=智慧拍-后端应用
+app_name = 智慧拍-后端应用
 # 应用版本号
-version=1.0.0
+version = 1.0.0
 # 应用host地址
-host=127.0.0.1
+host = 192.168.31.246
 # 应用服务启动名称
-app_run=api:app
+app_run = api:app
 # 端口号
-port=7074
-debug=false
-env=prod
+port = 7074
+debug = false
+env = dev
 # 线程数
-works=1
-project=惠利玛
-is_upload=true
+works = 1
+project = 惠利玛
+is_upload = true
 [log]
 # 日志相关
-log_file_name=app.log
+log_file_name = app.log
 #最大字节数
-max_bytes=1024000
+max_bytes = 1024000
 #备份数量
-backup_counts=3
+backup_counts = 3
 # 地址
-hlm_host=https://dev2.pubdata.cn
+hlm_host = https://dev2.pubdata.cn
 
-project=红蜻蜓
+project = 红蜻蜓
 
 
 

+ 2 - 5
python/mcu/BaseClass.py

@@ -16,12 +16,9 @@ class BaseClass:
         # -1连接失败  0未连接 1连接中  2连接成功  3端口占用
         # self.device_status = 2
 
-    def sendSocketMessage(self, code=0, msg="", data=None, device_status=2, msg_type=None):
+    def sendSocketMessage(self, code=0, msg="", data=None, device_status=2):
         t_start = time.time()
-        if msg_type:
-            message_type = msg_type
-        else:
-            message_type = self.msg_type
+        message_type = self.msg_type
         payload = {
             "code": code,
             "msg": msg,

+ 6 - 3
python/mcu/DeviceControl.py

@@ -602,11 +602,14 @@ class DeviceControl(BaseClass, metaclass=SingletonType):
             else:
                 # print("设备异常数据打印:", data)
                 logger.info(f"115  设备异常数据打印:%{data}")
+                current_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())
                 msg_data = {
-                    "message": data
+                    "message": data,
+                    "current_time": current_time
                 }
-                self.sendSocketMessage(msg="设备信息打印", data=msg_data, device_status=2,
-                                       msg_type="print_mcu_error_data")
+                self.msg_type = "print_mcu_error_data"
+                self.sendSocketMessage(msg="设备信息打印", data=msg_data, device_status=2)
+                self.msg_type = "mcu"
         except BaseException as e:
             print("117 error {}".format(e))
             logger.info(f"117 error %{e}")

+ 40 - 29
python/mcu/ProgramItem.py

@@ -12,20 +12,21 @@ import logging
 
 logger = logging.getLogger(__name__)
 
+
 class ProgramItem(BaseClass):
     # program_sign = Signal(dict)
     # program_refresh_photo_list_sign = Signal()
 
     def __init__(
-        self,
-        websocket_manager,
-        action_data: any,
-        mcu,
-        goods_art_no: str = None,
-        image_index: int = -1,
-        record_id: int = -1,
-        smart_shooter=None,
-        is_get_mcu_state=True,
+            self,
+            websocket_manager,
+            action_data: any,
+            mcu,
+            goods_art_no: str = None,
+            image_index: int = -1,
+            record_id: int = -1,
+            smart_shooter=None,
+            is_get_mcu_state=True,
     ):
         super().__init__(BaseClass)
         # 1 表示等待中,2表示没有等待
@@ -61,6 +62,8 @@ class ProgramItem(BaseClass):
         self.camera_angle = float(self.get_value(action_data, "camera_angle", 0.0))
         self.af_times = self.get_value(action_data, "number_focus", 0)
         self.shoe_overturn = self.get_value(action_data, "shoe_upturn", False)
+        # 焦段距离
+        self.camera_focal_distance = self.get_value(action_data, "camera_focal_distance", 1)
         self.is_photograph = self.get_value(action_data, "take_picture", True)
         self.turntable_position = float(
             self.get_value(action_data, "turntable_position", 0.0)
@@ -188,6 +191,7 @@ class ProgramItem(BaseClass):
         print("\033[1;31m执行结束\033[0m", self.mcu.action_state)
         # await asyncio.sleep(0.1)
         # self.mcu.to_get_mcu_base_info()
+
     async def _do_camera_check(self):
         """执行一次完整的状态查询检测,返回是否全部停止"""
         self.mcu.send_get_all_info_to_mcu()
@@ -227,6 +231,7 @@ class ProgramItem(BaseClass):
                     logger.info("拍照前运动检测状态[失败],耗时%.1f秒", time.time() - _s)
                     return False
             await asyncio.sleep(0.2)
+
     async def run(self, total_len=5, *args):
         if total_len == 1:
             self.mode_type = "其他配置"
@@ -277,6 +282,8 @@ class ProgramItem(BaseClass):
                     device_name="turntable_steering", value=self.turntable_angle
                 )
                 time.sleep(0.1)
+            if self.camera_focal_distance is not None:
+                self.mcu.to_device_move(device_name="camera_zoom_motor", value=self.camera_focal_distance)
             loop = asyncio.get_event_loop()
             # self.mcu.send_all_cmd()
             loop.create_task(self.mcu.send_all_cmd())
@@ -287,7 +294,7 @@ class ProgramItem(BaseClass):
         #     return False
         start_time = time.time()
         current_time = time.time()
-        self.mcu.is_get_mcu_state = self.is_get_mcu_state 
+        self.mcu.is_get_mcu_state = self.is_get_mcu_state
         # ============连接MCU 处理步进电机与舵机等
         if self.is_move_device:
             if settings.IS_MCU:
@@ -307,8 +314,11 @@ class ProgramItem(BaseClass):
                 if self.shoe_overturn:
                     self.mcu.to_deal_device(device_name="overturn_steering")
                     await asyncio.sleep(0.001)
+                if self.camera_focal_distance is not None:
+                    # 移动距离
+                    self.mcu.to_device_move(device_name="camera_zoom_motor", value=self.camera_focal_distance)
                 if self.camera_height is not None:
-                    if (current_time - self.last_move_time)>110:
+                    if (current_time - self.last_move_time) > 110:
                         if self.camera_height == 0:
                             self.mcu.to_device_move(
                                 device_name="camera_high_motor", value=1
@@ -319,10 +329,10 @@ class ProgramItem(BaseClass):
                             )
                         else:
                             self.mcu.to_device_move(
-                                device_name="camera_high_motor", value=self.camera_height-1
+                                device_name="camera_high_motor", value=self.camera_height - 1
                             )
                         await asyncio.sleep(0.01)
-                        logger.info("设备延迟执行===>,%s",time.time())
+                        logger.info("设备延迟执行===>,%s", time.time())
                     self.mcu.to_device_move(
                         device_name="camera_high_motor", value=self.camera_height
                     )
@@ -333,17 +343,17 @@ class ProgramItem(BaseClass):
                         self.mcu.to_device_move(
                             device_name="camera_steering", value=-39.9
                         )
-                        logger.info("转盘位置首次运动===>,%s",-39.9)
+                        logger.info("转盘位置首次运动===>,%s", -39.9)
                     elif self.turntable_position == 40:
                         self.mcu.to_device_move(
                             device_name="camera_steering", value=39.9
                         )
-                        logger.info("转盘位置首次运动===>,%s",39.9)
+                        logger.info("转盘位置首次运动===>,%s", 39.9)
                     else:
                         self.mcu.to_device_move(
-                            device_name="camera_steering", value=self.camera_angle-0.1
+                            device_name="camera_steering", value=self.camera_angle - 0.1
                         )
-                        logger.info("转盘位置首次运动===>,%s",self.camera_angle-0.1)
+                        logger.info("转盘位置首次运动===>,%s", self.camera_angle - 0.1)
                     await asyncio.sleep(0.01)
                     self.mcu.to_device_move(
                         device_name="camera_steering", value=self.camera_angle
@@ -353,25 +363,25 @@ class ProgramItem(BaseClass):
                 if self.turntable_position is not None:
                     if self.turntable_position == 0:
                         self.mcu.to_device_move(
-                                device_name="turntable_position_motor", value=1
-                            )
-                        logger.info("转盘位置首次运动===>,%s",1)
+                            device_name="turntable_position_motor", value=1
+                        )
+                        logger.info("转盘位置首次运动===>,%s", 1)
                     elif self.turntable_position == 800:
                         self.mcu.to_device_move(
                             device_name="turntable_position_motor", value=799
                         )
-                        logger.info("转盘位置首次运动===>,%s",799)
+                        logger.info("转盘位置首次运动===>,%s", 799)
                     else:
                         self.mcu.to_device_move(
-                            device_name="turntable_position_motor", value=self.turntable_position-1
+                            device_name="turntable_position_motor", value=self.turntable_position - 1
                         )
-                        logger.info("转盘位置首次运动===>,%s",self.turntable_position-1)
+                        logger.info("转盘位置首次运动===>,%s", self.turntable_position - 1)
                     await asyncio.sleep(0.01)
                     self.mcu.to_device_move(
                         device_name="turntable_position_motor",
                         value=self.turntable_position,
                     )
-                    logger.info("转盘位置2次运动===>,%s",self.turntable_position)
+                    logger.info("转盘位置2次运动===>,%s", self.turntable_position)
                     await asyncio.sleep(0.01)
 
                 if self.turntable_angle is not None:
@@ -417,8 +427,8 @@ class ProgramItem(BaseClass):
                     "iso_config",
                     None,
                 )
-                print(" camera_configs p_item",camera_configs)
-                CameraKey = camera_configs[self.point_name].get("CameraKey",None)
+                print(" camera_configs p_item", camera_configs)
+                CameraKey = camera_configs[self.point_name].get("CameraKey", None)
                 print("smart shooter CameraShooter", record_id, goods_art_no, CameraKey)
                 await self.smart_shooter.CameraShooter(
                     msg_type="run_mcu",
@@ -440,7 +450,7 @@ class ProgramItem(BaseClass):
             await asyncio.sleep(self.after_delay_time)
         return True
 
-    async def RunSmartShooter(self, goods_art_no,record_id):
+    async def RunSmartShooter(self, goods_art_no, record_id):
         await asyncio.gather(
             self.smart_shooter.CameraShooter(
                 msg_type="run_mcu",
@@ -448,6 +458,7 @@ class ProgramItem(BaseClass):
                 id=record_id,
             ),
         )
+
     def digicam_take_picture(self):
         self.mcu.to_deal_device(device_name="buzzer", times=1)
         # 用于临时拍照计数
@@ -464,8 +475,8 @@ class ProgramItem(BaseClass):
         4、重新触发进行拍照,并更新最近拍照时间
         """
         if (
-            settings.getSysConfigs("other_configs", "running_mode", "普通模式")
-            == "普通模式"
+                settings.getSysConfigs("other_configs", "running_mode", "普通模式")
+                == "普通模式"
         ):
             return
 

+ 10 - 6
python/sockets/connect_manager.py

@@ -1,13 +1,16 @@
 from models import WebSocket
 from logger import logger
-import json, asyncio,time
+import json, asyncio, time
 from starlette.websockets import WebSocketState
+
+
 class ConnectionManager:
     is_connected = False
+
     def __init__(self):
         self.active_connections: list[WebSocket] = []
 
-    def jsonMessage(self, code=0, msg="", data: object = None,msg_type=""):
+    def jsonMessage(self, code=0, msg="", data: object = None, msg_type=""):
         """json字符串数据"""
         jsonData = {"code": code, "msg": msg, "data": data, "msg_type": msg_type}
         return jsonData
@@ -24,15 +27,16 @@ class ConnectionManager:
         self.active_connections.remove(websocket)
         logger.info("socket 连接断开")
 
-    async def send_personal_message(self, message: str, websocket: WebSocket):
+    async def send_personal_message(self, message: str, websocket: WebSocket, is_print=False):
         '''向用户发送消息'''
         # await websocket.send_json(message)
         t_send_start = time.time()
         try:
-            print(f"[T4: {time.time()-t_send_start:.4f}s] 开始 websocket.send_json")
+            print(f"[T4: {time.time() - t_send_start:.4f}s] 开始 websocket.send_json")
             await websocket.send_json(message)
-            await asyncio.sleep(0) 
-            # print(f"[T5: {time.time()-t_send_start:.4f}s] websocket.send_json 返回",message)
+            await asyncio.sleep(0)
+            if is_print:
+                print(f"[T5: {time.time() - t_send_start:.4f}s] websocket.send_json 返回", message)
         except Exception as e:
             logger.info(f"socket 消息发送异常:{str(e)}")
             await asyncio.sleep(0.001)

+ 28 - 22
python/sockets/socket_server.py

@@ -189,19 +189,22 @@ async def send_message(websocket):
             await asyncio.sleep(1)  # 防止死循环报错
 
 
-async def getActionInfo(record_info):
+async def getActionInfo(record_id):
     await asyncio.sleep(0.01)
-    if not record_info:
-        return None
-    action_id = record_info.action_id
-    if not action_id:
+    if not record_id:
         return None
     session = SqlQuery()
+    record_model = CRUD(PhotoRecord)
+    record_data = record_model.read(session, conditions={"id": record_id, "delete_time": None})
+    if not record_data:
+        session.close()
+        return None
     device_model = CRUD(DeviceConfig)
-    model = device_model.read(session, conditions={"id": action_id})
+    model = device_model.read(session, conditions={"id": record_data.action_id})
     if not model:
         session.close()
         return None
+    session.close()
     return model
 
 
@@ -223,25 +226,28 @@ async def MsgCallback(msg):
                 try:
                     if PhotoOrigin != "" and PhotoOrigin not in ["external", "ui"]:
                         goods_art_no, id = PhotoOrigin.split(",")
-                    # 创建任务来处理数据库更新,避免阻塞回调
-                    recordResult = await updateDataRecord(PhotoFilename, id)
-                except Exception as e:
-                    print("拍照更新异常", e)
-                    recordResult = None
-                actionModel = None
-                if recordResult:
-                    actionModel = await getActionInfo(recordResult)
-                data = conn_manager.jsonMessage(
-                    code=0,
-                    msg=f"照片获取成功",
-                    data={
+                        print("PhotoUpdated", goods_art_no, id)
+                        # 创建任务来处理数据库更新,避免阻塞回调
+                        await updateDataRecord(PhotoFilename, id)
+                    actionModel = None
+                    if id:
+                        actionModel = await getActionInfo(id)
+                    print("准备发送message_data", actionModel)
+                    message_data = {
                         "photo_file_name": PhotoFilename,
                         "goods_art_no": goods_art_no,
                         "action_name": actionModel.action_name if actionModel else None,
-                    },
-                    msg_type="smart_shooter_photo_take",
-                )
-                await conn_manager.send_personal_message(data, smart_shooter.websocket)
+                    }
+                    print("smart_shooter_photo_take message_data", message_data)
+                    data = conn_manager.jsonMessage(
+                        code=0,
+                        msg=f"照片获取成功",
+                        data=message_data,
+                        msg_type="smart_shooter_photo_take",
+                    )
+                    await conn_manager.send_personal_message(data, smart_shooter.websocket, is_print=True)
+                except Exception as e:
+                    print("拍照更新异常", e)
         case "LiveviewUpdated":
             CameraLiveviewImage = msg.get("CameraLiveviewImage", None)
             # base64_to_image(CameraLiveviewImage, "liveview.jpg")