Ejemplo n.º 1
0
 def getPortInfo(self, port):
     return {
         "Vendor": QSerialPortInfo(port).vendorIdentifier(),
         "Product": QSerialPortInfo(port).productIdentifier(),
         "Serial": QSerialPortInfo(port).serialNumber(),
         "Port": QSerialPortInfo(port).systemLocation()
     }
    def __init__(self,
                 debug=False,
                 vendor_id=6790,
                 product_id=29987,
                 start_command=b'(A)',
                 stop_command=b'(S)'):
        super().__init__()
        self.vendor_id = vendor_id
        self.product_id = product_id
        self.start_command = start_command
        self.stop_command = stop_command
        self.available_to_use = False
        self.online = False
        self.running = False
        self.debug = debug

        if self.debug:
            print('\n- - - - - - - - - - - - - - - - - - - - - - - - - - -')
            print('Numero de portas seriais conectadas ao PC: {}'.format(
                len(QSerialPortInfo().availablePorts())))

        for port_info in QSerialPortInfo().availablePorts():
            if (port_info.hasVendorIdentifier()
                    and port_info.hasProductIdentifier()):
                if (port_info.vendorIdentifier() == vendor_id
                        and port_info.productIdentifier() == product_id):
                    self.port_name = port_info.portName()
                    self.available_to_use = True

        if self.available_to_use:
            if self.debug:
                print('Dispositivo de controle da esteira encontrado'
                      ' com sucesso!')
            self.setPortName(self.port_name)
            self.setBaudRate(QSerialPort.Baud9600, QSerialPort.AllDirections)
            self.setDataBits(QSerialPort.Data8)
            self.setParity(QSerialPort.NoParity)
            self.setStopBits(QSerialPort.OneStop)
            self.setFlowControl(QSerialPort.NoFlowControl)

            # Apos todas as configuracoes tenta conectar com a porta serial
            if self.open(QSerialPort.ReadWrite):
                if self.debug:
                    print('Comunicacao estabelecida com sucesso!')
                self.online = True
            else:
                if self.debug:
                    print('Erro: nao foi possivel estabelecer a comunicacao'
                          ' com o dispositivo de controle da esteira.')
        else:
            if self.debug:
                print('Aviso: dispositivo de controle da esteira '
                      'nao encontrado.')
                print(
                    '- - - - - - - - - - - - - - - - - - - - - - - - - - -\n')
Ejemplo n.º 3
0
    def OpenSerial(self):
        if self.PushButton_Open.text() == "打开串口":
            #           serial.Serial.port = self.ComboBox_portName.currentText()
            #           print(serial.Serial)
            self.port_mes = QSerialPortInfo(
                self.ComboBox_portName.currentText())
            self.serial_port_state = self.port_mes.isBusy()
            if self.serial_port_state == False:
                self.SerialPort = serial.Serial()
                self.SerialPort.port = self.ComboBox_portName.currentText()
                self.SerialPort.baudrate = 19200  #serial.Serial.baudrate = 19200
                self.SerialPort.bytesize = 8  #serial.Serial.bytesize = 8
                self.SerialPort.stopbits = 1  #serial.Serial.stopbits = 1
                self.SerialPort.parity = serial.PARITY_NONE  #serial.Serial.parity = serial.PARITY_NONE
                #  print(serial.Serial.parity)
                #  print(serial.Serial.port)
                self.SerialPort.timeout = 0  #serial.Serial.timeout = 0
                try:
                    # 打开串口
                    # self.port = serial.Serial(serial_name1, baud_rate, int(data_bseit), parity=serial.PARITY_NONE)#打开串口
                    # self.port.open()
                    #                    print(self.SerialPort)
                    self.SerialPort.open()
                    #                    print(self.SerialPort)
                    self.port_mes = QSerialPortInfo(
                        self.SerialPort.port)  # 判断串口状态,若是则返回True,反之返回False
                    #                    print(self.port_mes)
                    self.serial_port_state = self.port_mes.isBusy()
                    #                    print(self.serial_port_state)
                    if self.serial_port_state == True:  # 再增加一个判断串口是否占用,若已占用,说明已打开成功
                        self.PushButton_Open.setText(
                            "关闭串口")  # 串口打开成功后状态显示为打开状态,即关闭
                        self.PushButton_read.setEnabled(True)
                        self.PushButton_set.setEnabled(True)

                        self.timer = QTimer(self)
                        self.timer.timeout.connect(self.receive_data)
                        self.timer.start(10)
                        #                        self.pushButton_ture()  # 成功打开串口后,再使能相关按钮
                        #                        self.receive_data(1)  # 打开成功后接收使能打开
                        QtWidgets.QApplication.processEvents()
                except:
                    #                   my_pyqt_wigth.show()
                    #                   my_pyqt_wigth.serial_open_error_mage()
                    print("串口打开失败")
                    pass

        elif self.PushButton_Open.text() == '关闭串口':

            # time.sleep(0.2)
            # print(type(self.port))
            self.SerialPort.close()
            self.PushButton_Open.setText("打开串口")
            self.PushButton_set.setEnabled(False)
            self.PushButton_read.setEnabled(False)
