Browse Source

Merge branch 'dev-python'

rambo 7 months ago
parent
commit
960a8d7e79

+ 13 - 13
python/action.json

@@ -2,7 +2,7 @@
     {
         "mode_type": "执行左脚程序",
         "execution_type": "程序1",
-        "action_name": "左脚俯拍鞋子",
+        "action_name": "俯视",
         "action_index": 20,
         "picture_index": 99,
         "camera_height": 200,
@@ -21,7 +21,7 @@
     {
         "mode_type": "执行左脚程序",
         "execution_type": "程序1",
-        "action_name": "侧视",
+        "action_name": "侧视",
         "action_index": 10,
         "picture_index": 99,
         "camera_height": 0,
@@ -40,7 +40,7 @@
     {
         "mode_type": "执行左脚程序",
         "execution_type": "程序1",
-        "action_name": "后跟",
+        "action_name": "后跟",
         "action_index": 30,
         "picture_index": 99,
         "camera_height": 0,
@@ -59,7 +59,7 @@
     {
         "mode_type": "执行左脚程序",
         "execution_type": "程序2",
-        "action_name": "鞋底",
+        "action_name": "鞋底",
         "action_index": 40,
         "picture_index": 99,
         "camera_height": 0,
@@ -78,7 +78,7 @@
     {
         "mode_type": "执行左脚程序",
         "execution_type": "程序2",
-        "action_name": "内里",
+        "action_name": "内里",
         "action_index": 50,
         "picture_index": 99,
         "camera_height": 0,
@@ -115,8 +115,8 @@
     },
     {
         "mode_type": "执行右脚程序",
-        "execution_type": "程序1",
-        "action_name": "右脚俯拍鞋子",
+        "execution_type": "程序2",
+        "action_name": "俯视",
         "action_index": 20,
         "picture_index": 99,
         "camera_height": 200,
@@ -134,8 +134,8 @@
     },
     {
         "mode_type": "执行右脚程序",
-        "execution_type": "程序1",
-        "action_name": "侧视",
+        "execution_type": "程序2",
+        "action_name": "侧视",
         "action_index": 10,
         "picture_index": 99,
         "camera_height": 0,
@@ -153,8 +153,8 @@
     },
     {
         "mode_type": "执行右脚程序",
-        "execution_type": "程序1",
-        "action_name": "后跟",
+        "execution_type": "程序2",
+        "action_name": "后跟",
         "action_index": 30,
         "picture_index": 99,
         "camera_height": 0,
@@ -173,7 +173,7 @@
     {
         "mode_type": "执行右脚程序",
         "execution_type": "程序2",
-        "action_name": "鞋底",
+        "action_name": "鞋底",
         "action_index": 40,
         "picture_index": 99,
         "camera_height": 0,
@@ -192,7 +192,7 @@
     {
         "mode_type": "执行右脚程序",
         "execution_type": "程序2",
-        "action_name": "内里",
+        "action_name": "内里",
         "action_index": 50,
         "picture_index": 99,
         "camera_height": 0,

+ 34 - 0
python/api.py

@@ -21,6 +21,8 @@ from databases import DeviceConfig, SqlQuery, CRUD, select
 from service.run_main import RunMain
 import importlib
 from service.auto_deal_pics.upload_pic import UploadPic
+from service.OnePicTest import OnePicTest
+
 # from service.AutoDealPics import AutoDealPics
 # for plugin in settings.plugins:
 #     module_path, class_name = plugin.rsplit(".", 1)
@@ -408,6 +410,20 @@ def get_device_configs(params: ModelGetDeviceConfigDetail):
     return {"code": 0, "msg": "", "data": model}
 
 
+@app.post("/device_config_detail_query", description="通过条件获取可执行程序详情")
+def get_device_configs(params: ModelGetDeviceConfigDetailQuery):
+    mode_type = params.mode_type
+    action_name = params.action_name
+    session = SqlQuery()
+    configModel = CRUD(DeviceConfig)
+    model = configModel.read(
+        session, conditions={"mode_type": mode_type, "action_name": action_name}
+    )
+    if model == None:
+        return {"code": 1, "msg": "数据不存在", "data": None}
+    return {"code": 0, "msg": "", "data": model}
+
+
 @app.post("/remove_config", description="删除一条可执行命令")
 def get_device_configs(params: ModelGetDeviceConfigDetail):
     action_id = params.id
@@ -549,3 +565,21 @@ def save_sys_configs(params: SysConfigParams):
         session, conditions={"key": params.key}, **kwargs
     )
     return {"code": 0, "msg": "操作成功", "data": save_device_config}
+
+
+@app.post("/create_main_image", description="创建主图测试")
+def save_sys_configs(params: MaineImageTest):
+    file_path = params.file_path
+    onePic = OnePicTest(pic_path=file_path)
+    # session = SqlQuery()
+    # sysConfig = CRUD(SysConfigs)
+    # model = sysConfig.read(session, conditions={"key": params.key})
+    # if model == None:
+    #     return {"code": 1, "msg": "配置不存在", "data": None}
+    # # 走编辑逻辑
+    # kwargs = params.__dict__
+    # save_device_config = sysConfig.updateConditions(
+    #     session, conditions={"key": params.key}, **kwargs
+    # )
+    main_out_path = onePic.HandlerMainImage()
+    return {"code": 0, "msg": "操作成功", "data": {"main_out_path": main_out_path}}

+ 35 - 17
python/databases.py

@@ -4,7 +4,7 @@ from typing import Dict
 from datetime import datetime
 from typing import Optional
 import json
-from sqlalchemy import and_, desc,asc
+from sqlalchemy import and_, desc, asc
 
 from sqlalchemy.dialects import sqlite
 from model import DeviceConfig, PhotoRecord, SysConfigs
@@ -22,9 +22,12 @@ engine = create_engine(
     pool_recycle=1800,
 )
 
+
 # 创建表
 def create_all_database():
     SQLModel.metadata.create_all(engine)
+
+
 # 创建会话
 def __get_session():
     with Session(engine) as session:
@@ -35,7 +38,7 @@ def __get_session():
 
 
 def batch_insert_device_configs(session: Session, data_list: list):
-    '''批量插入数据到设备配置表'''
+    """批量插入数据到设备配置表"""
     for data in data_list:
         device_config = DeviceConfig(**data)
         session.add(device_config)
@@ -52,13 +55,16 @@ def batch_insert_sys_configs(session: Session, data_list: list):
     session.close()
 
 
-def insert_photo_records(image_deal_mode: int, goods_art_no: str, image_index:int):
+def insert_photo_records(
+    image_deal_mode: int, goods_art_no: str, image_index: int, action_id: int
+):
     session = SqlQuery()
     """批量插入数据到照片记录"""
     data = {
         "image_deal_mode": image_deal_mode,
         "goods_art_no": goods_art_no,
         "image_index": image_index,
+        "action_id": action_id,
     }
     device_config = PhotoRecord(**data)
     session.add(device_config)
@@ -82,21 +88,28 @@ class CRUD:
         return db_obj
 
     def read(
-            self,
-            session: Session,
-            conditions: Optional[Dict] = None,
-            order_by: Optional[str] = None,
-            ascending: bool = True,
+        self,
+        session: Session,
+        conditions: Optional[Dict] = None,
+        order_by: Optional[str] = None,
+        ascending: bool = True,
     ):
         query = select(self.model)
         if conditions:
-            query = query.where(and_(*(getattr(self.model, key) == value for key, value in conditions.items())))
+            query = query.where(
+                and_(
+                    *(
+                        getattr(self.model, key) == value
+                        for key, value in conditions.items()
+                    )
+                )
+            )
         if order_by:
             if ascending:
                 query = query.order_by(asc(getattr(self.model, order_by)))
             else:
                 query = query.order_by(desc(getattr(self.model, order_by)))
-        data =  session.exec(query).first()
+        data = session.exec(query).first()
         session.close()
         return data
 
@@ -109,20 +122,27 @@ class CRUD:
     ):
         query = select(self.model)
         if conditions:
-            query = query.where(and_(*(getattr(self.model, key) == value for key, value in conditions.items())))
+            query = query.where(
+                and_(
+                    *(
+                        getattr(self.model, key) == value
+                        for key, value in conditions.items()
+                    )
+                )
+            )
         if order_by:
             if ascending:
                 query = query.order_by(asc(getattr(self.model, order_by)))
             else:
                 query = query.order_by(desc(getattr(self.model, order_by)))
-        data =  session.exec(query).all()
+        data = session.exec(query).all()
         session.close()
         return data
 
     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 =="":
+            if value == None or value == "":
                 continue
             setattr(db_obj, key, value)
         session.commit()
@@ -131,10 +151,7 @@ class CRUD:
         return db_obj
 
     def updateConditions(
-        self,
-        session: Session,
-        conditions: Optional[Dict] = None,
-        **kwargs
+        self, session: Session, conditions: Optional[Dict] = None, **kwargs
     ):
         query = select(self.model)
         if conditions:
@@ -189,6 +206,7 @@ class CRUD:
 def SqlQuery():
     return next(__get_session())
 
+
 # 使用示例
 if __name__ == "__main__":
     pass

+ 14 - 0
python/docs/socket命令.md

@@ -506,4 +506,18 @@ _(该命令用于单独自定义配置中某一项的单独调整测试,不进
     "msg_type": "send_command"
 }
 ```
+#### 执行重拍操作
+<mark>以下操作需要连接设备且初始化<mark>
+* data:
+    * record_id:原记录id
+* type:
+    * 当该字段为re_take_picture时,代表进行重拍操作
+<mark>注:后续得拍照动作参考消息回复为的type均为:re_take_picture,照片拍摄完成的消息依旧为photo_take<mark>
+##### 请求示例
+```python
+{
+    "data":{"record_id":1},
+    "type": "re_take_picture"
+}
+```
 ##### 未完待续.....

+ 10 - 4
python/mcu/DeviceControl.py

@@ -250,7 +250,7 @@ class DeviceControl(BaseClass, metaclass=SingletonType):
             )
             self.add_send_data_queue(buf)
 
-    async def get_deviation(self):
+    async def getDeviationInfo(self):
         await asyncio.sleep(0.01)
         # 发送获取偏移量
         data = [self.command["get_deviation"], 1]
@@ -1361,11 +1361,17 @@ class DeviceControl(BaseClass, metaclass=SingletonType):
         if config_list:
             for idx, item in enumerate(config_list):
                 is_take_picture = item["take_picture"]
+                action_id = item["id"]
                 if is_take_picture:
                     image_counts += 1
                     # 批量插入
                     image_deal_mode = 0 if action_info == "执行左脚程序" else 1
-                    insert_photo_records(image_deal_mode=image_deal_mode, goods_art_no=goods_art_no, image_index=idx)
+                    insert_photo_records(
+                        image_deal_mode=image_deal_mode,
+                        goods_art_no=goods_art_no,
+                        image_index=idx,
+                        action_id=action_id,
+                    )
             total_len = len(config_list)
             self.action_state = 1
             self.msg_type = "image_process"
@@ -1441,7 +1447,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):
+    async def run_mcu_config_single(self, config_info, goods_art_no,msg_type="run_mcu_single_finish"):
         '''独立拍照  仅作测试用'''
         if self.checkDevice() == False:
             return
@@ -1482,7 +1488,7 @@ class DeviceControl(BaseClass, metaclass=SingletonType):
                     )
             self.msg_type = "mcu"
             self.action_state = 2
-            self.msg_type = "run_mcu_single_finish"
+            self.msg_type = msg_type
             self.sendSocketMessage(
                     code=0,
                     msg=f"执行完成",

+ 4 - 4
python/mcu/McuDeviationSet.py

@@ -20,7 +20,8 @@ class McuDeviationSet:
         # self.show()
         self.last_value = defaultdict(float)
         self.mcu_debug = McuDebug(mcu, is_debug=True, is_deviation=False)
-        self.get_mcu_deviation()
+        loop = asyncio.get_event_loop()
+        loop.create_task(self.get_mcu_deviation(), name="get_mcu_deviation")
         # # 运动到设定位
         # QTimer.singleShot(2500, self.init_pos)
 
@@ -233,9 +234,8 @@ class McuDeviationSet:
     def _to_init_all(self, *args):
         self.mcu.to_init_device_origin_point(device_name="mcu", is_force=True)
 
-    def get_mcu_deviation(self):
-        loop = asyncio.get_event_loop()
-        loop.create_task(self.mcu.get_deviation(), name="get_mcu_deviation")
+    async def get_mcu_deviation(self):
+        await self.mcu.getDeviationInfo()
 
     def get_mcu_deviation_info(self, data):
         if "_type" not in data:

+ 4 - 4
python/mcu/ProgramItem.py

@@ -23,6 +23,7 @@ class ProgramItem(BaseClass):
         self.watch_dog = FileEventHandler()
         self.watch_dog.goods_art_no = goods_art_no
         self.watch_dog.image_index = image_index
+        self.watch_dog.mcu = mcu
         self.watch_dog.start_observer(captrure_folder_path)
         print("21 =========ProgramItem=======action_data=====")
         print(action_data)
@@ -274,10 +275,9 @@ class ProgramItem(BaseClass):
         # print("{} 拍照时间:{}".format(self.action_name, time.time() - start_time))
         print("{}-{}已完成".format(self.mode_type, self.action_name))
 
-        if True:
-            if self.after_delay_time:
-                print("拍照后延时:{}".format(self.after_delay_time))
-                time.sleep(self.after_delay_time)
+        if self.after_delay_time:
+            print("拍照后延时:{}".format(self.after_delay_time))
+            time.sleep(self.after_delay_time)
         return True
 
     def rephotograph_one_pic(self, *args):

+ 12 - 4
python/mcu/capture/module_watch_dog.py

@@ -7,7 +7,6 @@ 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
 def updateImageRaw(time_str, image_path, goods_art_no, image_index):
     session = SqlQuery()
     crud = CRUD(PhotoRecord)
@@ -43,6 +42,7 @@ class FileEventHandler(FileSystemEventHandler, metaclass=SingletonType):
         #     self.init_flag = True
         self.goods_art_no = None
         self.image_index = -1
+        self.mcu = None
         super().__init__()
         # self.window = window
         FileSystemEventHandler.__init__(self)
@@ -123,12 +123,20 @@ class FileEventHandler(FileSystemEventHandler, metaclass=SingletonType):
                 # print("获取文件create_time:{}".format(create_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 self.goods_art_no == None:
-                    print("货号不存在,监听不写入")
-                    return
                 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"
+                    return
                 updateImageRaw(create_time, file_path, self.goods_art_no,self.image_index)
             except BaseException as e:
                 print("获取文件create_time失败", e)

+ 1 - 0
python/model/photo_record.py

@@ -5,6 +5,7 @@ from settings import TIME_ZONE
 class PhotoRecord(SQLModel, table=True):
     __tablename__ = "photo_record"
     id: Optional[int] = Field(default=None, primary_key=True, index=True)
+    action_id: Optional[int] = Field(default=None)
     goods_art_no: Optional[str] = Field(max_length=128, nullable=False)
     image_path: Optional[str] = Field(default=None)
     image_index: Optional[int] = Field(default=None)

+ 13 - 0
python/models.py

@@ -23,6 +23,13 @@ class ModelGetDeviceConfigDetail(BaseModel):
     )
 
 
+class ModelGetDeviceConfigDetailQuery(BaseModel):
+    """获取可执行程序命令列表"""
+
+    mode_type: Optional[str] = Field(default="执行左脚程序", index=True, max_length=128)
+    action_name: Optional[str] = Field(default="", index=True, max_length=128)
+
+
 class SaveDeviceConfig(BaseModel):
     """获取可执行程序命令列表"""
 
@@ -64,6 +71,12 @@ class TemplateItem(BaseModel):
     template_local_classes: str = Field(description="模板名称")
 
 
+class MaineImageTest(BaseModel):
+    """模板项"""
+
+    file_path: str = Field(description="图片地址")
+
+
 class HandlerDetail(BaseModel):
     """获取可执行程序命令列表"""
 

+ 93 - 0
python/service/OnePicTest.py

@@ -0,0 +1,93 @@
+import threading
+import time
+import os
+import settings
+
+from service.remove_bg_ali import RemoveBgALi
+from service.generate_main_image.grenerate_main_image_test import (
+    GeneratePic,
+)
+from service.generate_main_image.image_deal_base_func import *
+from functools import partial
+import io
+from PIL import Image
+from .base import check_path, get_date_time_original
+from middleware import UnicornException
+
+class OnePicTest():
+    # is_end = Signal()
+
+    def __init__(self,  pic_path="", is_auto_closed=False):
+        # super().__init__()
+        # 加载默认配置
+        # self.ui = Ui_Form()
+        # self.ui.setupUi(self)
+        self.pic_path = pic_path
+        self.is_auto_closed = False
+        # self.init()
+        # self.show()
+        # if pic_path:
+        #     self.run()
+
+    def call_back_deal_image(self, data):
+        # 处理后回调
+        print(data)
+        if data["code"] == 0:
+            return data
+        else:
+            if data["message"]:
+                raise UnicornException(data["message"])
+
+    def deal_image(self, image_path):
+        # 处理加工图片
+        return_data = {"code": 99, "message": "", "data": {}}
+
+        # =============清空temp文件夹================
+        check_path("temp")
+        check_path("temp\pic_test")
+        root = r"{}\temp\pic_test".format(os.getcwd())
+        for file_name in os.listdir(root):
+            path = "{}\{}".format(root, file_name)
+            if os.path.isfile(path):
+                os.remove(path)
+
+        # ==============抠图处理=====================
+        remove_pic_ins = RemoveBgALi()
+        file = os.path.split(image_path)[1]
+        cut_image_path = r"{}\temp\pic_test\{}.png".format(
+            os.getcwd(), os.path.splitext(file)[0]
+        )
+        remove_pic_ins.get_image_cut(file_path=image_path, out_file_path=cut_image_path)
+
+        # ==============生成主图====================
+        main_out_path = r"{}\temp\pic_test\{}-主图.jpg".format(
+            os.getcwd(), os.path.splitext(file)[0]
+        )
+        GeneratePic().run(
+            image_path=image_path,
+            cut_image_path=cut_image_path,
+            out_path=main_out_path,
+            image_deal_mode=1,
+            resize_mode=1,
+            out_pic_size=1024,
+            is_logo=False,
+        )
+
+        # return_data["code"] = 0
+        # return_data["data"]["image_path"] = image_path
+        # return_data["data"]["image_cutout_path"] = cut_image_path
+        # return_data["data"]["image_main_path"] = main_out_path
+        return main_out_path
+
+    def HandlerMainImage(self):
+        # 先做整体校验
+        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 __name__ == "__main__":
+    pic = OnePicTest(pic_path="C:/Users/15001/Desktop/mmexport1739929178317.jpg")
+    pic.HandlerMainImage()

+ 53 - 1
python/sockets/message_handler.py

@@ -129,10 +129,62 @@ async def handlerSend(
                 blue_tooth.remote_control_v2.handlerTakePhoto(),
                 name="run_mcu_config",
             )
+        case "re_take_picture":#重拍
+            try:
+                # 判断拍照软件是否初始化
+                digicam = DigiCam()
+                camera_is_connect = digicam.checkCameraConnect()
+                if camera_is_connect is not True:
+                    data = manager.jsonMessage(
+                        code=1, msg="相机未连接,请检查", msg_type=msg_type
+                    )
+                    await manager.send_personal_message(data, websocket)
+                    return
+                digicam.getCaptureFolderPath()
+            except:
+                data = manager.jsonMessage(
+                    code=1, msg="digicam未初始化,请检查", msg_type=msg_type
+                )
+                await manager.send_personal_message(data, websocket)
+                return
+            msg_type = "re_take_picture"
+            record_id = data.get("record_id")
+            session = SqlQuery()
+            photoRecord = CRUD(PhotoRecord)
+            goods_art_record = photoRecord.read(session, conditions={"id": record_id})
+            if goods_art_record == None:
+                data = manager.jsonMessage(
+                    code=1,
+                    msg=f"记录不存在,请核实后重新操作~",
+                    msg_type=msg_type,
+                )
+                await manager.send_personal_message(data, websocket)
+                return
+            action_id = goods_art_record.action_id
+            goods_art_no = goods_art_record.goods_art_no
+            crud = CRUD(DeviceConfig)
+            condtions = {"id": action_id}
+            device_action = crud.read(
+                session, conditions=condtions
+            )
+            if device_action == None:
+                # 判断是否有可用配置
+                data = manager.jsonMessage(code=1, msg="当前没有可用配置")
+                await manager.send_personal_message(data, websocket, msg_type=msg_type)
+                return
+            # 清除图片记录,执行重拍
+            photoRecord.update(session, record_id, {"image_path": None})
+            device_ctrl = DeviceControl(websocket_manager=manager)
+            loop.create_task(
+                device_ctrl.run_mcu_config_single(
+                    device_action, goods_art_no, msg_type=msg_type
+                ),
+                name="run_mcu_config_single",
+            )
         case "get_deviation":
             device_ctrl = DeviceControl(websocket_manager=manager)
             loop.create_task(
-                device_ctrl.get_deviation(),
+                device_ctrl.getDeviationInfo(),
                 name="get_deviation",
             )
         case "set_deviation":