python程控电源编程(2)

# -*- coding: utf-8 -*-
#!/usr/bin/python
"""
Module implementing Watch_MainWindow.

 @Author:      TOBY
 @Email:       hejunwang@
 @DateTime:    2019-07-18 09:16:43
 @Description: keithley  2303 程控电源 ,RIGOL dm3068  读取电压和电流软件


"""
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *

from Ui_watchcurrent_ui import Ui_MainWindow
import sys
import visa
import threading
import time
from PyQt5.QtWidgets import qApp

class Watch_MainWindow(QMainWindow, Ui_MainWindow):
    """
    Class documentation goes here.
    """
    def __init__(self, parent=None):
        """
        Constructor
        
        @param parent reference to the parent widget
        @type QWidget
        """
        super(Watch_MainWindow, self).__init__(parent)
        self.setupUi(self)
        
        self.init()
        #设置框架的大小, 取消最大化
        self.setFixedSize(self.width(), self.height())
        
        self.statusBar.showMessage("Ready")
        
    #TODO 初始化设备
    def init(self):
        self.rm = visa.ResourceManager()
        self.dev =self.rm.list_resources()
        print(self.dev)
        
        
        self.rm2 = visa.ResourceManager()
        self.dev2 =self.rm2.list_resources()
        print(self.dev2)
        
        self.rigol = visa.ResourceManager()
        self.dm3068 =self.rigol.list_resources()
        print(self.dm3068)
        
        #停止按键设置灰色不可点击状态
        self.w_stop_btn.setEnabled(False)
    
        #设备是否连接
        self.IsCon = False
        self.IsCon2 = False
        self.IsCon3 = False
        
        #保存数据列表
        self.dataList=[]
        #保存测试的电压的数据
        self.dm3068List=[]
        
        #菜单
        self.menuAction()
        

    #TODO 计时器显示
    def lcdNum(self):
        #定时器
        self.second = 0  
        self.minute = 0
        self.hour = 0
        self.days = 0
        self.lcdtimer = QTimer(self)
        self.lcdtimer.timeout.connect(self.onTimerOut)
        self.lcdtimer.start(1000)
        
        #计数器
        self.jishu = 0
        
    def onTimerOut(self):
        self.second += 1
        self.jishu += 1

        if self.second%60==0:
            self.minute+=1
            self.second =0
            print('minute:'+str(self.minute))
            
            if self.minute%60==0:
                self.hour+=1
                self.minute=0
                print('minute:---'+str(self.minute))
                print('hour:'+str(self.hour))
            else:
                print('minute:--->'+str(self.minute))
                print('hour-->:'+str(self.hour))
        
        #采集时间长度
        self.duration_time= int(self.w_duration.text())
        #按照规定采集的时间到了 ,进行停止
        if self.jishu %self.duration_time==0:
            print('停止计时')
            self.data_save()
            self.data2_save()
            self.w_remind.append("###测量的实际电压###:"+str(self.t2)+
        " V"+ '---'+"###平均电流###:"+str(self.avgdata)+" mA"+
        "###充电平均电流###:"+str(self.avgdata2)+" mA")
#            self.all_timer_stop()
#            self.stopbtn_set()
            
            #保存数据
#           self.data_save()
#           self.w_remind.append('采集数据数量:'+str(self.lendata)+"\n") 

            
        self.w_lcd.display(str(self.hour)+":"+str(self.minute)+
        ":"+str(self.second))
        

    @pyqtSlot()
    def on_w_connect_btn_clicked(self):
        """
        Slot documentation goes here.
        """
        # TODO: 连接仪器一
#        self.init()
#        raise NotImplementedError
        try :
            print('on_w_connect_btn_clicked')

            self.my_instrument = self.rm.open_resource(self.dev[1])
            self.w_remind.append('仪器仪表查询结果:\n'+self.my_instrument.query('*IDN?'))
            print('读取*IDN?结果:\n'+self.my_instrument.query('*IDN?'))
            self.w_remind.append('当前查询到的设备:'+str(self.dev))
            #设置按键灰色
            self.w_connect_btn.setEnabled(False)
            self.IsCon = True
            print(self.IsCon)
            
            self.read_config()   #读取配置文件
                
        except :
            print("异常了")
            self.msg('仪器连接失败,请检查驱动是否安装成功'+'\n'+'或者是仪器是否开机')
            self.w_connect_btn.setEnabled(True)
            
    
    
    
    @pyqtSlot()
    def on_w_connect_btn2_clicked(self):
        """
        Slot documentation goes here.
        """
        # TODO: 连接仪器二
