Work-Recoder-ADD_TEMPLATES-1.0

1. ADD_TEMPLATES_QT.py

# -*- coding: utf-8 -*-

# Form implementation generated from reading ui file 'D:\desk\Work\Dataset\Script\ADD_TEMPLATES\ADD_TEMPLATES.ui'
#
# Created by: PyQt5 UI code generator 5.15.10
#
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again.  Do not edit this file unless you know what you are doing.


from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtCore import QTimer


class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("模板装订")
        MainWindow.resize(1112, 897)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.horizontalLayoutWidget_2 = QtWidgets.QWidget(self.centralwidget)
        self.horizontalLayoutWidget_2.setGeometry(QtCore.QRect(10, 740, 1041, 61))
        self.horizontalLayoutWidget_2.setObjectName("horizontalLayoutWidget_2")
        self.horizontalLayout_2 = QtWidgets.QHBoxLayout(self.horizontalLayoutWidget_2)
        self.horizontalLayout_2.setContentsMargins(0, 0, 0, 0)
        self.horizontalLayout_2.setSpacing(100)
        self.horizontalLayout_2.setObjectName("horizontalLayout_2")
        self.para_setting = QtWidgets.QPushButton(self.horizontalLayoutWidget_2)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.para_setting.sizePolicy().hasHeightForWidth())
        self.para_setting.setSizePolicy(sizePolicy)
        font = QtGui.QFont()
        font.setPointSize(20)
        font.setBold(True)
        font.setWeight(75)
        self.para_setting.setFont(font)
        self.para_setting.setObjectName("para_setting")
        self.horizontalLayout_2.addWidget(self.para_setting)
        self.close_window = QtWidgets.QPushButton(self.horizontalLayoutWidget_2)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.close_window.sizePolicy().hasHeightForWidth())
        self.close_window.setSizePolicy(sizePolicy)
        font = QtGui.QFont()
        font.setPointSize(20)
        font.setBold(True)
        font.setWeight(75)
        self.close_window.setFont(font)
        self.close_window.setObjectName("close_window")
        self.horizontalLayout_2.addWidget(self.close_window)
        self.template_frame = QtWidgets.QFrame(self.centralwidget)
        self.template_frame.setGeometry(QtCore.QRect(-10, 10, 1091, 721))
        self.template_frame.setFrameShape(QtWidgets.QFrame.StyledPanel)
        self.template_frame.setFrameShadow(QtWidgets.QFrame.Raised)
        self.template_frame.setObjectName("template_frame")
        self.images_container = QtWidgets.QLabel(self.template_frame)
        self.images_container.setGeometry(QtCore.QRect(20, 0, 751, 631))
        self.images_container.setStyleSheet("border:1px solid black;")
        self.images_container.setText("")
        self.images_container.setObjectName("images_container")
        self.RGB_Label = QtWidgets.QLabel(self.template_frame)
        self.RGB_Label.setGeometry(QtCore.QRect(800, 0, 261, 41))
        font = QtGui.QFont()
        font.setPointSize(20)
        font.setBold(True)
        font.setWeight(75)
        self.RGB_Label.setFont(font)
        self.RGB_Label.setLayoutDirection(QtCore.Qt.LeftToRight)
        self.RGB_Label.setAlignment(QtCore.Qt.AlignCenter)
        self.RGB_Label.setObjectName("RGB_Label")
        self.RGB_list = QtWidgets.QListView(self.template_frame)
        self.RGB_list.setGeometry(QtCore.QRect(810, 40, 261, 271))
        self.RGB_list.setObjectName("RGB_list")
        self.IR_Label = QtWidgets.QLabel(self.template_frame)
        self.IR_Label.setGeometry(QtCore.QRect(810, 330, 261, 31))
        font = QtGui.QFont()
        font.setPointSize(20)
        font.setBold(True)
        font.setWeight(75)
        self.IR_Label.setFont(font)
        self.IR_Label.setAlignment(QtCore.Qt.AlignCenter)
        self.IR_Label.setObjectName("IR_Label")
        self.IR_list = QtWidgets.QListView(self.template_frame)
        self.IR_list.setGeometry(QtCore.QRect(810, 360, 261, 271))
        self.IR_list.setObjectName("IR_list")
        self.horizontalLayoutWidget = QtWidgets.QWidget(self.template_frame)
        self.horizontalLayoutWidget.setGeometry(QtCore.QRect(20, 640, 1041, 71))
        self.horizontalLayoutWidget.setObjectName("horizontalLayoutWidget")
        self.horizontalLayout = QtWidgets.QHBoxLayout(self.horizontalLayoutWidget)
        self.horizontalLayout.setSizeConstraint(QtWidgets.QLayout.SetDefaultConstraint)
        self.horizontalLayout.setContentsMargins(0, 0, 0, 0)
        self.horizontalLayout.setSpacing(10)
        self.horizontalLayout.setObjectName("horizontalLayout")
        self.select_RGB_templates = QtWidgets.QPushButton(self.horizontalLayoutWidget)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.select_RGB_templates.sizePolicy().hasHeightForWidth())
        self.select_RGB_templates.setSizePolicy(sizePolicy)
        font = QtGui.QFont()
        font.setPointSize(20)
        font.setBold(True)
        font.setWeight(75)
        self.select_RGB_templates.setFont(font)
        self.select_RGB_templates.setObjectName("select_RGB_templates")
        self.horizontalLayout.addWidget(self.select_RGB_templates)
        self.select_IR_templates = QtWidgets.QPushButton(self.horizontalLayoutWidget)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.select_IR_templates.sizePolicy().hasHeightForWidth())
        self.select_IR_templates.setSizePolicy(sizePolicy)
        font = QtGui.QFont()
        font.setPointSize(20)
        font.setBold(True)
        font.setWeight(75)
        self.select_IR_templates.setFont(font)
        self.select_IR_templates.setObjectName("select_IR_templates")
        self.horizontalLayout.addWidget(self.select_IR_templates)
        self.send_templates = QtWidgets.QPushButton(self.horizontalLayoutWidget)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.send_templates.sizePolicy().hasHeightForWidth())
        self.send_templates.setSizePolicy(sizePolicy)
        font = QtGui.QFont()
        font.setPointSize(20)
        font.setBold(True)
        font.setWeight(75)
        self.send_templates.setFont(font)
        self.send_templates.setObjectName("send_templates")
        self.horizontalLayout.addWidget(self.send_templates)
        self.check_sended_templates = QtWidgets.QPushButton(self.horizontalLayoutWidget)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.check_sended_templates.sizePolicy().hasHeightForWidth())
        self.check_sended_templates.setSizePolicy(sizePolicy)
        font = QtGui.QFont()
        font.setPointSize(20)
        font.setBold(True)
        font.setWeight(75)
        self.check_sended_templates.setFont(font)
        self.check_sended_templates.setObjectName("check_sended_templates")
        self.horizontalLayout.addWidget(self.check_sended_templates)
        self.clear_templates = QtWidgets.QPushButton(self.horizontalLayoutWidget)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.clear_templates.sizePolicy().hasHeightForWidth())
        self.clear_templates.setSizePolicy(sizePolicy)
        font = QtGui.QFont()
        font.setPointSize(20)
        font.setBold(True)
        font.setWeight(75)
        self.clear_templates.setFont(font)
        self.clear_templates.setObjectName("clear_templates")
        self.horizontalLayout.addWidget(self.clear_templates)
        self.para_frame = QtWidgets.QFrame(self.centralwidget)
        self.para_frame.setGeometry(QtCore.QRect(60, 40, 901, 661))
        self.para_frame.setFrameShape(QtWidgets.QFrame.Box)
        self.para_frame.setFrameShadow(QtWidgets.QFrame.Sunken)
        self.para_frame.setObjectName("para_frame")
        self.verticalLayoutWidget = QtWidgets.QWidget(self.para_frame)
        self.verticalLayoutWidget.setGeometry(QtCore.QRect(370, 40, 411, 441))
        self.verticalLayoutWidget.setObjectName("verticalLayoutWidget")
        self.verticalLayout = QtWidgets.QVBoxLayout(self.verticalLayoutWidget)
        self.verticalLayout.setContentsMargins(0, 0, 0, 0)
        self.verticalLayout.setSpacing(20)
        self.verticalLayout.setObjectName("verticalLayout")
        self.IP_textEdit = QtWidgets.QTextEdit(self.verticalLayoutWidget)
        font = QtGui.QFont()
        font.setPointSize(15)
        self.IP_textEdit.setFont(font)
        self.IP_textEdit.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
        self.IP_textEdit.setObjectName("IP_textEdit")
        self.verticalLayout.addWidget(self.IP_textEdit)
        self.PORT_textEdit = QtWidgets.QTextEdit(self.verticalLayoutWidget)
        font = QtGui.QFont()
        font.setPointSize(15)
        self.PORT_textEdit.setFont(font)
        self.PORT_textEdit.setObjectName("PORT_textEdit")
        self.verticalLayout.addWidget(self.PORT_textEdit)
        self.serial_textEdit = QtWidgets.QTextEdit(self.verticalLayoutWidget)
        font = QtGui.QFont()
        font.setPointSize(15)
        self.serial_textEdit.setFont(font)
        self.serial_textEdit.setObjectName("serial_textEdit")
        self.verticalLayout.addWidget(self.serial_textEdit)
        self.baudrate_textEdit = QtWidgets.QTextEdit(self.verticalLayoutWidget)
        font = QtGui.QFont()
        font.setPointSize(15)
        self.baudrate_textEdit.setFont(font)
        self.baudrate_textEdit.setObjectName("baudrate_textEdit")
        self.verticalLayout.addWidget(self.baudrate_textEdit)
        self.send_data_textEdit = QtWidgets.QTextEdit(self.verticalLayoutWidget)
        font = QtGui.QFont()
        font.setPointSize(15)
        self.send_data_textEdit.setFont(font)
        self.send_data_textEdit.setObjectName("send_data_textEdit")
        self.verticalLayout.addWidget(self.send_data_textEdit)
        self.verticalLayoutWidget_2 = QtWidgets.QWidget(self.para_frame)
        self.verticalLayoutWidget_2.setGeometry(QtCore.QRect(120, 40, 179, 441))
        self.verticalLayoutWidget_2.setObjectName("verticalLayoutWidget_2")
        self.verticalLayout_2 = QtWidgets.QVBoxLayout(self.verticalLayoutWidget_2)
        self.verticalLayout_2.setContentsMargins(0, 0, 0, 0)
        self.verticalLayout_2.setSpacing(20)
        self.verticalLayout_2.setObjectName("verticalLayout_2")
        self.label = QtWidgets.QLabel(self.verticalLayoutWidget_2)
        font = QtGui.QFont()
        font.setPointSize(15)
        font.setBold(True)
        font.setWeight(75)
        self.label.setFont(font)
        self.label.setFrameShape(QtWidgets.QFrame.StyledPanel)
        self.label.setAlignment(QtCore.Qt.AlignCenter)
        self.label.setObjectName("label")
        self.verticalLayout_2.addWidget(self.label)
        self.label_4 = QtWidgets.QLabel(self.verticalLayoutWidget_2)
        font = QtGui.QFont()
        font.setPointSize(15)
        font.setBold(True)
        font.setWeight(75)
        self.label_4.setFont(font)
        self.label_4.setFrameShape(QtWidgets.QFrame.StyledPanel)
        self.label_4.setAlignment(QtCore.Qt.AlignCenter)
        self.label_4.setObjectName("label_4")
        self.verticalLayout_2.addWidget(self.label_4)
        self.label_2 = QtWidgets.QLabel(self.verticalLayoutWidget_2)
        font = QtGui.QFont()
        font.setPointSize(15)
        font.setBold(True)
        font.setWeight(75)
        self.label_2.setFont(font)
        self.label_2.setFrameShape(QtWidgets.QFrame.StyledPanel)
        self.label_2.setAlignment(QtCore.Qt.AlignCenter)
        self.label_2.setObjectName("label_2")
        self.verticalLayout_2.addWidget(self.label_2)
        self.label_3 = QtWidgets.QLabel(self.verticalLayoutWidget_2)
        font = QtGui.QFont()
        font.setPointSize(15)
        font.setBold(True)
        font.setWeight(75)
        self.label_3.setFont(font)
        self.label_3.setFrameShape(QtWidgets.QFrame.StyledPanel)
        self.label_3.setMidLineWidth(1)
        self.label_3.setAlignment(QtCore.Qt.AlignCenter)
        self.label_3.setObjectName("label_3")
        self.verticalLayout_2.addWidget(self.label_3)
        self.label_5 = QtWidgets.QLabel(self.verticalLayoutWidget_2)
        font = QtGui.QFont()
        font.setPointSize(15)
        font.setBold(True)
        font.setWeight(75)
        self.label_5.setFont(font)
        self.label_5.setFrameShape(QtWidgets.QFrame.StyledPanel)
        self.label_5.setMidLineWidth(1)
        self.label_5.setAlignment(QtCore.Qt.AlignCenter)
        self.label_5.setObjectName("label_5")
        self.verticalLayout_2.addWidget(self.label_5)
        self.horizontalLayoutWidget_4 = QtWidgets.QWidget(self.para_frame)
        self.horizontalLayoutWidget_4.setGeometry(QtCore.QRect(40, 540, 831, 71))
        self.horizontalLayoutWidget_4.setObjectName("horizontalLayoutWidget_4")
        self.horizontalLayout_4 = QtWidgets.QHBoxLayout(self.horizontalLayoutWidget_4)
        self.horizontalLayout_4.setContentsMargins(0, 0, 0, 0)
        self.horizontalLayout_4.setObjectName("horizontalLayout_4")
        self.sent_data_pushButton = QtWidgets.QPushButton(self.horizontalLayoutWidget_4)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.sent_data_pushButton.sizePolicy().hasHeightForWidth())
        self.sent_data_pushButton.setSizePolicy(sizePolicy)
        font = QtGui.QFont()
        font.setPointSize(20)
        font.setBold(True)
        font.setWeight(75)
        self.sent_data_pushButton.setFont(font)
        self.sent_data_pushButton.setObjectName("sent_data_pushButton")
        self.horizontalLayout_4.addWidget(self.sent_data_pushButton)
        self.network_port_pushButton = QtWidgets.QPushButton(self.horizontalLayoutWidget_4)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.network_port_pushButton.sizePolicy().hasHeightForWidth())
        self.network_port_pushButton.setSizePolicy(sizePolicy)
        font = QtGui.QFont()
        font.setPointSize(20)
        font.setBold(True)
        font.setWeight(75)
        self.network_port_pushButton.setFont(font)
        self.network_port_pushButton.setObjectName("network_port_pushButton")
        self.horizontalLayout_4.addWidget(self.network_port_pushButton)
        self.comfirm_para = QtWidgets.QPushButton(self.horizontalLayoutWidget_4)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.comfirm_para.sizePolicy().hasHeightForWidth())
        self.comfirm_para.setSizePolicy(sizePolicy)
        font = QtGui.QFont()
        font.setPointSize(20)
        font.setBold(True)
        font.setWeight(75)
        self.comfirm_para.setFont(font)
        self.comfirm_para.setObjectName("comfirm_para")
        self.horizontalLayout_4.addWidget(self.comfirm_para)
        self.clear_para = QtWidgets.QPushButton(self.horizontalLayoutWidget_4)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.clear_para.sizePolicy().hasHeightForWidth())
        self.clear_para.setSizePolicy(sizePolicy)
        font = QtGui.QFont()
        font.setPointSize(20)
        font.setBold(True)
        font.setWeight(75)
        self.clear_para.setFont(font)
        self.clear_para.setObjectName("clear_para")
        self.horizontalLayout_4.addWidget(self.clear_para)
        self.state_frame = QtWidgets.QFrame(self.centralwidget)
        self.state_frame.setGeometry(QtCore.QRect(10, 820, 1041, 21))
        self.state_frame.setFrameShape(QtWidgets.QFrame.Box)
        self.state_frame.setFrameShadow(QtWidgets.QFrame.Raised)
        self.state_frame.setObjectName("state_frame")
        self.horizontalLayoutWidget_3 = QtWidgets.QWidget(self.state_frame)
        self.horizontalLayoutWidget_3.setGeometry(QtCore.QRect(0, 0, 1041, 22))
        self.horizontalLayoutWidget_3.setObjectName("horizontalLayoutWidget_3")
        self.horizontalLayout_3 = QtWidgets.QHBoxLayout(self.horizontalLayoutWidget_3)
        self.horizontalLayout_3.setContentsMargins(0, 0, 0, 0)
        self.horizontalLayout_3.setObjectName("horizontalLayout_3")
        self.daoyingtou_state_label = QtWidgets.QLabel(self.horizontalLayoutWidget_3)
        self.daoyingtou_state_label.setObjectName("daoyingtou_state_label")
        self.horizontalLayout_3.addWidget(self.daoyingtou_state_label)
        self.daoyingtou_state_label_1 = QtWidgets.QLabel(self.horizontalLayoutWidget_3)
        self.daoyingtou_state_label_1.setText("")
        self.daoyingtou_state_label_1.setObjectName("daoyingtou_state_label_1")
        self.horizontalLayout_3.addWidget(self.daoyingtou_state_label_1)
        self.template_state_label = QtWidgets.QLabel(self.horizontalLayoutWidget_3)
        self.template_state_label.setObjectName("template_state_label")
        self.horizontalLayout_3.addWidget(self.template_state_label)
        self.template_state_label_2 = QtWidgets.QLabel(self.horizontalLayoutWidget_3)
        self.template_state_label_2.setText("")
        self.template_state_label_2.setObjectName("template_state_label_2")
        self.horizontalLayout_3.addWidget(self.template_state_label_2)
        self.horizontalLayout_3.setStretch(1, 2)
        self.horizontalLayout_3.setStretch(3, 2)
        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtWidgets.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 1112, 23))
        self.menubar.setObjectName("menubar")
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)

        self.retranslateUi(MainWindow)
        self.close_window.clicked.connect(MainWindow.close) # type: ignore
        self.para_setting.clicked.connect(self.template_frame.hide) # type: ignore
        self.para_setting.clicked.connect(self.para_frame.show) # type: ignore
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "模版装订"))
        self.para_setting.setText(_translate("MainWindow", "参数设置"))
        self.para_setting.setShortcut(_translate("MainWindow", "S"))
        self.close_window.setText(_translate("MainWindow", "关闭窗口"))
        self.RGB_Label.setText(_translate("MainWindow", "RGB模板"))
        self.IR_Label.setText(_translate("MainWindow", "IR模板"))
        self.select_RGB_templates.setText(_translate("MainWindow", "选择RGB模版"))
        self.select_RGB_templates.setShortcut(_translate("MainWindow", "S"))
        self.select_IR_templates.setText(_translate("MainWindow", "选择IR模版"))
        self.select_IR_templates.setShortcut(_translate("MainWindow", "S"))
        self.send_templates.setText(_translate("MainWindow", "发送模版"))
        self.check_sended_templates.setText(_translate("MainWindow", "已发送模版"))
        self.clear_templates.setText(_translate("MainWindow", "清空模板"))
        self.label.setText(_translate("MainWindow", "导引头IP地址:"))
        self.label_4.setText(_translate("MainWindow", "导引头端口:"))
        self.label_2.setText(_translate("MainWindow", "串口号:"))
        self.label_3.setText(_translate("MainWindow", "波特率:"))
        self.label_5.setText(_translate("MainWindow", "串口发送内容:"))
        self.sent_data_pushButton.setText(_translate("MainWindow", "串口发送数据"))
        self.network_port_pushButton.setText(_translate("MainWindow", "网口连接测试"))
        self.comfirm_para.setText(_translate("MainWindow", "确认参数"))
        self.comfirm_para.setShortcut(_translate("MainWindow", "S"))
        self.clear_para.setText(_translate("MainWindow", "清空参数"))
        self.clear_para.setShortcut(_translate("MainWindow", "S"))
        self.daoyingtou_state_label.setText(_translate("MainWindow", "板子状态:"))
        self.template_state_label.setText(_translate("MainWindow", "模板状态:"))

