python+PyQt5 网口功能测试

UI界面:

源代码:

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

# Form implementation generated from reading ui file 'NetOpeningWinFrm.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 psutil
#pip install psutil
#import serial
import subprocess
import io
#import glob
#import re#正则表达式
#pip install pyserial

class AnalysisThread(QtCore.QThread):
    test_result_signal = QtCore.pyqtSignal(tuple)  # 新增信号,传递一个包含设备路径和测试结果的元组
    finished_signal = QtCore.pyqtSignal()  # 新增信号,表示线程完成
    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
        index=0
        if self.parent().rnetTestCount>0:
            index=self.parent().rnetTestCount-1
        result = self.parent().GetTestPortInfoAndTest(self.devicepath)
        print('resutl:',result)
        if result:
            print("Before removal:", self.parent().rnetPortName)
            self.parent().rnetPortName.remove(self.devicepath)
            print("After removal:", self.parent().rnetPortName)
            device_info = []
            device_info.append(self.devicepath)#连接状态
            device_info.append(self.parent().rnConnetcion[index])#连接状态
            device_info.append(self.parent().rnetRate[index])#速率
            device_info.append(self.parent().rnetMacAddress[index])#MacAddress
            self.parent().TableAddItem(device_info,True)#添加PASS数据
            #端口数
            self.parent().lbl_GetPortNum.setText(str(self.parent().rnetTestCount))#设置测试端口数
            self.parent().lbl_GetPortNum.setStyleSheet("background-color: lightgreen;")  # 后置端口背景色设置为浅绿色
            #连接状态
            self.parent().lbl_GetConntion.setText(self.parent().rnConnetcion[index])#设置连接状态
            self.parent().lbl_GetPortNum.setStyleSheet("background-color: lightgreen;")  # 后置端口背景色设置为浅绿色
            #速率
            self.parent().lbl_GetRate.setText(self.parent().rnetRate[index]+'M')
            self.parent().lbl_GetRate.setStyleSheet("background-color: lightgreen;")  # 后置端口背景色设置为浅绿色
        else:
            if self.parent().rnetFailInfo:
                device_info = []
                device_info.append(self.parent().rnetFailInfo[0])
                device_info.append(self.parent().rnetFailInfo[1])
                device_info.append(self.parent().rnetFailInfo[2])
                device_info.append(self.parent().rnetFailInfo[3])
                self.parent().TableAddItem(device_info, False)  # 添加PASS数据
                self.test_result_signal.emit((device_info,False))

                # 端口数
                self.parent().lbl_GetPortNum.setText(str(self.parent().rnetTestCount+1))  # 设置测试端口数
                self.parent().lbl_GetPortNum.setStyleSheet("background-color: red;")  # 后置端口背景色设置为浅绿色
                # 连接状态
                self.parent().lbl_GetConntion.setText(self.parent().rnetFailInfo[1])  # 设置连接状态
                self.parent().lbl_GetConntion.setStyleSheet("background-color: red;")  # 后置端口背景色设置为浅绿色
                # 速率
                self.parent().lbl_GetRate.setText(self.parent().rnetFailInfo[2] + 'M')
                self.parent().lbl_GetRate.setStyleSheet("background-color: red;")  # 后置端口背景色设置为浅绿色

                self.parent().lbl_Result.setStyleSheet("background-color: black; color: red;")
                self.parent().lbl_Result.setText("测试FAIL!!")
        self.finished_signal.emit()  # 线程完成时发出信号
        self.stop()

    def stop(self):
        self.is_running = False # 或者使用更安全的停止逻辑

