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

软件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 outputconst char* RED = "\033[31m";   // Red color startconst char* GREEN = "\033[32m"; // Green color startconst char* RESET = "\033[0m";  // Reset to default colorstd::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"]));//读取参数1config_args_B=static_cast<unsigned char>(std::stoi(config["Args_1"]));//读取参数2const 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 pyserialclass AnalysisThread(QtCore.QThread):test_result_signal = QtCore.pyqtSignal(tuple)  # 新增信号,传递一个包含设备路径和测试结果的元组def __init__(self, devicepath,type, parent=None):super(AnalysisThread, self).__init__(parent)self.devicepath = devicepathself.type=typeself.is_running = Truedef run(self):result = Falseif 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=Trueelse:self.testModel=Falseself.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):#判断测试PASSself.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 = resultself.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()#获取输出#判断结果是否为PASSdef JudgeIsPass(output):for line in output.split('\n'):if line.strip():  # 确保行不是空的if 'Test PASS' in line:return Trueelse:#print(f'{port} Test Fail!!')return Falsereturn 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 Trueelse:return Falseexcept 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=1for item in lst:if item not in seen:seen.add(item)result.append((f'{type}{str(i)}',item))i+=1return resultself.rtsComTestPortInfo = remove_duplicates_keep_order(GetDeviceInfo(com_output),'COM')self.rtsLptTestPortInfo = remove_duplicates_keep_order(GetDeviceInfo(lpt_output),'LPT')return Trueexcept Exception as e:self.ShowLog(f"GetTestPortInfo Err:{e}", False)return Falsedef 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.translateself.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 Trueself.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()) // 2y = (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 Trueexcept 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_())

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/635420.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

基于 UniAPP 社区论坛项目多端开发实战

社区论坛项目多端开发实战 基于 UniAPP 社区论坛项目多端开发实战一、项目准备1.1 ThinkSNS 简介及相关文档1.2 使用 UniAPP 构建项目1.3 构建项目文件结构1.4 配置页面 TabBar 导航1.5 使用 npm 引入 uView UI 插件库 二、首页功能实现2.1 首页 header 广告位轮播图功能实现2.…

小白水平理解面试经典题目LeetCode 121 Best Time to Buy and Sell Stock

121 Best Time to Buy and Sell Stock (买卖股票的最佳时机) 你好&#xff0c;2024年的第一个月&#xff0c;又是秋风萧瑟天气凉&#xff0c;草木摇落露为霜。.。。在这个特殊的时代&#xff0c;作为我们普通的一个打工人&#xff0c;我们用这道题&#xff0c;开启对这个不符合…

2023全球边缘计算大会深圳站:核心内容与学习收获(附大会核心PPT下载)

边缘计算作为当今IT领域的热门话题&#xff0c;已经引起了全球范围内的广泛关注。本次大会汇聚了众多业界精英&#xff0c;共同探讨边缘计算的发展趋势、技术应用与创新实践。本文将围绕大会的核心内容展开讨论&#xff0c;并分析参会者从中能够学到的东西。 一、边缘计算的发…

C++PythonC# 三语言OpenCV从零开发(2):教程选择

文章目录 相关专栏前言视频教学和官方文档视频教程OpenCV 官方教程最终选择我的最终选择 相关专栏 C&Python&Csharp in OpenCV 前言 OpenCV 有官方的教程和简单的视频教程&#xff1a; OpenCV 官方教程 B站也有相关的视频教学 OpenCV4 C 快速入门视频30讲 - 系列合集 …

【Java】JDBC的使用