#        self.init()
#        raise NotImplementedError
        
        #是否设置为自动增加电压 标志位
        if self.comboBox_2.currentText()=="否":
            
            self.IsCon2= False
            self.msg('请选择启动电源二的开关')
        else:
            
            try :
                print('on_w_connect_btn2_clicked')
                
                self.my_instrument2 = self.rm2.open_resource(self.dev2[2])
                self.w_remind.append('仪器仪表查询结果:\n'+self.my_instrument2.query('*IDN?'))
                print('读取*IDN?结果:\n'+self.my_instrument2.query('*IDN?'))
                self.w_remind.append('当前查询到的设备:'+str(self.dev2[2]))
                #设置按键灰色
                self.w_connect_btn2.setEnabled(False)
                
                self.IsCon2=True
#                #读取仪器2所设置的参数
                self.read_config2()
                
        
            except :
                print("异常了")
                self.msg('仪器连接失败,请检查驱动是否安装成功'+'\n'+'或者是仪器是否开机')
                self.w_connect_btn2.setEnabled(True)
            
        

    
    
    #弹出框
    def msg(self, str):
        reply = QMessageBox.critical(self, '提示信息', str)
        print(reply)
    
    

    #配置1设置的参数
    def read_config(self):
        #TODO 参数设置
        
        self.reset()
        
        #是否设置为自动增加电压 标志位
        if self.comboBox.currentText()=="否":
            
            self.is_Volt_Auto= False
        else:
            self.is_Volt_Auto= True
        
        print('是否自动电压自动增加处理:'+self.comboBox.currentText())
        
#        TODO 打开电源通道
        self.my_instrument.write(":OUTP ON")
        print('OUTP 电源通道的开启')
        self.w_remind.append('当前通道的状态:'+self.my_instrument.query(':OUTP?'))
        
        #--#读取界面设置的电压值,作为参数------------------------------------
        print(type(self.w_setting_volt.text()))
        self.setvolt = self.w_setting_volt.text()
#        print(self.setvolt+"...........")
        self.my_instrument.write(":VOLT "+self.setvolt)
        
        print('设置当前电压值:'+self.my_instrument.query(':VOLT?'))
#        self.w_remind.append('设置电压值:'+self.my_instrument.query(':VOLT?'))
        
        
        #读取界面设置的电流值,作为参数
        self.setcurrent = self.w_setting_current.text()
        self.my_instrument.write(":CURR "+self.setcurrent)
        
#        my_instrument.write(":OUTPut:TIMer:DATA 100")
        print('设置当前电流值:'+self.my_instrument.query(':CURR?'))
        self.w_remind.append('设置当前电流值:'+self.my_instrument.query(':CURR?'))
        
        self.w_remind.append('电源的软件版本号:'
        +self.my_instrument.query(':SYSTem:VERSion?'))
        
        self.w_remind.append('电源的出错信息:'+self.my_instrument.query(':SYSTem:ERRor?'))
        self.w_remind.append('连接设备1成功!!!')
        
        #配置2设置的参数
    def read_config2(self):
        #TODO 参数设置
        
        self.reset2()
        
#        TODO 打开电源通道
        self.my_instrument2.write(":OUTP ON")
        print('OUTP 电源通道的开启')
        self.w_remind.append('当前通道的状态:'+self.my_instrument2.query(':OUTP?'))
        
        #--#读取界面设置的电压值,作为参数------------------------------------

        self.setvolt2 = self.w_setting_volt2.text()

        self.my_instrument2.write(":VOLT "+self.setvolt2)
        
        print('设置当前电压值:'+self.my_instrument2.query(':VOLT?'))
#        self.w_remind.append('设置电压值:'+self.my_instrument.query(':VOLT?'))
        
        
        #读取界面设置的电流值,作为参数
        self.setcurrent2 = self.w_setting_current2.text()
        self.my_instrument2.write(":CURR "+self.setcurrent2)
        