Ejemplo n.º 4
0
 def _open(self,
           port_name,
           baudrate=QSerialPort.Baud9600,
           data_bits=QSerialPort.Data8,
           flow_control=QSerialPort.NoFlowControl,
           parity=QSerialPort.NoParity,
           stop_bits=QSerialPort.OneStop):
     """
     인자값으로 받은 시리얼 접속 정보를 이용하여 해당 포트를 연결한다.
     :param port_name:
     :param baudrate:
     :param data_bits:
     :param flow_control:
     :param parity:
     :param stop_bits:
     :return: bool
     """
     info = QSerialPortInfo(port_name)
     self.serial.setPort(info)
     self.serial.setBaudRate(baudrate)
     self.serial.setDataBits(data_bits)
     self.serial.setFlowControl(flow_control)
     self.serial.setParity(parity)
     self.serial.setStopBits(stop_bits)
     return self.serial.open(QIODevice.ReadWrite)
Ejemplo n.º 5
0
    def init(self):

        self.serianame = ''
        self.com = QSerialPort()
        self.cominfo = QSerialPortInfo()
        self.infos = self.cominfo.availablePorts()
        for info in self.infos:
            print("Name:", info.portName())
            print("vendoridentifier:", info.vendorIdentifier())

            # 串口信息认证
            if info.vendorIdentifier() == 6790:
                self.serianame = info.portName()

        self.com.setPortName(self.serianame)
        self.com.setBaudRate(9600)

        # 打开串口
        if self.com.open(QSerialPort.ReadWrite) == False:
            print("open fault")
            return

        # 设置定时函数
        self.readtimer = QTimer()
        self.readtimer.timeout.connect(self.readData)  # 读信号
        self.readtimer.start(200)  # 每200ms读一次数据
Ejemplo n.º 6
0
def updateList():
    portList = []
    ports = QSerialPortInfo().availablePorts()
    for port in ports:
        portList.append(port.portName())
    ui.comL.clear()
    ui.comL.addItems(portList)
Ejemplo n.º 7
0
 def _serial_scan_btn(self):
     info_list = QSerialPortInfo()
     serial_list = info_list.availablePorts()
     self._serial_ports = [port.portName() for port in serial_list]
     #print(self._serial_ports[0])
     self._widget.comboBox.clear()
     self._widget.comboBox.addItems(self._serial_ports)
