Kaynağa Gözat

主图生成流程

rambo 7 ay önce
ebeveyn
işleme
83b3eacb34

+ 1 - 1
python/api.py

@@ -568,7 +568,7 @@ def save_sys_configs(params: SysConfigParams):
 
 
 @app.post("/create_main_image", description="创建主图测试")
-def save_sys_configs(params: MaineImageTest):
+def create_main_image(params: MaineImageTest):
     file_path = params.file_path
     onePic = OnePicTest(pic_path=file_path)
     # session = SqlQuery()

+ 2 - 2
python/databases.py

@@ -142,8 +142,8 @@ class CRUD:
     def update(self, session: Session, obj_id: int, **kwargs):
         db_obj = session.get(self.model, obj_id)
         for key, value in kwargs.items():
-            if value == None or value == "":
-                continue
+            # if value == None or value == "":
+            #     continue
             setattr(db_obj, key, value)
         session.commit()
         session.refresh(db_obj)

+ 9 - 0
python/mcu/BlueToothMode.py

@@ -22,6 +22,7 @@ class BlueToothMode(BaseClass,metaclass=SingletonType):
         else:
             self.init_flag = True
         self.msg_type = "blue_tooth"
+        self.bluetooth_exit = False
         self.remote_control_v2 = RemoteControlV2(self, websocket_manager)
         # 用于存储找到的目标设备的地址
         self.target_device_address = None
@@ -241,15 +242,23 @@ class BlueToothMode(BaseClass,metaclass=SingletonType):
         await self.scan_for_esp32()
         # 定期重新扫描以发现新设备
         while True:
+            print("正在扫描设备...")
+            if self.bluetooth_exit:
+                break
             if self.devices:
                 await asyncio.sleep(20)
             else:
                 await asyncio.sleep(3)
             await self.scan_for_esp32()
+        print("蓝牙断开连接,已释放")
     def run(self):
         self.print_error("开启蓝牙扫描")
         asyncio.run(self.main_func())
 
+    def clearMyInstance(self):
+        print("清除蓝牙实例...")
+        SingletonType.clear_instance()
+
     def write_cmd(self, address, data: list):
         buf = []
         buf.extend([0x55, 0x55, (0xFF & len(data))])

+ 7 - 3
python/mcu/DeviceControl.py

@@ -41,6 +41,7 @@ class DeviceControl(BaseClass, metaclass=SingletonType):
         self.camera_motor_value = 0
         self.init_state = False
         self.port_name = ""
+        self.mcu_exit = False
         self.t_n = 0
         self.serial_ins = None
         self.connected_ports_dict = {}  # 已连接的ports
@@ -960,7 +961,8 @@ class DeviceControl(BaseClass, metaclass=SingletonType):
         # 正常跳过;记录为其他列表
         # 不正常进行尝试连接
         # 连接不上,记录为其他列表
-
+    def clearMyInstance(self):
+        SingletonType.clear_instance()
     def to_connect_com(self, port_name):
         # 关闭串口
         print("to_connect_com", port_name)
@@ -1447,7 +1449,7 @@ class DeviceControl(BaseClass, metaclass=SingletonType):
             self.msg_type = "mcu"
             self.controlDevice("laser_position", 1)
 
-    async def run_mcu_config_single(self, config_info, goods_art_no,msg_type="run_mcu_single_finish"):
+    async def run_mcu_config_single(self, config_info, goods_art_no,msg_type="run_mcu_single_finish",image_index=-1):
         '''独立拍照  仅作测试用'''
         if self.checkDevice() == False:
             return
@@ -1455,7 +1457,6 @@ class DeviceControl(BaseClass, metaclass=SingletonType):
             self.action_state = 1
             self.msg_type = "mcu"
             await asyncio.sleep(0.1)