#        my_instrument.write(":OUTPut:TIMer:DATA 100")
        print('设置当前电流值:'+self.my_instrument2.query(':CURR?'))
        self.w_remind.append('设置当前电流值:'+self.my_instrument2.query(':CURR?'))
        
        self.w_remind.append('电源的软件版本号:'
        +self.my_instrument2.query(':SYSTem:VERSion?'))
        
        self.w_remind.append('电源的出错信息:'+self.my_instrument2.query(':SYSTem:ERRor?'))
        self.w_remind.append('连接设备2成功!!!')
        
    

    
    
    @pyqtSlot()
    def on_w_run_btn_clicked(self):
        """
        Slot documentation goes here.
        """
        # TODO 执行操作

        #电源一数据存储
        self.dataList=[]
        #电源二数据存储 
        self.data2List=[]
        #万用表数据
        self.dm3068List=[]
        
        #是否设置为自动增加电压 标志位
        if self.comboBox.currentText()=="否":
            
            self.is_Volt_Auto= False
        else:
            self.is_Volt_Auto= True
        
        #清理前一次显示的数据
        self.w_max_current.setText('0.000')
        self.w_min_current.setText('0.000')
        self.w_avg_current.setText('0.000')
        
        #判断设备一是否连接成功
        if self.IsCon:
            
            print(self.w_setting_volt.text())
            self.setvolt = float(self.w_setting_volt.text())
            self.lowvolt = float(self.w_low_volt.text())
            self.hightvolt = float(self.w_hight_volt.text())
            #TODO 出现两种情况 
            #1 使用电压调节,电压自动增长,读取电流值,保存数据
            #2 使用电流测试, 读取一段时间内的电流的数据 ,获取电流的平均值,保存数据
            
            if self.is_Volt_Auto:
                pass
                print('电压调节测试')
                self.read_config()
                
                self.volttimer = QTimer(self)
                self.volttimer.timeout.connect(self.timeout_slot)
                self.volttimer.start(5000)
                
                self.w_run_btn.setEnabled(False)
                self.w_stop_btn.setEnabled(True)
                
            else:
                #1判断设置的电压的大小是否符合规则 
                #2显示电流的数据在界面上
                
                if (self.setvolt< self.lowvolt) or (self.setvolt> self.hightvolt):
                    self.msg('请重新设置电压参数值,不要低于最低电压阈值或者超过最高电压阈值')
                else:
                    #开始数据采集
                    self.data_Collection()
                    
                    #按键设置
                    self.w_run_btn.setEnabled(False)
                    self.w_stop_btn.setEnabled(True)
                    self.w_remind.append('***开始测量计数中***')
                    
                    #计时器 计算测试的时常
                    self.lcdNum()
            
            
        else:
            self.msg('亲,请先连接仪器哦!')

        

    
    
    #TODO       
    def data_Collection(self):
        self.timer = QTimer(self)
        
        #采集数据的间隔,即 一秒钟采集多少次数据
        self.timedelay = int(self.w_time_delay.text())
        
        if self.timedelay<250:
            #经过测试发现得到的数据 250ms能够得到4个数据 ,低于250,就不能在规定的时间得到相应的数据
            self.timer.start(250)
        
        self.timer.start(self.timedelay)        
#             #开始进行测量 计时结束调用operate()方法    
        self.timer.timeout.connect(self.timeout_slot)

        
    def timeout_slot(self):
        local_time = QDateTime.currentDateTime()
        # 时间显示格式w_remind
#        self.w_remind.append(time.toString(Qt.ISODate)+'<:当前电压:>'+self.my_instrument.query(':MEAS?'))
        print(local_time.toString(Qt.ISODate)+'<:当前电压:>'+self.my_instrument.query(':MEAS:VOLT?'))
#        self.w_remind.append(time.toString(Qt.ISODate)+'<:当前电流:>'+self.my_instrument.query(':MEAS:CURR?'))
        print(local_time.toString(Qt.ISODate)+'<:当前电流:>'+self.my_instrument.query(':MEAS:CURR?'))