Ejemplo n.º 8
0
    def __asyc_detect_new_device_handle(self, device):
        device_name = device[1]
        prefixPath = r"/dev/"
        if device_name[:len(prefixPath)] == prefixPath:
            device_name = device_name[len(prefixPath):]
        self.__set_all_button(False)
        self.info.has_firmware = False
        self.info.board_id = None
        self.info.board_name = device_name
        port = QSerialPortInfo(device_name)

        def match(pvid, ids):
            for valid in ids:
                if pvid == valid:
                    self.info.board_id = str(valid)
                    return True
            return False

        pvid = (port.vendorIdentifier(), port.productIdentifier())
        print(device_name, pvid)

        # need match the seeed board pid vid
        if match(pvid, self.info.board_normal):
            self.invoke.in_bootload_mode = False
            self.invoke.detected = True
            print("detect a normal mode borad")
        if match(pvid, self.info.board_boot):
            self.invoke.in_bootload_mode = True
            self.invoke.detected = True
            print("detect a bootload mode borad")
Ejemplo n.º 9
0
 def refreshPorts(self):
     self.cbxPort.clear()
     ports = reversed(
         sorted(port.portName()
                for port in QSerialPortInfo.availablePorts()))
     for p in ports:
         port = QSerialPortInfo(p)
         self.cbxPort.addItem(port.portName(), port.systemLocation())
Ejemplo n.º 10
0
    def _get_available_port(self):
        result = []

        for port in QSerialPortInfo().availablePorts():

            result.append(port.portName() if __platform__.startswith('win') else "/dev/" + port.portName())

        return result
Ejemplo n.º 11
0
 def updatePort(self):
     if len(self.availablePorts) != len(QSerialPortInfo().availablePorts()):#如果串口信息改变
         self.availablePorts = portInfo.availablePorts()  # 更新串口信息
         self.portOpen=False#串口标志位关闭
         self.port.close()#关闭串口
         availablePortList=[]
         for port in self.availablePorts:
             availablePortList.append(port.description()+' ('+port.portName()+')')
         self.gpsAvailablePortSig.emit(availablePortList)#发送新的串口信息
         self.portOpenSig.emit(self.portOpen)#GUI按钮状态改变
Ejemplo n.º 12
0
 def __init__(self, number=0):
     super().__init__()
     ports = QSerialPortInfo.availablePorts()
     if len(ports) < 1:
         logger.warning('No serial ports')
     port = QSerialPortInfo(ports[number])
     print(port.systemLocation())
     self.serial = QSerialDevice(port=port)
     if self.serial.isOpen():
         print('open')
         print(self.serial.handshake('VERSION'))
Ejemplo n.º 13
0
 def __init__(self,parent=None):
     super(MyPort, self).__init__(parent)
     self.ser=None
     self.portOpen=False
     self.headerList = ['GPHPD', 'GTIMU', 'GPFPD']
     self.portInfo=QSerialPortInfo()
     self.availablePorts=[]
     self.port=QSerialPort()
     self.paritySet={'even':QSerialPort.EvenParity,'odd':QSerialPort.OddParity,'none':QSerialPort.NoParity}
     self.time=QTimer()
     self.time.timeout.connect(self.updatePort)
     self.time.start(500)
 def getPorts(self):
     oldport = self.port.portName() if self.port else None
     
     self.ports = QSerialPortInfo().availablePorts()
     self.comboBox_port.clear()
     for port in self.ports:
         self.comboBox_port.addItem(port.portName() + " : " + port.description())
     self.update()
     plist = [p.portName() for p in self.ports]
     if oldport in plist:
         self.comboBox_port.setCurrentIndex(plist.index(oldport))
     self.selectPort(self.comboBox_port.currentIndex())
Ejemplo n.º 15
0
def get_serial_ports():
    """
     Liste les ports serie disponibles avec leur description

    """
    info_list = QSerialPortInfo()
    serial_list = info_list.availablePorts()
    serial_ports = []
    for port in serial_list:
        name = port.portName()
        descr = port.description()
        serial_ports.append(name + " : " + descr)
    return serial_ports
