linux LPT和COM回路测试(基于python+Qt+C++)

时间:2024-01-21 15:01:30

软件UI:

回路治具(COM+LPT):

lpt_test.cpp(c++ 源代码):

#include <iostream>
#include <fstream>
#include <sstream>
#include <unistd.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <linux/parport.h>
#include <linux/ppdev.h>
#include <string>
#include <map>

//using namespace std;
int main() {

    // Use ANSI escape codes for coloring the output
    const char* RED = "\033[31m";   // Red color start
    const char* GREEN = "\033[32m"; // Green color start
    const char* RESET = "\033[0m";  // Reset to default color

    std::ifstream config_file("./Conf/lptconfig.txt");
    std::map<std::string, std::string> config;
    std::string line;
    unsigned char config_args_A;
    unsigned char config_args_B;
    unsigned char status;

    if (!config_file.is_open()) {
        std::cerr << "无法打开配置文件" << std::endl;
        return 1;
    }

    while (std::getline(config_file, line)) {
        std::istringstream is_line(line);
        std::string key;
        if (std::getline(is_line, key, '=')) {
            std::string value;
            if (std::getline(is_line, value)) {
                config[key] = value;
            }
        }
    }

    config_file.close();

    //const char* parport = config["parport"].c_str();

    config_args_A = static_cast<unsigned char>(std::stoi(config["Args_2"]));//读取参数1
    config_args_B=static_cast<unsigned char>(std::stoi(config["Args_1"]));//读取参数2
    const char* parport = "/dev/parport0";
    int fd = open(parport, O_RDWR);
    if (fd == -1) {
        std::cerr<<"无法打开并口设备 "<<parport<<std::endl;
        return 1;
    }

    if (ioctl(fd, PPCLAIM)) {
        std::cerr<<"无法获取并口的控制权"<<std::endl;
        close(fd);
        return 1;
    }

    // 发送数字1到并口50次
    for (int i = 0; i < 5; ++i) {
        // 写入数据
        unsigned char data = 1; // 要发送的数据
        if (ioctl(fd, PPWDATA, &data)) {
            std::cerr << "在写入数据 " << static_cast<int>(data) << " 时发生错误" << std::endl;
            break;
        }

        usleep(1000); // 延时以确保写入完成

        // 读取数据
        if (ioctl(fd, PPRSTATUS, &status)) {
            std::cerr << "在读取数据时发生错误" << std::endl;
            break;
        }
        std::cout << "写入 " << static_cast<int>(data) << ", 读取 " << static_cast<int>(status) << std::endl;
    }

    if (ioctl(fd, PPRELEASE)) {
        std::cerr << "无法释放并口控制权" << std::endl;
    }

    close(fd);

    if (static_cast<int>(config_args_A) == static_cast<int>(status)||static_cast<int>(config_args_B) == static_cast<int>(status)) {
        std::cout << GREEN << "Test PASS!!" << RESET << std::endl;
        return 0;
    }
    std::cout << RED << "Test FAIL!!" << RESET << std::endl;
    return 1;
}
COMLPTTest.py(Python+Qt源代码)
# -*- coding: utf-8 -*-

# Form implementation generated from reading ui file 'COMLPTTest.ui'
#
# Created by: PyQt5 UI code generator 5.15.2
#
# 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.

import sys
from PyQt5 import *
from PyQt5.Qt import *
from PyQt5 import QtWidgets
from PyQt5 import QtGui
from PyQt5 import QtCore
import logging
import os
import json
import configparser
import serial
import subprocess
import io
import glob
import re#正则表达式
#pip install pyserial