#        print(type(self.my_instrument.query(':MEAS:CURR?')))
        
        #电流1
        self.tempcurr = float(self.my_instrument.query(':MEAS:CURR?'))*1000
        #round 保留指定的小数位
        self.t1 = round(self.tempcurr, 3)
        print(self.t1)
        self.w_now_current.setText(str(self.t1))
        
        #电压
        self.tempvolt =float(self.my_instrument.query(':MEAS:VOLT?'))
        #round 保留指定的小数位
        self.t2 = round(self.tempvolt, 3)
        print(self.t2)
        self.w_current_volt.setText(str(self.t2))
        
        
        
        if self.IsCon2:
            #电流2
            self.tempcurr2 = float(self.my_instrument2.query(':MEAS:CURR?'))*1000
            #round 保留指定的小数位
            self.tmpc2 = round(self.tempcurr2, 3)
            print(self.tmpc2)
            self.w_now_current.setText(str(self.tmpc2))
        
        
        
        
    
        #判断rigol 是否连接 ,如果连接成功 ,就启动测试功能
        if self.IsCon3:
            #rigol 电压电压 DC
            self.tempvolt3 =float(self.my_instrument3.query(':MEAS:VOLT:DC?'))
            #round 保留指定的小数位
            self.t3 = round(self.tempvolt3, 3)
            print('rigol读取到的电压值-->'+str(self.t3))
            self.w_current_volt3.setText(str(self.t3))
            
            self.dm3068List.append(self.t3)
        
        #TODO 数据保存到列表中
        self.dataList.append(self.t1)
        self.data2List.append(self.tmpc2)
        
        
        
        #测试电压自动增加
        if self.is_Volt_Auto:
            
            self.w_remind.append(local_time.toString(Qt.ISODate)+"-->设置电压:"+
        self.w_setting_volt.text()+'V'+
        "-->实际电压:"+str(self.t2)+" V"+
        "-->实际电流:"+str(self.t1)+" mA"+"-->充电电流:"+str(self.tmpc2)+'mA')
            
            #设定的电压值
            a = float(self.setvolt)+float(self.w_volt_step.text())
            self.w_setting_volt.setText(str(round(a, 3)))

            self.setvolt = self.w_setting_volt.text()

            self.my_instrument.write(":VOLT "+self.setvolt)
            
            
            #如果设定的电压值超过了电压阈值,自动停止
            if a > self.hightvolt:
                
                self.reset()
                #显示设置
                self.w_run_btn.setEnabled(True)
                self.w_stop_btn.setEnabled(False)
                self.w_connect_btn.setEnabled(False)
                self.volttimer.stop()
                
                self.w_remind.append('************停止测试************\n')   
        else:
            if self.IsCon3:
                
                self.w_remind.append("测量的实际电压:"+str(self.t2)+
            " V"+ '---'+"实时电流:"+str(self.t1)+" mA"+"DM3068电压:"+str(self.t3))
            else:
                self.w_remind.append("测量的实际电压:"+str(self.t2)+
            " V"+ '---'+"实时电流:"+str(self.t1)+" mA"+"----充电电流:"+str(self.tmpc2))
    
    
   
  
    #保存数据方法
    def data_save(self):
        maxdata =round(max(self.dataList), 3)
        mindata =round(min(self.dataList), 3) 
        self.lendata = len(self.dataList)
        self.avgdata = round(sum(self.dataList)/self.lendata, 3)
        
        self.w_max_current.setText(str(maxdata))
        self.w_min_current.setText(str(mindata))
        self.w_avg_current.setText(str(self.avgdata))
        
        
        #清空20s的数据
        self.dataList=[]



    def data2_save(self):
#        maxdata =round(max(self.dataList), 3)
#        mindata =round(min(self.dataList), 3) 
        self.lendata = len(self.data2List)
        self.avgdata2 = round(sum(self.data2List)/self.lendata, 3)
        
#        self.w_max_current.setText(str(maxdata))
#        self.w_min_current.setText(str(mindata))
        self.w_avg_current2.setText(str(self.avgdata2))
        
#        self.w_remind.append("######测量的实际电压######:"+str(self.t2)+
#        " V"+ '---'+"######平均电流######:"+str(avgdata)+" mA")
        #清空20s的数据
        self.data2List=[]
        
    
    
    
    
    @pyqtSlot()
    def on_w_stop_btn_clicked(self):
        """
        Slot documentation goes here.
        """
        # TODO: 停止测试
#        raise NotImplementedError
        print('on_w_stop_btn_clicked')
        self.stopbtn_set()
        self.all_timer_stop()
        
        self.w_remind.append('************停止测试************\n')    
     
  
  
    def stopbtn_set(self):
        
        #显示设置
        self.w_run_btn.setEnabled(True)
        self.w_stop_btn.setEnabled(False)
        
#        if self.IsCon:
#            self.reset()
#            self.w_connect_btn.setEnabled(True)
#        if self.IsCon2:
#            self.reset2()
#            self.w_connect_btn2.setEnabled(True)
#        if self.IsCon3:
#            self.reset3()
#            self.w_connect_btn3.setEnabled(True)


        
    
    #定时器停止
    def all_timer_stop(self):
        if self.is_Volt_Auto:
            self.volttimer.stop()
        else:
            #采集停止
           self.timer.stop()
           #统计测试时间停止
           self.lcdtimer.stop()
           
             
        #保存数据
           self.data_save()
           self.w_remind.append('采集数据数量:'+str(self.lendata)+"\n") 
            
        
    
    #复位1
    def reset(self):