2. add_templates_utils.py

import os
import shutil
import socket
import struct
import serial
import tkinter
import re

# 退出默认的tk窗口
def exit_tk():
    window = tkinter.Tk()
    window.withdraw()  # 退出默认 tk 窗口

# 操作文件夹类
class Operate_Dir():
    def __init__(self):
        pass

    # 如果文件夹不存在则创建文件夹
    def make_dir(self,dir):
        if not os.path.exists(dir):
            os.makedirs(dir)

# 导引头串口相关操作类
class Serial_port():
    def __init__(self):
        self.serial = None

    def open_serial(self, serial_port, baudrate, timeout=1):
        """
        打开串口。
        """
        try:
            # 尝试打开指定的串口
            self.serial = serial.Serial(serial_port, baudrate=baudrate, timeout=timeout)
            # 如果打开成功,返回True
            return True
        except serial.SerialException as e:
            # 如果打开串口失败,返回False
            return False

    def close_serial(self):
        """
        关闭串口。
        """
        if self.serial and self.serial.isOpen():
            self.serial.close()

    def write(self, data):
        """
        向串口写入数据。
        :param data: 要写入的数据,可以是字符串或字节串
        """
        if self.serial and self.serial.isOpen():
            try:
                self.serial.write(bytes.fromhex(data) if isinstance(data, str) else data)
            except serial.SerialException as e:
                print(f"写入数据时出错: {e}")

    def read(self, size=12):
        """
        从串口读取数据。
        :param size: 要读取的字节数
        :return: 读取到的数据
        """
        if self.serial and self.serial.isOpen():
            try:
                return self.serial.read(size)
            except serial.SerialException as e:
                print(f"读取数据时出错: {e}")
                return None