Ejemplo n.º 16
0
def get_serial_ports():
    """ List les ports séries disponible et leurs noms
    :raise EnvironmentError:
        Plateforme inconnue
    :return:
        La list des ports serial dispo sur le système
    """
    # if sys.platform.startswith('linux'):
    #     serial_ports = glob.glob('/dev/athome*')
    # else:
    info_list = QSerialPortInfo()
    serial_list = info_list.availablePorts()
    serial_ports = [port.portName() for port in serial_list]
    return serial_ports
Ejemplo n.º 17
0
 def __init__(self):
     self.app = QApplication(sys.argv)
     self.mainWidget = uic.loadUi("main.ui")
     mWid = self.mainWidget
     for port in QSerialPortInfo().availablePorts():
         mWid.aPorts.addItem(port.systemLocation())
     mWid.actionExit.triggered.connect(self.close)
     mWid.actionOpen.triggered.connect(self.binOpen)
     mWid.cBConsole.activated.connect(self.usableMemory)
     mWid.dumpBtn.released.connect(self.dump)
     mWid.burnBtn.released.connect(self.burn)
     mWid.burnBtn.setDisabled(True)
     #mWid.dumpBtn.setDisabled(True)
     self.initConsole()
     mWid.show()
Ejemplo n.º 18
0
    def __init__(self):
        QWidget.__init__(self, flags=Qt.Widget)
        # 위젯 선언
        self.gb = QGroupBox(self.tr("Serial"))
        self.cb_port = QComboBox()
        self.cb_baud_rate = QComboBox()

        # 시리얼 인스턴스 생성
        # 시리얼 스레드 설정 및 시작
        self.serial = QSerialPort()
        self.serial_info = QSerialPortInfo()
        self.serial_read_thread = SerialReadThread(self.serial)
        self.serial_read_thread.received_data.connect(
            lambda v: self.received_data.emit(v))
        self.serial_read_thread.start()

        self.init_widget()
Ejemplo n.º 19
0
    def find(self):
        '''
        Attempt to identify and open the serial port

        Returns
        -------
        find : bool
            True if port identified and successfully opened.
        '''
        ports = QSerialPortInfo.availablePorts()
        if len(ports) < 1:
            logger.warning(' No serial ports detected')
            return
        for port in ports:
            portinfo = QSerialPortInfo(port)
            if self.setup(portinfo):
                break
Ejemplo n.º 20
0
    def run(self):
        """
    Собственно сама проверка существования порта
    """
        if self.port == "":
            return

        port_exist = False
        for port_info in QSerialPortInfo().availablePorts():
            if port_info.portName() == self.port:
                port_exist = True
                break

        if port_exist is False and self.port_exist is True:
            self.off.emit()
        elif port_exist is True and self.port_exist is False:
            self.on.emit()

        self.port_exist = port_exist
Ejemplo n.º 21
0
    def __init__(self):
        QWidget.__init__(self, flags=Qt.Widget)
        self.gb = QGroupBox(self.tr("Serial"))
        self.cb_port = QComboBox()
        self.cb_baud_rate = QComboBox()
        self.cb_data_bits = QComboBox()
        self.cb_flow_control = QComboBox()
        self.cb_parity = QComboBox()
        self.cb_stop_bits = QComboBox()

        #serial instance
        #serial thread set up and start
        self.serial = QSerialPort()
        self.serial_info = QSerialPortInfo()
        self.serial_read_thread = SerialReadThread(self.serial)
        self.serial_read_thread.received_data.connect(
            lambda v: self.received_data.emit(v))
        self.serial_read_thread.start()

        self.init_widget()