#        TODO: 复位设置
        self.my_instrument.write('*CLS')
        self.my_instrument.write('*RST') 
        
    #复位2
    def reset2(self):
#        TODO: 复位设置
        self.my_instrument2.write('*CLS')
        self.my_instrument2.write('*RST') 
        
    #复位3
    def reset3(self):
#        TODO: 复位设置
        self.my_instrument3.write('*CLS')
        self.my_instrument3.write('*RST') 
    
        
    @pyqtSlot()
    def on_w_excelOut_btn_clicked(self):
        """
        Slot documentation goes here.
        """
        # TODO: 导出数据csv
#        raise NotImplementedError
        pass
    
    @pyqtSlot()
    def on_w_connect_btn3_clicked(self):
        """
        Slot documentation goes here.
        """
        # TODO: not implemented yet
#        raise NotImplementedError
        
        try:
            pass
            self.my_instrument3 = self.rm.open_resource(self.dm3068[2])
            time.sleep(1)
            self.w_remind.append('仪器仪表查询结果:\n'+self.my_instrument3.query('*IDN?'))
            self.w_remind.append('读取*IDN?结果:\n'+self.my_instrument3.query('*IDN?'))
            self.w_remind.append('系统错误结果:\n'+self.my_instrument3.query(':SYST:ERR?'))
            self.w_remind.append('SCPI版本号结果:\n'+self.my_instrument3.query(':SYST:VERS?'))
            print('读取*IDN?结果:\n'+self.my_instrument3.query('*IDN?'))
            print('系统错误结果:\n'+self.my_instrument3.query(':SYST:ERR?'))
            print('SCPI版本号结果:\n'+self.my_instrument3.query(':SYST:VERS?'))
        
    #        self.w_remind.append('当前查询到的设备:'+str(self.dev[2]))
            self.reset3()
            self.IsCon3 =True
            
            time.sleep(1)
            #功能 设定
            self.my_instrument3.write(':FUNCtion:VOLTage:DC')
            time.sleep(1)
            
            #电流需要调节设备的插孔
    #        self.my_instrument3.write(':FUNCtion:CURRent:DC')
    #        time.sleep(1)
    #        print('读取到的电流值'+str(self.my_instrument3.query(':MEAS:CURR:DC?')))
             
            #电压 DC
    #        self.tempvolt3 =float(self.my_instrument3.query(':MEAS:VOLT:DC?'))
    #        #round 保留指定的小数位
    #        self.t3 = round(self.tempvolt3, 3)
    #        print('读取到的电压值'+str(self.t3))
    #        self.w_current_volt3.setText(str(self.t3))
    
    
            self.w_connect_btn3.setEnabled(False)
            
            #设置标识位,连接成功
            self.IsCon3 = True
            
        except:
            pass
            self.msg("DM3068连接失败,请确认设备是否正常启动或者\n驱动是否安装成功")
            
        

        
    #Action  menu
    def menuAction(self):  
        self.new_action.triggered.connect(self.newtrigger)
        self.about_action.triggered.connect(self.abouttrigger)
        self.actionVersion.triggered.connect(self.versionaction)
        self.actionGuide.triggered.connect(self.guideaction)
        

    def newtrigger(self):  
        #输出那个Qmenu对象被点击
        print('is triggeres')
        if self.IsCon:
            self.reset()
            self.w_connect_btn.setEnabled(True)
        if self.IsCon2:
            self.reset2()
            self.w_connect_btn2.setEnabled(True)
        if self.IsCon3:
            self.reset3()
            self.w_connect_btn3.setEnabled(True)
            
#        QMessageBox.information(self,"Information","暂时没有操作,稍后会进行完善")
        
    def abouttrigger(self):
        print('about_action')
        QMessageBox.aboutQt(self,"About Qt")
        
    
    def versionaction(self):
        QMessageBox.information(self,"Information","程序当前版本为V1.1,如果有问题请联系:[email protected]"+"\n")
    
    def guideaction(self):
        print('information')
        QMessageBox.information(self,"Information",'请阅读使用说明文档')
        
    
if __name__ == "__main__":

    app = QtWidgets.QApplication(sys.argv)
    MainWindow =Watch_MainWindow()
    MainWindow.show()
    sys.exit(app.exec_())
    

实现电流测试的功能

你可能感兴趣的:(python程控电源编程(2))