class AnalysisThread(QtCore.QThread):
    test_result_signal = QtCore.pyqtSignal(tuple)  # 新增信号,传递一个包含设备路径和测试结果的元组
    def __init__(self, devicepath,type, parent=None):
        super(AnalysisThread, self).__init__(parent)
        self.devicepath = devicepath
        self.type=type
        self.is_running = True

    def run(self):
        result = False
        if self.type == 'com':
            result = self.parent().ComTest(self.devicepath[1])
            if result:
                self.parent().rtsComTestPortInfo.remove(self.devicepath)
                self.parent().tsComTestPortInfops.append(self.devicepath)
                self.parent().TableAddItem(self.devicepath, True)  # 添加PASS数据
                self.parent().lbl_COMResult.setText(str(len(self.parent().tsComTestPortInfops)))
                self.parent().lbl_COMResult.setStyleSheet("background-color: lightgreen;")  # 后置端口背景色设置为浅绿色
        elif self.type == 'lpt':
            result = self.parent().LptTest(self.devicepath[1])
            if result:
                self.parent().rtsLptTestPortInfo.remove(self.devicepath)
                self.parent().tsLptTestPortInfops.append(self.devicepath)
                self.parent().TableAddItem(self.devicepath, True)  # 添加PASS数据
                self.parent().lbl_LPTResult.setText(str(len(self.parent().tsLptTestPortInfops)))
                self.parent().lbl_LPTResult.setStyleSheet("background-color: lightgreen;")  # 后置端口背景色设置为浅绿色

        self.test_result_signal.emit((self.devicepath, result))
        self.stop()
        # while self.is_running:
        #     # 在这里执行串口或者并口测试
        #     if self.type=='com':#串口测试
        #         if self.parent().ComTest(self.devicepath[1])==True:
        #             self.parent().rtsComTestPortInfo.remove(self.devicepath)#移除串口内容
        #             self.parent().tsComTestPortInfops.append(self.devicepath)
        #             self.parent().TableAddItem(self.devicepath,True)#添加PASS数据
        #             self.parent().lbl_COMResult.setText(str(len(self.parent().tsComTestPortInfops)))
        #             self.parent().lbl_COMResult.setStyleSheet("background-color: lightgreen;")  # 后置端口背景色设置为浅绿色
        #         else:
        #             self.parent().TableAddItem(self.devicepath,False)#添加FAIL数据
        #         result = self.parent().ComTest(self.devicepath[1])
        #         self.test_result_signal.emit((self.devicepath, result))
        #     elif self.type=='lpt':#并口测试
        #         if self.parent().LptTest(self.devicepath[1])==True:
        #             self.parent().rtsLptTestPortInfo.remove(self.devicepath)#移除LPT内容
        #             self.parent().tsLptTestPortInfops.append(self.devicepath)
        #             self.parent().TableAddItem(self.devicepath,True)#添加PASS数据
        #             self.parent().lbl_LPTResult.setText(str(len(self.parent().tsLptTestPortInfops)))
        #             self.parent().lbl_LPTResult.setStyleSheet("background-color: lightgreen;")  # 后置端口背景色设置为浅绿色
        #         else:
        #             self.parent().TableAddItem(self.devicepath,False)#添加FAIL数据
        #         result = self.parent().LptTest(self.devicepath[1])
        #         self.test_result_signal.emit((self.devicepath, result))
        #     #self.parent().AnalysisSoundFile_Frequency(self.filename,self.type)
        #     #self.parent().standard_frequency=int(self.parent().AnalysisSound_FrequencySample)#标准的频响
        #     self.stop()
    def stop(self):
        self.is_running = False # 或者使用更安全的停止逻辑