Ejemplo n.º 22
0
    def SerialMode(self):
        """
        设置串口,并发送指令
        :return:
        """
        # 1.保存盖章图片,历史留底
        # loacltime = time.strftime("%Y%m%d%H%M%S", time.localtime())
        save_img_name = save_img_path
        image_saver(contract_path, save_img_name)

        # 2.设置发送数据
        # self.serialwork.Set_sendData(self.senddata)
        # self.serialwork.writeData()


        try:
            self.serianame = ''
            self.com = QSerialPort()
            self.cominfo = QSerialPortInfo()
            self.infos = self.cominfo.availablePorts()
            for info in self.infos:
                print("Name:", info.portName())
                print("vendoridentifier:", info.vendorIdentifier())

                # 串口信息认证
                if info.vendorIdentifier() == 6790:
                    self.serianame = info.portName()

            self.com.setPortName(self.serianame)
            self.com.setBaudRate(9600)
            ret = self.com.open(QSerialPort.ReadWrite)
            # 打开串口
            if ret == True:
                self.com.writeData(bytes(self.senddata, encoding='utf8'))
                print("senddata:", self.senddata)
            else:
                print("open fault")
        except Exception as e:
            print("Except", str(e))
Ejemplo n.º 23
0
    def displayGPSData(self,data):
        self.INS_GPS_data_text.setText(data)

    def writePort(self,data):
        if self.myPort.portOpen:
            try:
                if type(data) is str:
                    self.myPort.port.write(bytes(data+'\n\r', encoding='utf-8'))
                elif type(data) is list:
                    for cmd in data:
                        self.myPort.port.write(bytes(cmd + '\n\r', encoding='utf-8'))
                return True
            except:
                return False

        else:
            self.INS_GPS_message.setStatusMessage('端口未打开!','red','white')
            return None


if __name__ == '__main__':
    app = QApplication(sys.argv)
    portInfo=QSerialPortInfo()
    myWin=MyWindows()
    dark_stylesheet = qdarkstyle.load_stylesheet_pyqt5()
    app.setStyleSheet(dark_stylesheet)
    myWin.show()

    app.exec_()
    sys.exit(0)
Ejemplo n.º 24
0
        QSerialPort.SpaceParity,
        QSerialPort.MarkParity,
    ],
    'stop_bits': [
        QSerialPort.OneStop,
        QSerialPort.OneAndHalfStop,
        QSerialPort.TwoStop,
    ],
    'flow_control': [
        QSerialPort.NoFlowControl,
        QSerialPort.SoftwareControl,
        QSerialPort.HardwareControl,
    ],
}

for port_info in QSerialPortInfo().availablePorts():
    VALID_VALUES['port'].append(port_info.portName())


def is_valid_baud_rate(value):
    """
  Функция для проверки корректности значения baud_rate
  """
    if type(value) is str:
        try:
            value = int(value)
        except ValueError:
            return False

    return value > 0