# 网口发送接收数据的类
class Send_Rev_Imgs_Netport():
    def __init__(self):
        pass

    # 解析网口获取的图片路径,b'D:\\desk\\test_django\\79_4.jpg\xbb\xe6\x06\x00',去除多余部分,返回D:\\desk\\test_django\\79_4.jpg字符串
    def parser_img_path(self, path_bytes=b''):
        # 要查找的扩展名列表
        extensions = (b'.jpg', b'.png', b'.bmp', b'.jpeg')
        # 遍历每个扩展名
        for ext in extensions:
            len_suffix = len(ext)
            # 查找扩展名第一次出现的位置
            pos = path_bytes.find(ext)

            if pos != -1:
                # 截取从开始到包括最后一个反斜杠的部分
                path_and_filename_bytes = path_bytes[:pos + len_suffix]

                # 使用 UTF-8 解码提取的部分
                path_str = path_and_filename_bytes.decode('utf-8')

                return path_str
            else:
                return None

    # 网口发送图片
    def send_imgs_2_netport(self,img_path,ip, ip_port):
        # 创建socket对象
        client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        try:
            client_socket.connect((ip, int(ip_port)))  # 连接到Ubuntu单片机的IP地址和端口

            # 发送文件名
            client_socket.send(img_path.encode('utf-8'))

            # 发送文件大小
            with open(img_path, 'rb') as f:  # 确保文件在这里打开
                filesize = f.seek(0, 2)  # 获取文件大小
                f.seek(0)
                client_socket.send(struct.pack('<I', filesize))  # 发送文件大小,使用小端序

                # 发送文件数据
                while True:
                    chunk = f.read(1024)
                    if not chunk:
                        break
                    client_socket.send(chunk)
            print("文件发送完成。")
            return True
        except Exception as e:
            print(f"发送过程中发生错误: {e}")
            return False
        finally:
            client_socket.close()  # 确保socket连接被关闭

    # 网口接收图片

    # 套接字方式通过网口接收图片模板
    def receive_image_from_networkport(self, ip, ip_port):
        """
        确定输入是红外还是可见光,放在不同的文件夹目录
        返回保存在下位机的模板的路径,以便后续调用
        """
        # 创建socket对象
        server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        server_socket.bind((ip, int(ip_port)))  # 监听所有网络接口上的12345端口
        server_socket.listen(5)  # 最多可以挂起5个未完成的连接
        print("等待连接...")

        # 接受连接
        client_socket, addr = server_socket.accept()
        print("连接地址: %s" % str(addr))

        # 接收文件名和文件大小
        filename = self.parser_img_path(client_socket.recv(1024))
        img_name = filename.split("\\")[-1]

        # 通过文件名,设置保存路径
        if "rgb_template" in img_name:
            save_img_dir = os.path.join(os.getcwd(), r"temp/RGB")
        elif "infrared_template" in img_name:
            save_img_dir = os.path.join(os.getcwd(), r"temp/IR")
        Operate_Dir().make_dir(save_img_dir)

        save_img_path = os.path.join(save_img_dir, img_name)

        # 接收文件数据
        with open(save_img_path, 'wb') as f:
            while True:
                chunk = client_socket.recv(1024)
                if not chunk:
                    break
                f.write(chunk)
        print("模板图片上传成功!")
        client_socket.close()
        server_socket.close()

        print("save_img_path", save_img_path)
        return save_img_path