class Ui_COMLPTTest(QWidget):
    updateTimer=pyqtSignal(bool)#
    def __init__(self):
        super().__init__()
        self.analysis_threads = []  # 存储所有的 AnalysisThread 实例
        #self.record_play_threads = []  # 存储所有的 RecordPlayThread 实例

        # 设置环境变量
        #os.environ["XDG_RUNTIME_DIR"] = "/run/user/{}".format(os.getuid())
        self.config = configparser.ConfigParser()  # 创建对象
        self.itemName = ''  # 项目名称
        self.itemFailSleepExit = 0  # 项目Fail延时退出
        self.testArgs = []  # 测试参数信息
        self.testStandardArgs=''#测试准标参数
        self.ComTestCount=1# COM测试数
        self.LptTestCount=1# LPT测试数
        self.testModel=True#设置为自动测试模式
        self.tbrowIndex=0#表单指针

        #测试PASS接口
        self.tsComTestPortInfops=[]#测试PASS COM接口
        self.tsLptTestPortInfops=[]#测试PASS LPT接口

        # 检测到串口信息
        self.rtsComTestPortInfo=[]#读取COM接口
        self.rtsLptTestPortInfo=[]#读取Lpt接口

        # 生成日志信息
        self.logger = logging.getLogger('my_logger')  # 步骤1 创建日志记录器
        self.logger.setLevel(logging.DEBUG)  # 步骤2 将指定日志级别
        self.file_handler = logging.FileHandler('./log/log.txt')  # 步骤3 创建文件处理器
        self.formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')  # 步骤4 创建格式化器
        self.file_handler.setFormatter(self.formatter)  # 步骤4 将格式化器添加到处理器
        self.logger.addHandler(self.file_handler)  # 步骤5 将处理器添加到日志记录器

        # 读取配置
        self.config.read('./Conf/config.conf', encoding='utf-8')  # 读取配置文件,如果配置文件不存在则创建

        # 读取测试配置
        self.itemName = self.config.get('TestItemNameArrays', 'COMLPTTestName')  # 项目名称
        self.itemFailSleepExit = int(self.config.get('TestItemWinFrmSleepExit', 'COMLPTTestName'))  # 项目测试Fail延时退出
        self.testArgs = self.ReadJsonInfo('./Conf/TestArgs.json')  # 读取测试参数信息
        if self.ReadJsonTestArgs(self.itemName)==True:#获取标准参数
            testArgs=[]#测试参数
            testArgs=self.testStandardArgs.split('|')
            comArgs=testArgs[0]#分割com测试参数
            lptArgs=testArgs[1]#分割lpt测试参数
            testModel=testArgs[2]#分割测试模式
            self.ComTestCount=int(comArgs[comArgs.find('=') + 1:])
            self.LptTestCount=int(lptArgs[lptArgs.find('=') + 1:])
            testModel=testModel[testModel.find('=') + 1:]
            if testModel=='True':
                self.testModel=True
            else:
                self.testModel=False
            self.setupUi()  # 初始化
            if self.GetTestPortInfo()==True:#获取测试COM和LPT接口信息
                # 创建一个定时器来检查视频是否播放结束
                self.timer = QTimer(self)
                self.timer.setInterval(1000)  # 每秒检查一次
                self.timer.timeout.connect(self.check_Test)
                self.timer.start()

                # 连接信号到槽
                self.updateTimer.connect(self.handleTimer)

                # 启动线程
                #self.start_analysis_threads()
        else:
            sys.exit(1)


    #校验是否完成测试
    def check_Test(self):
        try:
            if self.ComTestCount==len(self.tsComTestPortInfops) and self.LptTestCount==len(self.tsLptTestPortInfops):#判断测试PASS
                self.UpdateJsonTestArgs(self.itemName,f" COM ={str(len(self.tsComTestPortInfops))}|LPT ={str(len(self.tsLptTestPortInfops))}|TestModel = str({self.testModel})",'PASS')
                sys.exit(0)
            else:
                self.updateTimer.emit(False)  # 发射信号以停止定时器
                self.start_analysis_threads()
                #self.RecordPlay_analysis_threads()
        except Exception as e:
            self.ShowLog(f"check_Test Err:{e}", False)
            return False

    # 定义触发器
    def handleTimer(self, start):
        if start:
            self.timer.start()
        else:
            self.timer.stop()

    # 启动多线程
    def start_analysis_threads(self):
        # 创建多个线程
        self.threads = []
        #print("Starting COM threads")  # 调试信息
        for comDev in self.rtsComTestPortInfo:#遍历COM硬件信息
            #print(f"Starting COM thread for {comDev}")  # 调试信息
            thread=AnalysisThread(comDev,'com',self)
            thread.test_result_signal.connect(self.handle_test_result)  # 连接信号
            thread.start()
            self.threads.append(thread)
            self.analysis_threads.append(thread)

        #print("Starting LPT threads")  # 调试信息
        for lptDev in self.rtsLptTestPortInfo:#遍历LPT硬件信息
            #print(f"Starting LPT thread for {lptDev}")  # 调试信息
            thread=AnalysisThread(lptDev,'lpt',self)
            thread.test_result_signal.connect(self.handle_test_result)  # 连接信号
            thread.start()
            self.threads.append(thread)
            self.analysis_threads.append(thread)
        self.updateTimer.emit(True)  # 启动时钟

    def handle_test_result(self, result):
        devicepath, isPass = result
        # if isPass:
        #     # 更新UI的逻辑
        #     self.TableAddItem(devicepath, True)
        # else:
        #     self.TableAddItem(devicepath, False)
        devicepath, isPass = result
        self.TableAddItem(devicepath, isPass)

    #日志信息栏添加数据 port:端口信息,isPass:测试结果
    # def TableAddItem(self,port,isPass):
    #     # 检查设备是否已经在表格中
    #     for rowIndex in range(self.tableWidget.rowCount()):
    #         if self.tableWidget.item(rowIndex, 1).text() == port[0] and self.tableWidget.item(rowIndex, 2).text() ==port[1]:
    #             return  # 如果已存在,则不添加
    #     newItem=QTableWidgetItem(str(self.tbrowIndex+1))
    #     newItem.setTextAlignment(Qt.AlignCenter)  # 文本内容居中
    #     self.tableWidget.setItem(self.tbrowIndex,0,newItem)
    #     newItem = QTableWidgetItem(port[0])
    #     newItem.setTextAlignment(Qt.AlignCenter)  # 文本内容居中
    #     self.tableWidget.setItem(self.tbrowIndex, 1, newItem)
    #     newItem = QTableWidgetItem(port[1])
    #     newItem.setTextAlignment(Qt.AlignCenter)  # 文本内容居中
    #     self.tableWidget.setItem(self.tbrowIndex,2,newItem)
    #     testResult='PASS'
    #     if isPass==False:
    #         testResult='FAIL'
    #     newItem=QTableWidgetItem(testResult)
    #     newItem.setTextAlignment(Qt.AlignCenter)  # 文本内容居中
    #     self.tableWidget.setItem(self.tbrowIndex,3,newItem)
    #     if testResult=='PASS':
    #         self.tableWidget.item(self.tbrowIndex, 3).setForeground(QtGui.QColor(51, 204, 51))
    #         self.tbrowIndex+=1
    #     else:
    #         self.tableWidget.item(self.tbrowIndex, 3).setForeground(QtGui.QColor(255, 51, 51))

    def TableAddItem(self, port, isPass):
        # 检查设备是否已经在表格中
        for rowIndex in range(self.tableWidget.rowCount()):
            if self.tableWidget.item(rowIndex, 1) and self.tableWidget.item(rowIndex, 2):
                if self.tableWidget.item(rowIndex, 1).text() == port[0] and self.tableWidget.item(rowIndex, 2).text() == \
                        port[1]:
                    # 更新现有行的测试结果
                    testResult = 'PASS' if isPass else 'FAIL'
                    self.tableWidget.item(rowIndex, 3).setText(testResult)
                    if testResult == 'PASS':
                        self.tableWidget.item(rowIndex, 3).setForeground(QtGui.QColor(51, 204, 51))
                    else:
                        self.tableWidget.item(rowIndex, 3).setForeground(QtGui.QColor(255, 51, 51))
                    return

        # 添加新项目
        newItem = QTableWidgetItem(str(self.tbrowIndex + 1))
        newItem.setTextAlignment(Qt.AlignCenter)
        self.tableWidget.setItem(self.tbrowIndex, 0, newItem)

        newItem = QTableWidgetItem(port[0])
        newItem.setTextAlignment(Qt.AlignCenter)
        self.tableWidget.setItem(self.tbrowIndex, 1, newItem)

        newItem = QTableWidgetItem(port[1])
        newItem.setTextAlignment(Qt.AlignCenter)
        self.tableWidget.setItem(self.tbrowIndex, 2, newItem)

        testResult = 'PASS' if isPass else 'FAIL'
        newItem = QTableWidgetItem(testResult)
        newItem.setTextAlignment(Qt.AlignCenter)
        self.tableWidget.setItem(self.tbrowIndex, 3, newItem)

        if testResult == 'PASS':
            self.tableWidget.item(self.tbrowIndex, 3).setForeground(QtGui.QColor(51, 204, 51))
        else:
            self.tableWidget.item(self.tbrowIndex, 3).setForeground(QtGui.QColor(255, 51, 51))

        self.tbrowIndex += 1

    #LPT测试
    def LptTest(self,port):
        try:
            # 获取COM硬件信息
            lpttest = subprocess.Popen('./lpt_test', stdout=subprocess.PIPE, stderr=subprocess.PIPE,shell=True, encoding='utf-8')
            lpt_output,_=lpttest.communicate()#获取输出

            #判断结果是否为PASS
            def JudgeIsPass(output):
                for line in output.split('\n'):
                    if line.strip():  # 确保行不是空的
                        if 'Test PASS' in line:
                            return True
                else:
                    #print(f'{port} Test Fail!!')
                    return False
            return JudgeIsPass(lpt_output)
        except Exception as e:
            self.ShowLog(f"Lpt Test Err:{e}", False)
            return False

    #串口测试
    def ComTest(self,port):
        serial_port = serial.Serial(port=port,baudrate=115200,bytesize=serial.EIGHTBITS,parity=serial.PARITY_NONE,stopbits=serial.STOPBITS_ONE,timeout=0.5)
        try:
            self.lbl_Console.setText(f'{port} Test')
            serial_port.write("2".encode())
            if int(str(serial_port.read())[2:3]) == 2:
                self.lbl_Result.setText("测试中..")
                return True
            else:
                return False
        except KeyboardInterrupt:
            print("Exiting Program")
        except Exception as exception_err:
            self.ShowLog(f"Error occurred. Exiting Program:{str(exception_err)}", False)
        finally:
            serial_port.close()

    #获取当前测试端口
    def GetTestPortInfo(self):
        try:
            self.rtsComTestPortInfo.clear()  # 清空COM存放硬件容器
            self.rtsLptTestPortInfo.clear()  # 清空LPT存放硬件容器

            # 获取COM硬件信息
            process_com = subprocess.Popen('dmesg | grep tty', stdout=subprocess.PIPE, stderr=subprocess.PIPE,
                                           shell=True, encoding='utf-8')
            com_output, _ = process_com.communicate()  # 获取输出

            # 获取LPT硬件信息
            process_lpt = subprocess.Popen('dmesg | grep lp0', stdout=subprocess.PIPE, stderr=subprocess.PIPE,
                                           shell=True, encoding='utf-8')
            lpt_output, _ = process_lpt.communicate()  # 获取输出

            #截取字符串
            def extract_tty_devices(log_data):
                # 使用正则表达式匹配 ttyS*, ttyUSB*, 和 lpt* 设备
                pattern = r"(ttyS\d+|ttyUSB\d+|lp\d+)"
                devices = re.findall(pattern, log_data)
                if devices:#检查列表是否为空
                    return devices[0]
                else:
                    return None

            # 解析输出硬件信息
            def GetDeviceInfo(output):
                device_names = []
                for line in output.split('\n'):
                    if line.strip():  # 确保行不是空的
                        parts =extract_tty_devices(line)
                        #parts = line.split()  # 分割每一行
                        if parts:
                            device_names.append(f'/dev/{parts}')  # 假设设备名称是每行的第一个元素
                return device_names

            # 移除重复的字符串
            def remove_duplicates_keep_order(lst,type):
                seen = set()
                result = []
                i=1
                for item in lst:
                    if item not in seen:
                        seen.add(item)
                        result.append((f'{type}{str(i)}',item))
                        i+=1
                return result
            self.rtsComTestPortInfo = remove_duplicates_keep_order(GetDeviceInfo(com_output),'COM')
            self.rtsLptTestPortInfo = remove_duplicates_keep_order(GetDeviceInfo(lpt_output),'LPT')
            return True
        except Exception as e:
            self.ShowLog(f"GetTestPortInfo Err:{e}", False)
            return False

    def setupUi(self):
        self.setObjectName("COMLPTTest")
        self.resize(845, 835)
        icon = QtGui.QIcon()
        icon.addPixmap(QtGui.QPixmap("IMAGE/Serial.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.setWindowIcon(icon)
        self.gridLayout = QtWidgets.QGridLayout(self)
        self.gridLayout.setObjectName("gridLayout")
        self.verticalLayout = QtWidgets.QVBoxLayout()
        self.verticalLayout.setObjectName("verticalLayout")
        self.horizontalLayout_2 = QtWidgets.QHBoxLayout()
        self.horizontalLayout_2.setObjectName("horizontalLayout_2")
        self.verticalLayout_2 = QtWidgets.QVBoxLayout()
        self.verticalLayout_2.setObjectName("verticalLayout_2")
        self.lbl_Logo = QtWidgets.QLabel(self)
        font = QtGui.QFont()
        font.setPointSize(12)
        self.lbl_Logo.setFont(font)
        self.lbl_Logo.setText("")
        self.lbl_Logo.setPixmap(QtGui.QPixmap("IMAGE/logo.jpg"))
        self.lbl_Logo.setAlignment(QtCore.Qt.AlignCenter)
        self.lbl_Logo.setObjectName("lbl_Logo")
        self.verticalLayout_2.addWidget(self.lbl_Logo)
        self.label_4 = QtWidgets.QLabel(self)
        font = QtGui.QFont()
        font.setPointSize(12)
        self.label_4.setFont(font)
        self.label_4.setText("")
        self.label_4.setAlignment(QtCore.Qt.AlignCenter)
        self.label_4.setObjectName("label_4")
        self.verticalLayout_2.addWidget(self.label_4)
        self.horizontalLayout_2.addLayout(self.verticalLayout_2)
        self.verticalLayout_3 = QtWidgets.QVBoxLayout()
        self.verticalLayout_3.setObjectName("verticalLayout_3")
        self.label_6 = QtWidgets.QLabel(self)
        font = QtGui.QFont()
        font.setPointSize(12)
        self.label_6.setFont(font)
        self.label_6.setStyleSheet("background-color: rgb(170, 170, 127);\n"
"color: rgb(255, 255, 255);")
        self.label_6.setAlignment(QtCore.Qt.AlignCenter)
        self.label_6.setObjectName("label_6")
        self.verticalLayout_3.addWidget(self.label_6)
        self.lbl_Console = QtWidgets.QLabel(self)
        font = QtGui.QFont()
        font.setPointSize(12)
        self.lbl_Console.setFont(font)
        self.lbl_Console.setStyleSheet("background-color: rgb(85, 255, 127);")
        self.lbl_Console.setAlignment(QtCore.Qt.AlignCenter)
        self.lbl_Console.setObjectName("lbl_Console")
        self.verticalLayout_3.addWidget(self.lbl_Console)
        self.horizontalLayout_2.addLayout(self.verticalLayout_3)
        self.horizontalLayout_4 = QtWidgets.QHBoxLayout()
        self.horizontalLayout_4.setObjectName("horizontalLayout_4")
        self.verticalLayout_7 = QtWidgets.QVBoxLayout()
        self.verticalLayout_7.setObjectName("verticalLayout_7")
        self.label_8 = QtWidgets.QLabel(self)
        font = QtGui.QFont()
        font.setPointSize(12)
        self.label_8.setFont(font)
        self.label_8.setStyleSheet("background-color: rgb(170, 170, 127);\n"
"color: rgb(255, 255, 255);")
        self.label_8.setAlignment(QtCore.Qt.AlignCenter)
        self.label_8.setObjectName("label_8")
        self.verticalLayout_7.addWidget(self.label_8)
        self.lbl_TestModel = QtWidgets.QLabel(self)
        font = QtGui.QFont()
        font.setPointSize(12)
        self.lbl_TestModel.setFont(font)
        self.lbl_TestModel.setStyleSheet("background-color: rgb(255, 170, 127);")
        self.lbl_TestModel.setAlignment(QtCore.Qt.AlignCenter)
        self.lbl_TestModel.setObjectName("lbl_TestModel")
        self.verticalLayout_7.addWidget(self.lbl_TestModel)
        self.horizontalLayout_4.addLayout(self.verticalLayout_7)
        self.horizontalLayout_2.addLayout(self.horizontalLayout_4)
        self.verticalLayout_5 = QtWidgets.QVBoxLayout()
        self.verticalLayout_5.setObjectName("verticalLayout_5")
        self.label = QtWidgets.QLabel(self)
        font = QtGui.QFont()
        font.setPointSize(12)
        self.label.setFont(font)
        self.label.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter)
        self.label.setObjectName("label")
        self.verticalLayout_5.addWidget(self.label)
        self.label_7 = QtWidgets.QLabel(self)
        font = QtGui.QFont()
        font.setPointSize(12)
        self.label_7.setFont(font)
        self.label_7.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter)
        self.label_7.setObjectName("label_7")
        self.verticalLayout_5.addWidget(self.label_7)
        self.label_2 = QtWidgets.QLabel(self)
        font = QtGui.QFont()
        font.setPointSize(12)
        self.label_2.setFont(font)
        self.label_2.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter)
        self.label_2.setObjectName("label_2")
        self.verticalLayout_5.addWidget(self.label_2)
        self.horizontalLayout_2.addLayout(self.verticalLayout_5)
        self.verticalLayout_4 = QtWidgets.QVBoxLayout()
        self.verticalLayout_4.setObjectName("verticalLayout_4")
        self.label_12 = QtWidgets.QLabel(self)
        font = QtGui.QFont()
        font.setPointSize(12)
        self.label_12.setFont(font)
        self.label_12.setAlignment(QtCore.Qt.AlignCenter)
        self.label_12.setObjectName("label_12")
        self.verticalLayout_4.addWidget(self.label_12)
        self.lbl_LPTArgs = QtWidgets.QLabel(self)
        font = QtGui.QFont()
        font.setPointSize(12)
        self.lbl_LPTArgs.setFont(font)
        self.lbl_LPTArgs.setAlignment(QtCore.Qt.AlignCenter)
        self.lbl_LPTArgs.setObjectName("lbl_LPTArgs")
        self.verticalLayout_4.addWidget(self.lbl_LPTArgs)
        self.lbl_LPTResult = QtWidgets.QLabel(self)
        font = QtGui.QFont()
        font.setPointSize(12)
        self.lbl_LPTResult.setFont(font)
        self.lbl_LPTResult.setAlignment(QtCore.Qt.AlignCenter)
        self.lbl_LPTResult.setObjectName("lbl_LPTResult")
        self.verticalLayout_4.addWidget(self.lbl_LPTResult)
        self.horizontalLayout_2.addLayout(self.verticalLayout_4)
        self.verticalLayout_6 = QtWidgets.QVBoxLayout()
        self.verticalLayout_6.setObjectName("verticalLayout_6")
        self.label_9 = QtWidgets.QLabel(self)
        font = QtGui.QFont()
        font.setPointSize(12)
        self.label_9.setFont(font)
        self.label_9.setAlignment(QtCore.Qt.AlignCenter)
        self.label_9.setObjectName("label_9")
        self.verticalLayout_6.addWidget(self.label_9)
        self.lbl_COMArgs = QtWidgets.QLabel(self)
        font = QtGui.QFont()
        font.setPointSize(12)
        self.lbl_COMArgs.setFont(font)
        self.lbl_COMArgs.setAlignment(QtCore.Qt.AlignCenter)
        self.lbl_COMArgs.setObjectName("lbl_COMArgs")
        self.verticalLayout_6.addWidget(self.lbl_COMArgs)
        self.lbl_COMResult = QtWidgets.QLabel(self)
        font = QtGui.QFont()
        font.setPointSize(12)
        self.lbl_COMResult.setFont(font)
        self.lbl_COMResult.setAlignment(QtCore.Qt.AlignCenter)
        self.lbl_COMResult.setObjectName("lbl_COMResult")
        self.verticalLayout_6.addWidget(self.lbl_COMResult)
        self.horizontalLayout_2.addLayout(self.verticalLayout_6)
        self.verticalLayout.addLayout(self.horizontalLayout_2)
        self.verticalLayout_9 = QtWidgets.QVBoxLayout()
        self.verticalLayout_9.setObjectName("verticalLayout_9")
        self.tableWidget = QtWidgets.QTableWidget(self)
        self.tableWidget.setObjectName("tableWidget")
        self.tableWidget.setColumnCount(4)
        self.tableWidget.setRowCount(self.ComTestCount+self.LptTestCount)#设置表格行数
        self.tableWidget.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectRows)

        item = QtWidgets.QTableWidgetItem()
        font = QtGui.QFont()
        font.setPointSize(11)
        item.setFont(font)
        item.setBackground(QtGui.QColor(170, 170, 255))
        self.tableWidget.setHorizontalHeaderItem(0, item)
        self.tableWidget.setFont(font)
        item = QtWidgets.QTableWidgetItem()
        font = QtGui.QFont()
        font.setPointSize(11)
        item.setFont(font)
        item.setBackground(QtGui.QColor(170, 255, 127))
        self.tableWidget.setHorizontalHeaderItem(1, item)
        item = QtWidgets.QTableWidgetItem()
        font = QtGui.QFont()
        font.setPointSize(11)
        item.setFont(font)
        item.setBackground(QtGui.QColor(255, 170, 127))
        self.tableWidget.setHorizontalHeaderItem(2, item)
        item = QtWidgets.QTableWidgetItem()
        font = QtGui.QFont()
        font.setPointSize(11)
        item.setFont(font)
        item.setBackground(QtGui.QColor(170, 170, 127))
        self.tableWidget.setHorizontalHeaderItem(3, item)
        self.verticalLayout_9.addWidget(self.tableWidget)
        self.verticalLayout.addLayout(self.verticalLayout_9)
        self.lbl_Result = QtWidgets.QLabel(self)
        font = QtGui.QFont()
        font.setPointSize(22)
        self.lbl_Result.setFont(font)
        self.lbl_Result.setStyleSheet("background-color: rgb(0, 0, 0);\n"
"color: rgb(170, 255, 127);")
        self.lbl_Result.setAlignment(QtCore.Qt.AlignCenter)
        self.lbl_Result.setObjectName("lbl_Result")
        self.verticalLayout.addWidget(self.lbl_Result)
        self.horizontalLayout_3 = QtWidgets.QHBoxLayout()
        self.horizontalLayout_3.setObjectName("horizontalLayout_3")
        self.verticalLayout.addLayout(self.horizontalLayout_3)
        self.gridLayout.addLayout(self.verticalLayout, 1, 0, 1, 1)

        self.retranslateUi()
        QtCore.QMetaObject.connectSlotsByName(self)
        self.setWindowFlags(QtCore.Qt.WindowMinimizeButtonHint | QtCore.Qt.WindowCloseButtonHint)  # 只显示最小化按钮和关闭按钮

    def retranslateUi(self):
        _translate = QtCore.QCoreApplication.translate
        self.setWindowTitle(_translate("COMLPTTest", "COMLPTTest"))
        self.label_6.setText(_translate("COMLPTTest", "控制过程"))
        self.lbl_Console.setText(_translate("COMLPTTest", "当前COM1测试"))
        self.label_8.setText(_translate("COMLPTTest", "测试模式"))
        if self.testModel==True:
            self.lbl_TestModel.setText(_translate("COMLPTTest", "自动"))
        else:
            self.lbl_TestModel.setText(_translate("COMLPTTest", "单步"))
        self.label.setText(_translate("COMLPTTest", "接口名称:"))
        self.label_7.setText(_translate("COMLPTTest", "设置参数:"))
        self.label_2.setText(_translate("COMLPTTest", "测试结果:"))
        self.label_12.setText(_translate("COMLPTTest", "LPT"))
        self.lbl_LPTArgs.setText(_translate("COMLPTTest", str(self.LptTestCount)))
        self.lbl_LPTResult.setText(_translate("COMLPTTest", "N/A"))
        self.label_9.setText(_translate("COMLPTTest", "COM"))
        self.lbl_COMArgs.setText(_translate("COMLPTTest", str(self.ComTestCount)))
        self.lbl_COMResult.setText(_translate("COMLPTTest", "N/A"))
        item = self.tableWidget.horizontalHeaderItem(0)
        item.setText(_translate("COMLPTTest", "NO"))
        item = self.tableWidget.horizontalHeaderItem(1)
        item.setText(_translate("COMLPTTest", "项目名称"))
        item = self.tableWidget.horizontalHeaderItem(2)
        item.setText(_translate("COMLPTTest", "端口号"))
        item = self.tableWidget.horizontalHeaderItem(3)
        item.setText(_translate("COMLPTTest", "测试结果"))
        self.lbl_Result.setText(_translate("COMLPTTest", "测试中.."))

        self.tableWidget.setColumnWidth(0, 60)
        self.tableWidget.setColumnWidth(1, 220)
        self.tableWidget.setColumnWidth(2, 250)
        self.tableWidget.setColumnWidth(3, 260)
        self.tableWidget.setShowGrid(False)  # 是否显示网线
        self.tableWidget.setEditTriggers(QAbstractItemView.NoEditTriggers)  # 表格状态只读
        self.tableWidget.clicked.connect(self.TestThread)  # 表单,单击事件

    # 读取项目参数信息,itemName:项目名称
    def ReadJsonTestArgs(self, itemName):
        try:
            self.testArgs = self.ReadJsonInfo('./Conf/TestArgs.json')
            for js in self.testArgs:
                if itemName in js['ItemName']:
                    self.testStandardArgs = js['Standard']
                    return True
            self.ShowLog('Read TestArgs.json ItemName:' + itemName + ' Info Is Empty!!', False)
            sys.exit(1)
        except Exception as e:
            self.ShowLog("Read TestArgs.json ItemName:" + itemName + " Info Err:" + str(e), False)
            sys.exit(1)

    #读取json信息
    def ReadJsonInfo(self,fileName):
        try:
            if os.path.exists(fileName):
                f=open(fileName,'r',encoding='utf-8')
            return json.loads(f.read())
        except Exception as e:
            self.ShowLog("Read "+fileName+" Err:" + str(e),False)
            sys.exit(1)

    #手动关闭窗口
    def closeEvent(self, event):
        # 创建一个消息框,上面有两个按钮:“是”和“否”
        #reply = QMessageBox.question(self, '退出', "你确定要退出吗?", QMessageBox.Yes | QMessageBox.No, QMessageBox.No)

        # 如果用户点击了“是”,则执行event.accept()来关闭窗口
        #if reply == QMessageBox.Yes:
        #    event.accept()
        #    sys.exit(1)
        #else:
            # 如果用户点击了“否”,则忽略event,不关闭窗口
        #    event.ignore()
        sys.exit(1)

    # 定义一个函数使得函数窗口居中显示
    def Center(self):
        # 获取屏幕尺寸
        screen_geometry = app.desktop().availableGeometry()
        # 计算窗口居中位置
        x = (screen_geometry.width() - self.width()) // 2
        y = (screen_geometry.height() - self.height()) // 2
        # 设置窗口位置
        self.move(x, y)

    # 打印的信息
    def ShowLog(self, log, isPass):
        try:
            if isPass == True:
                self.lbl_Result.setStyleSheet("color:green;")
                self.logger.info(str(log))
                self.lbl_Result.setText("TEST PASS")
            else:
                self.lbl_Result.setStyleSheet("color:red;")
                self.logger.error(str(log))
                self.lbl_Result.setText("TEST FAIL")

        except Exception as e:
            print("\033[1;31m" + str(e) + " \033[0m")
            sys.exit(1)

    # 更新测试参数json,itemName:项目名称,readValue:读取值,testResult:测试结果
    def UpdateJsonTestArgs(self, itemName, readValue, testResult):
        try:
            updateTestArgs = []  # 更新的测试参数
            self.testArgs = self.ReadJsonInfo('./Conf/TestArgs.json')
            for js in self.testArgs:
                if itemName in js['ItemName']:
                    js['Read'] = readValue  # 读取的值
                    js['TestResult'] = testResult  # 测试结果
                    updateTestArgs.append(js)
                else:
                    updateTestArgs.append(js)
            with open("./Conf/TestArgs.json", "w") as write_file:
                json.dump(updateTestArgs, write_file)
            return True
        except Exception as e:
            self.ShowLog("Read TestArgs.json ItemName:" + itemName + " Info Err:" + str(e), False)
            sys.exit(1)

    #启动线重脚本
    def TestThread(self):
        pass
        #self.t_autoplay=Thread(target=self.Test)
        #self.t_autoplay.start()

if __name__=='__main__':
    app=QApplication(sys.argv)
    win=Ui_COMLPTTest()
    win.Center()  # 居中
    win.show()
    sys.exit(app.exec_())