JDBC package jdbc_demo;import java.sql.Connection; import java.sql.DriverManager; import java.sql.Statement;public class jdbc {public static void main(String[] args)throws Exception {//1.注册驱动Class.forName("com.mysql.cj.jdbc.Driver");//2.获取…

【开源】基于JAVA语言的教学资源共享平台

目录 一、摘要1.1 项目介绍1.2 项目录屏 二、功能模块2.1 数据中心模块2.2 课程档案模块2.3 课程资源模块2.4 课程作业模块2.5 课程评价模块 三、系统设计3.1 用例设计3.2 类图设计3.3 数据库设计3.3.1 课程档案表3.3.2 课程资源表3.3.3 课程作业表3.3.4 课程评价表 四、系统展…

逸学Docker【java工程师基础】3.4Docker安装redis

1.拉取redis docker pull redis 2.选择一个合适的redis 版本的配置文件 Redis configuration | Redis 或者这个 链接&#xff1a;https://pan.baidu.com/s/1RRdtgec4xBAgQghlhm0x1Q 提取码&#xff1a;ycyc 在1044行修改密码 3.提前在服务器建立 /data/redis 文件夹&…

【华为 ICT HCIA eNSP 习题汇总】——题目集1

1、&#xff08;多选&#xff09;根据下面所示的命令输出&#xff0c;下列描述中正确的是&#xff1f; A、GigabitEthernet0/0/1 允许VLAN1通过 B、GigabitEthernet0/0/1 不允许VLAN1通过 C、如果要把 GigabitEthernet0/0/1 变为 Access 端口&#xff0c;首先 需要使用命令“un…

2023 年,我患上了 AI 焦虑症!

【作者有话说】2023 年对我来说是神奇的一年&#xff0c;我意外地从一个程序员变成了一个 AI 资讯届的“网红”&#xff0c;到年底时我在 X 平台的阅读量超过 1 亿&#xff0c;微博上的阅读量则超过 10 亿&#xff0c;很多人通过我的微博或者 X 了解最新的 AI 资讯、教程和 Pro…

SpringMVC下半篇之整合ssm

4.ssm整合 4.1.创建表 CREATE TABLE account (id int(11) NOT NULL AUTO_INCREMENT,name varchar(20) DEFAULT NULL,money double DEFAULT NULL,PRIMARY KEY (id) ) ENGINEInnoDB DEFAULT CHARSETutf8;4.2.创建工程 4.3.pom.xml <?xml version"1.0" encoding&…

蓝桥杯备战 每日一题 (4)

题目地址 首先我们要有一个知识储备 1 加法&#xff1a;(ab)%m(a%mb%m)%m 2 减法&#xff1a;(a-b)%m(a%m-b%m)%m 3 乘法&#xff1a;a*b%m(a%m)*(b%m)%m 我们可以每次计算就可以取余一次&#xff0c;这样就保证了最后取余的结果和一起相加再取余的结果一样 然后这个题目要怎…

【LeetCode】数学精选4题

目录 1. 二进制求和&#xff08;简单&#xff09; 2. 两数相加&#xff08;中等&#xff09; 3. 两数相除&#xff08;中等&#xff09; 4. 字符串相乘&#xff08;中等&#xff09; 1. 二进制求和&#xff08;简单&#xff09; 从字符串的右端出发向左做加法&#xff0c;…

SQLAlchemy ORM指南:简化数据库操作的最佳实践

SQLAIchemy 开发指南 背景&#xff1a; ​ SQLAlchemy是一个数据库的ORM框架&#xff0c;让我们操作数据库的时候不要再用SQL语句了&#xff0c;跟直接操作模型一样。操作十分便捷&#xff0c;其实SQLAlchemy应该是在Flask和Django应用的特别多&#xff0c;而且在flask中已经…

Oracle架构_数据库底层原理、机制 (授人以渔)

目录 系统全局区SGA 高速缓存缓冲区(数据库缓冲区) 日志缓冲区 共享池 其他结构 用户连接进程 用户进程User Process Server Process服务进程 程序全局区PGA Oracle的connect连接和session会话与User Process紧密相关 后台进程 数据库写入进程(DBWn) 检查点(CKPT)…

多维时序 | Matlab实现CNN-LSTM-Mutilhead-Attention卷积长短期记忆神经网络融合多头注意力机制多变量时间序列预测

多维时序 | Matlab实现CNN-LSTM-Mutilhead-Attention卷积长短期记忆神经网络融合多头注意力机制多变量时间序列预测 目录 多维时序 | Matlab实现CNN-LSTM-Mutilhead-Attention卷积长短期记忆神经网络融合多头注意力机制多变量时间序列预测效果一览基本介绍程序设计参考资料 效果…

“深入理解 Docker 和 Nacos 的单个部署与集成部署“

目录 引言&#xff1a;Docker Nacos 单个部署1.1 什么是 Docker&#xff1f;Docker 的概念和工作原理Docker 为什么受到广泛应用和认可 1.2 什么是 Nacos&#xff1f;Nacos 的核心功能和特点Nacos 在微服务架构中的作用 1.3 Docker 单个部署 Nacos Docker Nacos 集成部署总结&a…

【重点!!!】【背包】【回溯】518.零钱兑换II

题目 跟39.组合总数、322.零钱兑换题目很类似。 法1&#xff1a;背包DP&#xff0c;最优解法 解释如下&#xff1a; 0 1 2 3 4 5(背包容量)1 0 0 0 0 0 没有硬币的时候&#xff09; 0 1 2 3 4 5(背包容量) 1 1 1 1 1 1 1 0 1 2 3 4 5(背包容量) 1 …

Ubuntu 22.04 安装MySql

MySQL是非常常用的关系型数据库,无论是大厂还是小厂,都有它的身影。最大的优点是免费,安装起来也比较简单。 MySQL的架构 画了个简图,描述了下MySQL的架构。 其中的比较有趣的点在于连接池和存储引擎。连接池缓存了数据库和客户端的TCP连接,以减少建立连接的开销。存储引…

git中合并分支时出现了代码冲突怎么办

目录 第一章、Git代码冲突介绍1.1&#xff09;什么是Git代码冲突①git merge命令介绍②代码冲突原因 1.2&#xff09;提示代码冲突的两种情况①本地不同分支的文件有差异时&#xff1a;②本地仓库和git远程仓库的文件有差异时&#xff1a; 1.3&#xff09;解决合并时的代码冲突…

calloc与realloc和malloc的区别以及new

目录 calloc、realloc 和 malloc 三个函数的区别在于 更详细的示例代码 交叉使用 内存泄漏 悬空指针 内存重叠 new 的语法 使用 new 运算符在堆上创建学生对象的示例 new和malloc都可以用于在堆上分配内存 calloc、realloc 和 malloc 是 C/C 中用于动态内存分配的函…