# 测试网口是否能够ping通
import subprocess
import platform
def ping_host(ip_address, count=1):
    # 根据操作系统选择ping命令
    ping_command = ['ping', '-n', str(count), ip_address] if platform.system().lower() == 'windows' else ['ping', '-c', str(count), ip_address]

    # 执行ping命令
    try:
        result = subprocess.run(ping_command,shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)

        # 检查返回码
        if result.returncode == 0:
            print(f"主机 {ip_address} 已响应 ping 请求。")
            return True
        else:
            print(f"主机 {ip_address} 没有响应 ping 请求。")
            return False
    except Exception as e:
        print(f"执行 ping 命令时发生错误: {e}")
        return False


# 检测设备的以太网适配器IP地址
import psutil
import socket

def get_ethernet_adapter_ip():
    # 获取所有网络接口的详细信息
    interfaces = psutil.net_if_addrs()

    # 遍历所有网络接口
    for interface_name, interface_addresses in interfaces.items():
        # 检查接口是否是UP状态,并且不是回环接口
        if interface_name.lower() != 'lo' and psutil.net_if_stats()[interface_name].isup:
            # 遍历接口的所有地址
            for address in interface_addresses:
                # 检查地址是否是IPv4地址
                if address.family == socket.AF_INET:
                    return interface_name, address.address

    return None, None  # 如果没有找到或发生错误,返回None