class Ui_Form(QWidget):
    updateTimer=pyqtSignal(bool)#时间线程启动器
    def __init__(self):
        super().__init__()
        self.finished_threads = 0  # 用于跟踪完成的线程数
        self.analysis_threads = []  # 存储所有的 AnalysisThread 实例
        self.Err=''#错误信息

        self.config = configparser.ConfigParser()  # 创建对象
        self.itemName = ''  # 项目名称
        self.testArgs = []  # 测试参数信息
        self.testStandardArgs = ''  # 测试准标参数

        #参数信息
        self.anetTestCount=1#网卡测试端口数
        self.anetRate=[]#网卡速率

        #读取的网卡信息
        self.rnetTestCount=0#网卡测试端口数
        self.rnetPortName=[]#获取所有网络接口名称
        self.rnetRate=[]#网卡速率
        self.rnetMacAddress=[]#网卡MACAddress
        self.rnConnetcion=[]#连接状态
        self.rnetFailInfo=[]#读取的fail信息

        # 生成日志信息
        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', 'NetOpening')  # 项目名称
        self.itemFailSleepExit = int(self.config.get('TestItemWinFrmSleepExit', 'NetOpening'))  # 项目测试Fail延时退出
        self.testArgs = self.ReadJsonInfo('./Conf/TestArgs.json')  # 读取测试参数信息

        if self.ReadJsonTestArgs(self.itemName)==True:#获取标准参数
            testArgs=[]#测试参数
            testArgs=self.testStandardArgs.split('|')

            testCount=testArgs[0]#测试端口数
            netRate=testArgs[1]#测试速率

            self.anetTestCount=int(testCount[testCount.find('=')+1:])
            self.anetRate=netRate[netRate.find('=')+1:].split(',')#截取速率信息

            self.setupUi()#初始化
            self.lbl_Result.setStyleSheet("background-color: black; color: red;")

            self.rnetPortName=self.get_network_interfaces()
            for rn in self.rnetPortName:
                if 'lo' in rn:
                    self.rnetPortName.remove(rn)
                    break
            if len(self.rnetPortName)!=self.anetTestCount:#获取测试接口信息
                self.lbl_GetPortNum.setText(str(len(self.rnetPortName)))
                self.lbl_GetPortNum.setStyleSheet("color: red;")
                self.lbl_Result.setStyleSheet("background-color: black; color: red;")
                self.ShowLog(f"侦测试网络适配器数量与参数不匹配 Err:{self.rnetPortName}", False)
                self.Err=f"侦测试网络适配器数量与参数不匹配 Err:{self.rnetPortName}";

            # 创建一个定时器来检查视频是否播放结束
            self.timer = QTimer(self)
            self.timer.setInterval(1000)  # 每秒检查一次
            self.timer.timeout.connect(self.check_Test)
            self.timer.start()
            # 连接信号到槽
            self.updateTimer.connect(self.handleTimer)

    #获取所有网络接口名称
    def get_network_interfaces(self):
        return list(psutil.net_if_addrs().keys())

    def get_net_interfaces(self):
        net_if_addrs = psutil.net_if_addrs()
        return net_if_addrs

    #获取端口信息及测试 interface_name:适配置器名称
    def GetTestPortInfoAndTest(self,interface_name):
        try:
            self.rnetFailInfo.clear()#清空fail信息
            testdata=self.get_interface_details(interface_name)
            self.label_2.setText(f'当前{interface_name} 端口测试..')
            if self.Err is None:
                self.lbl_Result.setStyleSheet("background-color: black; color: lightyellow;")
                self.lbl_Result.setText("测试中..")
            else:
                self.lbl_Result.setStyleSheet("background-color: black; color: red;")
                self.lbl_Result.setText(self.Err)
            if testdata and testdata['speed'] and testdata['operstate'] and testdata['mac_address']:
                if int(self.anetRate[self.rnetTestCount])==int(testdata['speed']):
                    self.rnetMacAddress.append(testdata['mac_address'])
                    self.rnetRate.append(testdata['speed'])
                    self.rnConnetcion.append(testdata['operstate'])
                    self.rnetTestCount+=1
                    return True
                else:
                    self.rnetFailInfo.append(interface_name)
                    self.rnetFailInfo.append(testdata['operstate'])
                    self.rnetFailInfo.append(testdata['speed'])
                    self.rnetFailInfo.append(testdata['mac_address'])
                    return False
            else:
                return False
        except Exception as e:
            self.ShowLog(f"GetTestPortInfoAndTest Err:{e}", False)
            return False

    def read_sys_file(self,path):
        try:
            with open(path, 'r') as file:
                return file.read().strip()
        except IOError:
            return None

    def get_interface_details(self,interface):
        speed = self.read_sys_file(f'/sys/class/net/{interface}/speed')
        operstate = self.read_sys_file(f'/sys/class/net/{interface}/operstate')
        mac_address = self.read_sys_file(f'/sys/class/net/{interface}/address')
        return {
            'speed': speed,
            'operstate': operstate,
            'mac_address': mac_address
        }

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

    # 启动多线程
    def start_analysis_threads(self):
        # 创建多个线程
        self.finished_threads = 0  # 重置计数器
        self.analysis_threads = []  # 重置线程列表
        print("Remaining devices to test:", self.rnetPortName)  # 打印剩余的设备列表
        #self.threads = []
        for portname in self.rnetPortName:
            thread=AnalysisThread(portname,'lan',self)
            thread.test_result_signal.connect(self.handle_test_result)  # 连接信号
            thread.finished_signal.connect(self.thread_finished)
            thread.start()
            #self.threads.append(thread)
            self.analysis_threads.append(thread)

    # 判断是否所有线程都执行完成
    def thread_finished(self):
        self.finished_threads += 1
        if self.finished_threads == len(self.analysis_threads):
            self.updateTimer.emit(True)  # 所有线程完成后重新启动定时器

    #
    def handle_test_result(self, result):
        devicepath, isPass = result
        if isPass:
            # 如果测试通过,从待测试列表中移除该设备
            if devicepath in self.rnetPortName:
                self.rnetPortName.remove(devicepath)
        self.TableAddItem(devicepath, isPass)

    # 校验是否完成测试
    def check_Test(self):
        if self.anetTestCount==self.rnetTestCount:
            macinfo=''#mac信息
            rate=''#速率
            for mac in self.rnetMacAddress:
                macinfo+=mac+','
            macinfo=macinfo[:-1] #去掉最后一个字符
            for rte in self.anetRate:
                rate+=rte+','
            rate=rate[:-1]#去掉最后一个字符
            self.UpdateJsonTestArgs(self.itemName,f'PortNum={self.anetTestCount}|MAC={macinfo}|Rate={rate}','PASS')
            self.lbl_Result.setStyleSheet("background-color: black; color: green;")
            self.lbl_Result.setText("测试PASS!!")
            sys.exit(0)
        elif self.finished_threads < len(self.analysis_threads):
            # 等待所有线程完成
            pass
        else:
            self.updateTimer.emit(False)  # 重新启动定时器
            self.start_analysis_threads()

    def setupUi(self):
        self.setObjectName("Form")
        self.resize(1006, 800)
        icon = QtGui.QIcon()
        icon.addPixmap(QtGui.QPixmap("IMAGE/lan.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 = QtWidgets.QHBoxLayout()
        self.horizontalLayout.setObjectName("horizontalLayout")
        self.horizontalLayout_2 = QtWidgets.QHBoxLayout()
        self.horizontalLayout_2.setObjectName("horizontalLayout_2")
        self.verticalLayout_2 = QtWidgets.QVBoxLayout()
        self.verticalLayout_2.setObjectName("verticalLayout_2")
        self.horizontalLayout_6 = QtWidgets.QHBoxLayout()
        self.horizontalLayout_6.setObjectName("horizontalLayout_6")
        self.lbl_Logo = QtWidgets.QLabel(self)
        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.horizontalLayout_6.addWidget(self.lbl_Logo)
        self.label_3 = QtWidgets.QLabel(self)
        font = QtGui.QFont()
        font.setPointSize(12)
        self.label_3.setFont(font)
        self.label_3.setStyleSheet("color: rgb(255, 255, 255);
"
"background-color: rgb(170, 170, 127);")
        self.label_3.setAlignment(QtCore.Qt.AlignCenter)
        self.label_3.setObjectName("label_3")
        self.horizontalLayout_6.addWidget(self.label_3)
        self.verticalLayout_2.addLayout(self.horizontalLayout_6)
        self.label_2 = QtWidgets.QLabel(self)
        font = QtGui.QFont()
        font.setPointSize(14)
        self.label_2.setFont(font)
        self.label_2.setStyleSheet("background-color: rgb(85, 255, 127);")
        self.label_2.setAlignment(QtCore.Qt.AlignCenter)
        self.label_2.setObjectName("label_2")
        self.verticalLayout_2.addWidget(self.label_2)
        self.horizontalLayout_2.addLayout(self.verticalLayout_2)
        self.horizontalLayout.addLayout(self.horizontalLayout_2)
        self.verticalLayout_3 = QtWidgets.QVBoxLayout()
        self.verticalLayout_3.setObjectName("verticalLayout_3")
        self.horizontalLayout_3 = QtWidgets.QHBoxLayout()
        self.horizontalLayout_3.setObjectName("horizontalLayout_3")
        self.label_7 = QtWidgets.QLabel(self)
        font = QtGui.QFont()
        font.setPointSize(12)
        self.label_7.setFont(font)
        self.label_7.setStyleSheet("background-color: rgb(170, 170, 127);
"
"color: rgb(255, 255, 255);")
        self.label_7.setAlignment(QtCore.Qt.AlignCenter)
        self.label_7.setObjectName("label_7")
        self.horizontalLayout_3.addWidget(self.label_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(85, 170, 127);
"
"color: rgb(255, 255, 255);")
        self.label_8.setAlignment(QtCore.Qt.AlignCenter)
        self.label_8.setObjectName("label_8")
        self.horizontalLayout_3.addWidget(self.label_8)
        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, 255, 127);
"
"color: rgb(255, 255, 255);")
        self.label_6.setAlignment(QtCore.Qt.AlignCenter)
        self.label_6.setObjectName("label_6")
        self.horizontalLayout_3.addWidget(self.label_6)
        self.label_5 = QtWidgets.QLabel(self)
        font = QtGui.QFont()
        font.setPointSize(12)
        self.label_5.setFont(font)
        self.label_5.setStyleSheet("background-color: rgb(255, 170, 0);
"
"color: rgb(255, 255, 255);")
        self.label_5.setAlignment(QtCore.Qt.AlignCenter)
        self.label_5.setObjectName("label_5")
        self.horizontalLayout_3.addWidget(self.label_5)
        self.verticalLayout_3.addLayout(self.horizontalLayout_3)
        self.horizontalLayout_4 = QtWidgets.QHBoxLayout()
        self.horizontalLayout_4.setObjectName("horizontalLayout_4")
        self.label_10 = QtWidgets.QLabel(self)
        font = QtGui.QFont()
        font.setPointSize(12)
        self.label_10.setFont(font)
        self.label_10.setAlignment(QtCore.Qt.AlignCenter)
        self.label_10.setObjectName("label_10")
        self.horizontalLayout_4.addWidget(self.label_10)
        self.lbl_SetPortNum = QtWidgets.QLabel(self)
        font = QtGui.QFont()
        font.setPointSize(12)
        self.lbl_SetPortNum.setFont(font)
        self.lbl_SetPortNum.setAlignment(QtCore.Qt.AlignCenter)
        self.lbl_SetPortNum.setObjectName("lbl_SetPortNum")
        self.horizontalLayout_4.addWidget(self.lbl_SetPortNum)
        self.lbl_SetConntion = QtWidgets.QLabel(self)
        font = QtGui.QFont()
        font.setPointSize(12)
        self.lbl_SetConntion.setFont(font)
        self.lbl_SetConntion.setAlignment(QtCore.Qt.AlignCenter)
        self.lbl_SetConntion.setObjectName("lbl_SetConntion")
        self.horizontalLayout_4.addWidget(self.lbl_SetConntion)
        self.lbl_SetRate = QtWidgets.QLabel(self)
        font = QtGui.QFont()
        font.setPointSize(12)
        self.lbl_SetRate.setFont(font)
        self.lbl_SetRate.setAlignment(QtCore.Qt.AlignCenter)
        self.lbl_SetRate.setObjectName("lbl_SetRate")
        self.horizontalLayout_4.addWidget(self.lbl_SetRate)
        self.verticalLayout_3.addLayout(self.horizontalLayout_4)
        self.horizontalLayout_5 = QtWidgets.QHBoxLayout()
        self.horizontalLayout_5.setObjectName("horizontalLayout_5")
        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.horizontalLayout_5.addWidget(self.label_12)
        self.lbl_GetPortNum = QtWidgets.QLabel(self)
        font = QtGui.QFont()
        font.setPointSize(12)
        self.lbl_GetPortNum.setFont(font)
        self.lbl_GetPortNum.setAlignment(QtCore.Qt.AlignCenter)
        self.lbl_GetPortNum.setObjectName("lbl_GetPortNum")
        self.horizontalLayout_5.addWidget(self.lbl_GetPortNum)
        self.lbl_GetConntion = QtWidgets.QLabel(self)
        font = QtGui.QFont()
        font.setPointSize(12)
        self.lbl_GetConntion.setFont(font)
        self.lbl_GetConntion.setAlignment(QtCore.Qt.AlignCenter)
        self.lbl_GetConntion.setObjectName("lbl_GetConntion")
        self.horizontalLayout_5.addWidget(self.lbl_GetConntion)
        self.lbl_GetRate = QtWidgets.QLabel(self)
        font = QtGui.QFont()
        font.setPointSize(12)
        self.lbl_GetRate.setFont(font)
        self.lbl_GetRate.setAlignment(QtCore.Qt.AlignCenter)
        self.lbl_GetRate.setObjectName("lbl_GetRate")
        self.horizontalLayout_5.addWidget(self.lbl_GetRate)
        self.verticalLayout_3.addLayout(self.horizontalLayout_5)
        self.horizontalLayout.addLayout(self.verticalLayout_3)
        self.verticalLayout.addLayout(self.horizontalLayout)
        self.tableWidget = QtWidgets.QTableWidget(self)
        font = QtGui.QFont()
        font.setPointSize(12)
        self.tableWidget.setFont(font)
        self.tableWidget.setObjectName("tableWidget")
        self.tableWidget.setColumnCount(6)
        self.tableWidget.setRowCount(0)  # 初始化表格行数为0
        self.tableWidget.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectRows)

        item = QtWidgets.QTableWidgetItem()
        item.setTextAlignment(QtCore.Qt.AlignCenter)
        font = QtGui.QFont()
        font.setPointSize(12)
        item.setFont(font)
        item.setBackground(QtGui.QColor(170, 170, 127))
        self.tableWidget.setHorizontalHeaderItem(0, item)
        item = QtWidgets.QTableWidgetItem()
        item.setTextAlignment(QtCore.Qt.AlignCenter)
        font = QtGui.QFont()
        font.setPointSize(12)
        item.setFont(font)
        item.setBackground(QtGui.QColor(0, 170, 127))
        self.tableWidget.setHorizontalHeaderItem(1, item)
        item = QtWidgets.QTableWidgetItem()
        item.setTextAlignment(QtCore.Qt.AlignCenter)
        font = QtGui.QFont()
        font.setPointSize(12)
        item.setFont(font)
        item.setBackground(QtGui.QColor(170, 255, 127))
        self.tableWidget.setHorizontalHeaderItem(2, item)
        item = QtWidgets.QTableWidgetItem()
        item.setTextAlignment(QtCore.Qt.AlignCenter)
        font = QtGui.QFont()
        font.setPointSize(12)
        item.setFont(font)
        item.setBackground(QtGui.QColor(255, 170, 127))
        self.tableWidget.setHorizontalHeaderItem(3, item)
        item = QtWidgets.QTableWidgetItem()
        item.setTextAlignment(QtCore.Qt.AlignCenter)
        font = QtGui.QFont()
        font.setPointSize(12)
        item.setFont(font)
        item.setBackground(QtGui.QColor(85, 255, 127))
        self.tableWidget.setHorizontalHeaderItem(4, item)
        item = QtWidgets.QTableWidgetItem()
        item.setTextAlignment(QtCore.Qt.AlignCenter)
        font = QtGui.QFont()
        font.setPointSize(12)
        item.setFont(font)
        item.setBackground(QtGui.QColor(85, 255, 0))
        self.tableWidget.setHorizontalHeaderItem(5, item)
        self.verticalLayout.addWidget(self.tableWidget)
        self.lbl_Result = QtWidgets.QLabel(self)
        font = QtGui.QFont()
        font.setPointSize(18)
        self.lbl_Result.setFont(font)
        self.lbl_Result.setStyleSheet("background-color: rgb(0, 0, 0);")
        self.lbl_Result.setAlignment(QtCore.Qt.AlignCenter)
        self.lbl_Result.setText("测试中..")
        self.lbl_Result.setObjectName("lbl_Result")
        self.verticalLayout.addWidget(self.lbl_Result)
        self.gridLayout.addLayout(self.verticalLayout, 0, 0, 1, 1)
        self.lbl_Result.setStyleSheet("background-color: black; color: red;")

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

    def retranslateUi(self):
        _translate = QtCore.QCoreApplication.translate
        self.setWindowTitle(_translate("Form", "LAN Test"))
        self.label_3.setText(_translate("Form", "控制过程"))
        self.label_2.setText(_translate("Form", "当前 Realtek PCIe GbE Family Controller测试.."))
        self.label_7.setText(_translate("Form", "测试参数名称"))
        self.label_8.setText(_translate("Form", "端口数"))
        self.label_6.setText(_translate("Form", "连接状态"))
        self.label_5.setText(_translate("Form", "测试速率"))
        self.label_10.setText(_translate("Form", "设置参数"))
        self.lbl_SetPortNum.setText(_translate("Form", str(self.anetTestCount)))
        self.lbl_SetConntion.setText(_translate("Form", "True"))
        self.lbl_SetRate.setText(_translate("Form", f'{str(self.anetRate[0])}M'))
        self.label_12.setText(_translate("Form", "当前测试状态"))
        self.lbl_GetPortNum.setText(_translate("Form", "N/A"))
        self.lbl_GetConntion.setText(_translate("Form", "N/A"))
        self.lbl_GetRate.setText(_translate("Form", "N/A"))
        item = self.tableWidget.horizontalHeaderItem(0)
        item.setText(_translate("Form", "NO"))
        item = self.tableWidget.horizontalHeaderItem(1)
        item.setText(_translate("Form", "项目名称"))
        item = self.tableWidget.horizontalHeaderItem(2)
        item.setText(_translate("Form", "连接状态"))
        item = self.tableWidget.horizontalHeaderItem(3)
        item.setText(_translate("Form", "速率"))
        item = self.tableWidget.horizontalHeaderItem(4)
        item.setText(_translate("Form", "MacAddress"))
        item = self.tableWidget.horizontalHeaderItem(5)
        item.setText(_translate("Form", "测试结果"))
        self.lbl_Result.setText(_translate("COMLPTTest", "测试中.."))

        self.tableWidget.setColumnWidth(0,60)
        self.tableWidget.setColumnWidth(1,140)
        self.tableWidget.setColumnWidth(2,140)
        self.tableWidget.setColumnWidth(3,140)
        self.tableWidget.setColumnWidth(4,280)
        self.tableWidget.setColumnWidth(5,200)
        self.tableWidget.setEditTriggers(QAbstractItemView.NoEditTriggers)  # 表格状态只读
        self.tableWidget.clicked.connect(self.TestThread)  # 表单,单击事件

    #读取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)

    # 读取项目参数信息,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)

    #手动关闭窗口
    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(log)

        except Exception as e:
            print("33[1;31m" + str(e) + " 33[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 TableAddItem(self, port, isPass):
    #     # 检查设备是否已经在表格中
    #     for rowIndex in range(self.tableWidget.rowCount()):
    #         print('port',port)
    #         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] and self.tableWidget.item(rowIndex,3).text()==port[2]:
    #                 # 更新现有行的测试结果
    #                 testResult = 'PASS' if isPass else 'FAIL'
    #                 self.tableWidget.item(rowIndex, 4).setText(testResult)
    #                 if testResult == 'PASS':
    #                     self.tableWidget.item(rowIndex, 4).setForeground(QtGui.QColor(51, 204, 51))
    #                 else:
    #                     self.tableWidget.item(rowIndex, 4).setForeground(QtGui.QColor(255, 51, 51))
    #                 return
    def TableAddItem(self, port, isPass):
        # 检查设备是否已经在表格中
        rowToUpdate = None
        print('self.tableWidget.rowCount()',self.tableWidget.rowCount())
        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]:
                    rowToUpdate = rowIndex
                    break

        if rowToUpdate is not None:
            # 更新现有行
            testResult = 'PASS' if isPass else 'FAIL'
            self.tableWidget.item(rowToUpdate, 5).setText(testResult)
            if testResult == 'PASS':
                self.tableWidget.item(rowToUpdate, 5).setForeground(QtGui.QColor(51, 204, 51))
            else:
                self.tableWidget.item(rowToUpdate, 5).setForeground(QtGui.QColor(255, 51, 51))
        else:
            # 添加新行
            newRow = self.tableWidget.rowCount()
            self.tableWidget.insertRow(newRow)
            self.tableWidget.setRowCount(newRow + 1)  # 增加表格行数
            # ... 添加数据到新行 ...

            # 添加数据到新行
            self.tableWidget.setItem(newRow, 0, QTableWidgetItem(str(newRow + 1)))
            self.tableWidget.setItem(newRow, 1, QTableWidgetItem(port[0]))
            self.tableWidget.setItem(newRow, 2, QTableWidgetItem(port[1]))
            self.tableWidget.setItem(newRow, 3, QTableWidgetItem(port[2]))
            self.tableWidget.setItem(newRow, 4, QTableWidgetItem(port[3]))

            testResult = 'PASS' if isPass else 'FAIL'
            resultItem = QTableWidgetItem(testResult)
            resultItem.setTextAlignment(Qt.AlignCenter)
            self.tableWidget.setItem(newRow, 5, resultItem)

            if testResult == 'PASS':
                resultItem.setForeground(QtGui.QColor(51, 204, 51))
            else:
                resultItem.setForeground(QtGui.QColor(255, 51, 51))

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

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