-            image_index = -1
             program_item = ProgramItem(
                     websocket_manager=self.websocket_manager,
                     action_data=config_info,
@@ -1510,6 +1511,8 @@ async def checkMcuConnection(device_ctrl: DeviceControl):
     """实时检测串口是否连接"""
     while True:
         await asyncio.sleep(0.5)
+        if device_ctrl.mcu_exit:
+            break
         ports_dict = device_ctrl.scan_serial_port()
         device_ctrl.temp_ports_dict = ports_dict
         if not ports_dict:
@@ -1532,3 +1535,4 @@ async def checkMcuConnection(device_ctrl: DeviceControl):
                         device_ctrl.add_port_by_linkage(_port_name)
                     except BaseException as e:
                         print("串口不存在{} {}".format(_port_name, e))
+    print("MCU断开连接,已释放")

+ 43 - 18
python/mcu/capture/module_watch_dog.py

@@ -6,7 +6,10 @@ import os
 from utils.utils_func import get_folder, check_path
 import datetime
 from utils.SingletonType import SingletonType
-from databases import CRUD,SqlQuery,PhotoRecord
+from databases import CRUD, SqlQuery, PhotoRecord
+import asyncio
+
+
 def updateImageRaw(time_str, image_path, goods_art_no, image_index):
     session = SqlQuery()
     crud = CRUD(PhotoRecord)
@@ -52,7 +55,7 @@ class FileEventHandler(FileSystemEventHandler, metaclass=SingletonType):
         self.observer = None
         self.last_create_time = datetime.datetime.now()
 
-    def start_observer(self,path):
+    def start_observer(self, path):
         if self.observer != None:
             return
         print("图片保存目录:", path)
@@ -62,7 +65,9 @@ class FileEventHandler(FileSystemEventHandler, metaclass=SingletonType):
 
         watch_path = self.check_and_get_real_dir(path)
         if watch_path:
-            self.observer.schedule(self, watch_path, recursive=True)  # recursive 遍历目录
+            self.observer.schedule(
+                self, watch_path, recursive=True
+            )  # recursive 遍历目录
             self.observer.start()
             print("开启开门狗目录监听")
         else:
@@ -73,7 +78,7 @@ class FileEventHandler(FileSystemEventHandler, metaclass=SingletonType):
         逻辑:
         1、检查当前路径如包含Originals 则定位到对应Originals的父级目录
         2、如没有Originals,则认定为一个普通目录(且子文件夹没有Originals),否则定位到父级目录
-        
+
         """
         if not os.path.exists(watch_path):
             return None
@@ -91,9 +96,11 @@ class FileEventHandler(FileSystemEventHandler, metaclass=SingletonType):
         year = now.year
         month = now.month
         day = now.day
-        path = r"{root_path}\Originals\{year}\{month}\{day}".format(root_path=root_path, year=year, month=month, day=day)
+        path = r"{root_path}\Originals\{year}\{month}\{day}".format(
+            root_path=root_path, year=year, month=month, day=day
+        )
         check_path(path)
-        print("watch_path:",path)
+        print("watch_path:", path)
         return path
 
     def on_moved(self, event):
@@ -104,10 +111,24 @@ class FileEventHandler(FileSystemEventHandler, metaclass=SingletonType):
         #     if os.path.split(event.dest_path)[0] == settings.PhotoOutputDir:
         #         print("1111111")
         pass
+
     def updatePhotoRecord(self):
         session = SqlQuery()
         crud = CRUD(PhotoRecord)
         crud.read()
+
+    async def sendCallback(self, file_path):
+        await asyncio.sleep(0.01)
+        self.mcu.msg_type = "run_mcu_single"
+        print("货号不存在,监听不写入", self.mcu.msg_type)
+        self.mcu.sendSocketMessage(
+            code=0,
+            msg="主图测试拍摄完成",
+            device_status=2,
+            data={"file_path": file_path.replace("\\", "/")},
+        )
+        self.msg_type = "mcu"
+
     def on_created(self, event):
         if not event.is_directory:
             file_path = event.src_path
@@ -119,25 +140,27 @@ class FileEventHandler(FileSystemEventHandler, metaclass=SingletonType):
             try:
                 take_time = time.time()
                 self.send_log("获取文件file_path:{}".format(file_path))
-                create_time = datetime.datetime.fromtimestamp(os.path.getctime(file_path))
+                create_time = datetime.datetime.fromtimestamp(
+                    os.path.getctime(file_path)
+                )
                 # print("获取文件create_time:{}".format(create_time))
-                self.get_photo_info(raw_path=file_path, create_time=create_time, take_time=take_time)
+                self.get_photo_info(
+                    raw_path=file_path, create_time=create_time, take_time=take_time
+                )
                 self.send_log("获取文件create_time:{}".format(create_time))
                 if file_path == None:
                     print("file_path不存在,监听不写入")
                     return
                 if self.goods_art_no == None:
                     # print("货号不存在,监听不写入")
-                    self.mcu.msg_type = "run_mcu_single"
-                    self.mcu.sendSocketMessage(
-                        code=0,
-                        msg="主图测试拍摄完成",
-                        device_status=2,
-                        data={"file_path": file_path},
-                    )
-                    self.msg_type = "mcu"
+                    loop = asyncio.new_event_loop()
+                    asyncio.set_event_loop(loop)
+                    loop.run_until_complete(self.sendCallback(file_path))
+                    loop.close()
                     return
-                updateImageRaw(create_time, file_path, self.goods_art_no,self.image_index)
+                updateImageRaw(
+                    create_time, file_path, self.goods_art_no, self.image_index
+                )
             except BaseException as e:
                 print("获取文件create_time失败", e)
                 self.send_log("获取文件处理失败{}".format(e))
@@ -163,7 +186,9 @@ class FileEventHandler(FileSystemEventHandler, metaclass=SingletonType):
                     # 判断是否为文件
                     if os.path.isfile(file_path):
                         # 获取文件创建时间
-                        create_time = datetime.datetime.fromtimestamp(os.path.getctime(file_path))
+                        create_time = datetime.datetime.fromtimestamp(
+                            os.path.getctime(file_path)
+                        )
                         # 更新最早时间
                         if create_time > self.last_create_time:
                             self.last_create_time = create_time

+ 3 - 1
python/model/photo_record.py

@@ -1,7 +1,9 @@
 from sqlmodel import SQLModel, Field
 from datetime import datetime
 from typing import Optional
-from settings import TIME_ZONE
+import pytz
+
+TIME_ZONE = pytz.timezone("Asia/Shanghai")
 class PhotoRecord(SQLModel, table=True):
     __tablename__ = "photo_record"
     id: Optional[int] = Field(default=None, primary_key=True, index=True)

+ 3 - 3
python/service/OnePicTest.py

@@ -84,9 +84,9 @@ class OnePicTest():
         if not os.path.exists(self.pic_path):
             raise UnicornException("图片不存在")
         return_data = self.deal_image(self.pic_path)
-        if return_data["message"]:
-            raise UnicornException(return_data["message"])
-        return return_data
+        # if return_data["message"]:
+        #     raise UnicornException(return_data["message"])
+        return return_data.replace("\\", "/")
 
 if __name__ == "__main__":
     pic = OnePicTest(pic_path="C:/Users/15001/Desktop/mmexport1739929178317.jpg")

+ 7 - 3
python/sockets/message_handler.py

@@ -34,11 +34,13 @@ async def handlerSend(
             await manager.broadcast(dictMsg)
         case "connect_mcu":
             device_ctrl = DeviceControl(websocket_manager=manager)
+            device_ctrl.mcu_exit = False
             # if device_ctrl.serial_ins.check_connect():
             #     print("未连接")
             loop.create_task(checkMcuConnection(device_ctrl), name="mcu")
         case "connect_bluetooth":
             blue_tooth = BlueToothMode(websocket_manager=manager)
+            blue_tooth.bluetooth_exit = False
             # await  blue_tooth.main_func()
             print("连接蓝牙信息")
             loop.create_task(blue_tooth.main_func(), name="blue_tooth")
@@ -120,7 +122,7 @@ async def handlerSend(
         case "run_mcu_single":
             device_ctrl = DeviceControl(websocket_manager=manager)
             loop.create_task(
-                device_ctrl.run_mcu_config_single(data, None),
+                device_ctrl.run_mcu_config_single(data, None, "run_mcu_single"),
                 name="run_mcu_single",
             )
         case "handler_take_picture":
@@ -162,6 +164,7 @@ async def handlerSend(
                 return
             action_id = goods_art_record.action_id
             goods_art_no = goods_art_record.goods_art_no
+            image_index = goods_art_record.image_index
             crud = CRUD(DeviceConfig)
             condtions = {"id": action_id}
             device_action = crud.read(
@@ -173,11 +176,12 @@ async def handlerSend(
                 await manager.send_personal_message(data, websocket, msg_type=msg_type)
                 return
             # 清除图片记录,执行重拍
-            photoRecord.update(session, record_id, {"image_path": None})
+            reset_data = {"image_path": None}
+            photoRecord.update(session, record_id, **reset_data)
             device_ctrl = DeviceControl(websocket_manager=manager)
             loop.create_task(
                 device_ctrl.run_mcu_config_single(
-                    device_action, goods_art_no, msg_type=msg_type
+                    device_action.model_dump(), goods_art_no, msg_type=msg_type,image_index=image_index
                 ),
                 name="run_mcu_config_single",
             )

+ 6 - 0
python/sockets/socket_server.py

@@ -26,14 +26,20 @@ async def websocket_endpoint(websocket: WebSocket):
                     socket_type = byteDats.get("type")
                     if socket_type == "websocket.disconnect":
                         device_ctrl.close_connect()
+                        device_ctrl.mcu_exit = True
+                        device_ctrl.clearMyInstance()
                         diviceList = blue_tooth.devices
                         if len(diviceList) == 0:
+                            blue_tooth.bluetooth_exit = True
+                            blue_tooth.clearMyInstance()
                             break
                         diviceAddress = 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()
                         break
                     print("byteDats", byteDats)
                     await handlerSend(conn_manager, json.dumps(byteDats), websocket)

+ 4 - 1
python/utils/SingletonType.py

@@ -9,4 +9,7 @@ class SingletonType(type):
                     cls._instance = super(SingletonType, cls).__call__(*args, **kwargs)
         return cls._instance
 
-
+    @classmethod
+    def clear_instance(cls):
+        if hasattr(cls, "_instance"):
+            delattr(cls, "_instance")