3. add_templates_app.py

import time

from PyQt5.QtCore import QDir, QStringListModel
from PyQt5.QtGui import QPixmap
from PyQt5.QtWidgets import QMainWindow, QFileDialog, QAbstractItemView

from ADD_TEMPLATES_QT import Ui_MainWindow  # 确保导入你的UI类
from PyQt5.QtCore import Qt,QTimer

from tkinter.messagebox import *
from add_templates_utils import *


class MainWindow(QMainWindow, Ui_MainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()
        self.setupUi(self)  # 设置UI界面

        # 初始化参数
        self.init()

        # 选择上传哪个模板
        self.select_RGB_templates.clicked.connect(self.choose_RGB_templates)
        self.select_IR_templates.clicked.connect(self.choose_IR_templates)

        # 上传模板
        self.send_templates.clicked.connect(self.send_template_fun)

        # 查看上传的模板
        self.check_sended_templates.clicked.connect(self.check_sended_templates_fun)

        # 双击list显示图片
        self.RGB_list.doubleClicked.connect(self.RGB_list_double_clicked_fun)
        self.IR_list.doubleClicked.connect(self.IR_list_double_clicked_fun)

        # 清空模板
        self.clear_templates.clicked.connect(self.Clear_templates_fun)

        # 参数设置

        # 清空参数
        self.clear_para.clicked.connect(self.clear_Edittext)

        # 提交参数
        self.comfirm_para.clicked.connect(self.get_all_para)

        # 测试串口连接是否成功
        self.sent_data_pushButton.clicked.connect(self.test_serial_fun)

        #  测试网口连接是否成功
        self.network_port_pushButton.clicked.connect(self.test_netport_fun)


    def init(self):

        # 所有参数列表框名
        self.para_list = [self.IP_textEdit,self.PORT_textEdit,self.serial_textEdit,self.baudrate_textEdit,self.send_data_textEdit]

        # 选中的要发送的模板路径相关参数字典
        self.selected_img_info={"RGB_FLAG":True,"IMG_PATH":""}

        # 参数框的值字典,设定初始值
        self.para_info={                        # "ip" : '192.168.137.39',
                        "ip" : '10.77.240.116',
                        "ip_port" : '12345',
                        "serial_port" : "COM4",
                        "baudrate" : "9600",
                        "send_data" : "aa0a00000100000000000001",
                        }

        # 初始化参数框的值
        self.init_para_textEdit()

        #参数框是否为空标志
        self.para_empty_flag = False

        # 退出默认的tk界面
        self.exit_tk = exit_tk()

        # 防止添加的模板列表被用户更改
        self.RGB_list.setEditTriggers(QAbstractItemView.NoEditTriggers)
        self.IR_list.setEditTriggers(QAbstractItemView.NoEditTriggers)

        # 导引头类导入
        self.serial_port = Serial_port()

        # 网口接收发送图片
        self.s_r_imgs_netport = Send_Rev_Imgs_Netport()

        # 创建串口发送指令
        self.serial_port = Serial_port()


    # 初始化参数框的值
    def init_para_textEdit(self):
        # 刚进入界面把添加模板框架设置为不可见
        self.template_frame.setVisible(False)

        # 注意参数框列表和字典一一对应!!!!!!!!!
        for i, key in enumerate(self.para_info):
            self.para_list[i].setText(self.para_info[key])


    # 检查参数设置中是否有重要的参数为空
    def check_para_is_empety(self):
        for para in self.para_list[:-1]:
            if para.toPlainText().strip()=="":
                self.para_empty_flag = True
                return
            else:
                self.para_empty_flag = False

    # 把参数框里的参数赋值给para_info字典
    def textvalue_2_para_info(self):
        for i, key in enumerate(self.para_info):
            self.para_info[key] = self.para_list[i].toPlainText().strip()

    # 获取参数框设置中所有的参数
    def get_all_para(self):
        self.check_para_is_empety()
        if not self.para_empty_flag:

            # 把参数框里的参数赋值给para_info字典
            self.textvalue_2_para_info()

            # 更新板子状态
            serial_flag = self.test_serial_fun()
            network_flag = self.test_netport_fun()

            if serial_flag and network_flag:
                self.daoyingtou_state_label_1.setText(
                    "{}串口连接正常!, {}网口连接正常!".format(self.para_info["serial_port"], self.para_info["ip"]))
            elif serial_flag and not network_flag:
                self.daoyingtou_state_label_1.setText(
                    "{}串口连接正常!, {}网口连接失败!请检查!".format(self.para_info["serial_port"], self.para_info["ip"]))
            elif not serial_flag and network_flag:
                self.daoyingtou_state_label_1.setText(
                    "{}串口连接失败!请检查!, {}网口连接正常!".format(self.para_info["serial_port"], self.para_info["ip"]))
            else:
                self.daoyingtou_state_label_1.setText(
                    "{}串口连接失败!请检查!, {}网口连接失败!请检查!".format(self.para_info["serial_port"], self.para_info["ip"]))

            # 显示模板装订界面,隐藏参数设置界面
            self.template_frame.setVisible(True)
            self.para_frame.setVisible(False)

        else:
            self.exit_tk
            showerror('错误', '请确保IP、端口、串口、波特率参数均被正确填入')

    # 清空参数文本框
    def clear_Edittext(self):
        for para in self.para_list:
            para.clear()
        self.exit_tk
        showinfo('提示', '参数已被清空')


    # 在label中显示图片
    def show_img_in_label(self,file_path=""):
        if file_path:
            # 使用QPixmap加载选中的图片
            pixmap = QPixmap(file_path)
            # 调整图片大小以适应images_container
            scaled_pixmap = pixmap.scaled(self.images_container.size(), Qt.KeepAspectRatio,
                                          Qt.SmoothTransformation)

            # 将图片设置到images_container上
            self.images_container.setPixmap(scaled_pixmap)

    # 在本地打开模板图片并显示
    def open_image_dialog_fun(self):
        # 获取当前工作目录
        current_directory = os.path.join(QDir.currentPath(),"temp")
        # 设置文件过滤器,只显示图片格式
        image_filter = "Image files (*.jpg *.jpeg *.bmp *.png)"
        # 打开文件对话框,让用户选择图片
        file_path, _ = QFileDialog.getOpenFileName(
            None,  # 父窗口,None表示没有父窗口
            "Select Image",  # 对话框标题
            current_directory,  # 初始目录
            image_filter  # 文件过滤器
        )

        # 检查用户是否选择了文件并显示图片在qlabel
        self.show_img_in_label(file_path)
        return file_path

    # 获得用户选中的模板文件路径   并确定  模板为可见光还是红外光
    def choose_RGB_templates(self):
        self.selected_img_info["RGB_FLAG"] = True
        self.template_state_label_2.setText("准备装订可见光模板!")
        self.selected_img_info["IMG_PATH"] = self.open_image_dialog_fun()

    def choose_IR_templates(self):
        self.selected_img_info["RGB_FLAG"] = False
        self.template_state_label_2.setText("准备装订红外光模板!")
        self.selected_img_info["IMG_PATH"] = self.open_image_dialog_fun()



    # 测试串口连接是否正常
    def test_serial_fun(self):
        # prompt参数为仅有在单独测试时才显示,在其他情况调用的时候不显示

        # 判断重要参数是否为空,不为空进行测试
        if self.serial_textEdit.toPlainText().strip()!="" and self.baudrate_textEdit.toPlainText().strip()!="" and self.send_data_textEdit.toPlainText().strip()!="":
            # 先把文本框里的值赋给para_info
            self.textvalue_2_para_info()

            serial_port_flag = self.serial_port.open_serial(self.para_info["serial_port"], self.para_info["baudrate"])
            if serial_port_flag:
                # 向串口写入数据测试
                self.serial_port.write(self.para_info["send_data"])
                self.serial_port.close_serial()
                showinfo("提示","{}串口连接正常!".format(self.para_info["serial_port"]))
                return serial_port_flag

            else:
                showerror("错误", "{}串口连接失败!请检查!".format(self.para_info["serial_port"]))
                return serial_port_flag

        else:
            showerror("错误", "请确保串口、波特率参数均被正确填入!")

    # 测试网口连接是否正常
    def test_netport_fun(self):
        # 判断ip文本框里是否有值
        if self.IP_textEdit.toPlainText().strip():
            # 先把文本框里的值赋给para_info
            self.textvalue_2_para_info()
            # 调用函数并传入IP地址,判断能否ping通
            net_port_flag = ping_host(self.para_info["ip"])
            if net_port_flag:
                showinfo("提示","{}网口连接正常!".format(self.para_info["ip"]))
                return net_port_flag
            else:

                showerror("错误", "{}网口连接失败!请检查!".format(self.para_info["ip"]))
                return net_port_flag
        else:
            showerror("错误", "请确保IP参数均被正确填入!")


    # 发送模板至下位机
    def send_template_fun(self):

        # 判断是否选择了模板?
        if self.selected_img_info["IMG_PATH"].strip() == "":
            showerror("错误", "请选择要装订的模板")

        else:
            # 上传可见光模板图片串口命令
            if self.selected_img_info["RGB_FLAG"]:
                self.para_info["send_data"] = "aa0a00000100000000000001"

            # 上传红外光模板图片串口命令
            if not self.selected_img_info["RGB_FLAG"]:
                self.para_info["send_data"] ="aa0a00000200000000000002"

            # 创建串口
            send_data = self.para_info["send_data"]
            self.serial_port.write(send_data)

            # 留点给下位机准备接收模板服务器准备的时间
            time.sleep(1)

            # 此处应该得到导引头的反馈,即导引头应该返回一些数据告诉上位机它的状态,当导引头准备好接收网口的图片后,上位机再发送图片模板
            send_template_flag = self.s_r_imgs_netport.send_imgs_2_netport(self.selected_img_info["IMG_PATH"],self.para_info["ip"],self.para_info["ip_port"])
            if send_template_flag:
                self.template_state_label_2.setText("{}模板装订成功!".format(self.selected_img_info["IMG_PATH"]))
            else:
                self.template_state_label_2.setText("{}模板装订失败!".format(self.selected_img_info["IMG_PATH"]))

            # 关闭串口
            self.serial_port.close_serial()



    # 查看发送了哪些模板到导引头,把所有的模板从导引头下载到本地,查看本地的文件即可
    def check_sended_templates_fun(self):

        # # 向串口发送数据让下位机把模板图片全部发给上位机
        send_data = b'\xaa\n\x00\x00\x00\x00\x01\x00\x00\x00\x00\x01'
        self.serial_port.write(send_data)

        # 获取以太网适配器的名称和IP地址
        eth_adapter_name, eth_adapter_ip = get_ethernet_adapter_ip()
        self.s_r_imgs_netport.receive_image_from_networkport(ip=eth_adapter_ip, ip_port=12345)

        # 从导引头传输所有的模板,保存至根目录下的temp文件夹中
        # IR文件夹、RGB文件夹

        pwd = os.getcwd()
        self.IR_dir=os.path.join(pwd,r"temp\IR")
        self.RGB_dir=os.path.join(pwd,r"temp\RGB")

        self.IR_img_list = os.listdir(self.IR_dir)
        self.RGB_img_list = os.listdir(self.RGB_dir)


        # 实例化列表模型,添加数据
        RGB_slm = QStringListModel()
        RGB_slm.setStringList(self.RGB_img_list)
        self.RGB_list.setModel(RGB_slm)

        IR_slm = QStringListModel()
        IR_slm.setStringList(self.IR_img_list)
        self.IR_list.setModel(IR_slm)


    # 双击查看图片
    def RGB_list_double_clicked_fun(self, qModelIndex):
        img_path = os.path.join(self.RGB_dir,self.RGB_img_list[qModelIndex.row()])
        self.show_img_in_label(img_path)

    def IR_list_double_clicked_fun(self, qModelIndex):
        img_path = os.path.join(self.IR_dir,self.IR_img_list[qModelIndex.row()])
        self.show_img_in_label(img_path)


    # 清空所有的模板图片及数据库
    def Clear_templates_fun(self):
        # 调用串口发送清除模板的指令
        self.para_info["send_data"] = "aa0a00000300000000000003"
        send_data = self.para_info["send_data"]
        self.serial_port.write(send_data)
        self.serial_port.close_serial()

4. main.py

import sys
from PyQt5.QtWidgets import QApplication
from add_templates_app import MainWindow

if __name__ == "__main__":
    app = QApplication(sys.argv)
    mainWin = MainWindow()
    mainWin.show()
    sys.exit(app.exec_())

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

张飞飞飞飞飞

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值