Ejemplo n.º 25
0
    def receive_data(self):
        self.port_mes = QSerialPortInfo(
            self.SerialPort.port)  # 判断串口状态,若是则返回True,反之返回False
        self.serial_port_state = self.port_mes.isBusy()
        if self.serial_port_state == True:  # 再增加一个判断串口是否占用,若已占用,说明已打开成功
            res_data = self.SerialPort.read_all()
            info = []
            if len(res_data) != 0:
                print(str(res_data))
                print(str(res_data).__contains__('___'))
                if str(res_data).__contains__('___') == False:
                    return
                if (res_data != b'___(Ok)'):
                    for te in str(res_data).split(','):
                        if te.__contains__('('):
                            #                    print((te.split('(')[1]))
                            conum = te.split('(')[1]
                            t = 0
                            for c in conum:
                                if ord(c) < ord('A'):
                                    t = t * 16 + int(c)
                                elif ord(c) < ord('a'):
                                    t = t * 16 + int(ord(c) - ord('A') + 10)
                                else:
                                    t = t * 16 + int(ord(c) - ord('a') + 10)
    #                       print(t)
                            info.append(t)
                        elif te.__contains__(')'):
                            #                    print((te.split(')')[0]))
                            conum = te.split(')')[0]
                            t = 0
                            for c in conum:
                                if ord(c) < ord('A'):
                                    t = t * 16 + int(c)
                                elif ord(c) < ord('a'):
                                    t = t * 16 + int(ord(c) - ord('A') + 10)
                                else:
                                    t = t * 16 + int(ord(c) - ord('a') + 10)
                            info.append(t)
                        else:
                            #                    print((te))
                            t = 0
                            for c in te:
                                if ord(c) < ord('A'):
                                    t = t * 16 + int(c)
                                elif ord(c) < ord('a'):
                                    t = t * 16 + int(ord(c) - ord('A') + 10)
                                else:
                                    t = t * 16 + int(ord(c) - ord('a') + 10)
                            info.append(t)
                    print(info)
                    self.LineEdit_LoRa_Freq.setText(str(info[0]))
                    index = 0
                    for band in message_bandWidth_dict:
                        if (int(message_bandWidth_dict[band]) == int(
                                str(info[1]))):
                            if band != '':
                                self.ComboBox_BandWidth.setCurrentIndex(index)
                        index = index + 1
                    index = 0
                    for band in message_sprFactor_dict:
                        if (int(message_sprFactor_dict[band]) == int(
                                str(info[2]))):
                            if band != '':
                                self.ComboBox_SprFactor.setCurrentIndex(index)
                        index = index + 1
                    index = 0
                    for band in message_codingRate_dict:
                        if (int(message_codingRate_dict[band]) == int(
                                str(info[3]))):
                            if band != '':
                                self.ComboBox_CodingRate.setCurrentIndex(index)
                        index = index + 1
                    self.LineEdit_PowerCfig.setText(str(info[4]))
                    index = 0
                    for band in message_TrueOrFalse_dict:
                        if (int(message_TrueOrFalse_dict[band]) == int(
                                str(info[5]))):
                            if band != '':
                                self.ComboBox_MaxPowerOn.setCurrentIndex(index)
                        index = index + 1
                    index = 0
                    for band in message_TrueOrFalse_dict:
                        if (int(message_TrueOrFalse_dict[band]) == int(
                                str(info[6]))):
                            if band != '':
                                self.ComboBox_CRCON.setCurrentIndex(index)
                        index = index + 1
                    index = 0
                    for band in message_TrueOrFalse_dict:
                        if (int(message_TrueOrFalse_dict[band]) == int(
                                str(info[7]))):
                            if band != '':
                                self.ComboBox_HeaderOn.setCurrentIndex(index)
                        index = index + 1
                else:
                    # 通过setModal(bool)方法设置模态
                    #               window = QWidget()
                    qd = QDialog(MainWindow)
                    qd.resize(200, 100)
                    qd.setModal(True)

                    qd.Label = QtWidgets.QLabel(qd)
                    qd.Label.setGeometry(QtCore.QRect(40, 40, 100, 60))
                    qd.Label.setObjectName("Label")
                    qd.Label.setText("设置完成")
                    qd.Label.setFont(QFont("宋体", 12, QFont.Normal))
                    qd.Label.setAlignment(Qt.AlignRight)

                    qd.setWindowTitle("DE")
                    qd.show()
Ejemplo n.º 26
0
from PyQt5.QtSerialPort import QSerialPort, QSerialPortInfo
from PyQt5.QtCore import QIODevice
from pyqtgraph import PlotWidget
import pyqtgraph as pg
import sys

# https://stackoverflow.com/questions/35932660/qcombobox-click-event обновление по клику

app = QtWidgets.QApplication([])
ui = uic.loadUi("design.ui")
ui.setWindowTitle("SerialGUI")

serial = QSerialPort()
serial.setBaudRate(115200)
portList = []
ports = QSerialPortInfo().availablePorts()
for port in ports:
    portList.append(port.portName())
ui.comL.addItems(portList)

posX = 200
posY = 100
listX = []
for x in range(100): listX.append(x)
listY = []
for x in range(100): listY.append(0)


def onRead():
    if not serial.canReadLine(): return     # выходим если нечего читать
    rx = serial.readLine()
Ejemplo n.º 27
0
 def get_serial_ports(self):
     info_list = QSerialPortInfo()
     serial_list = info_list.availablePorts()
     return serial_list