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()
     }
Ejemplo n.º 2
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.º 3
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.º 4
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.º 5
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.º 6
0
def _get_index_of_first_matching_preferable_pattern(
        pi: QtSerialPort.QSerialPortInfo) -> typing.Optional[int]:
    for idx, (vendor_wildcard, product_wildcard
              ) in enumerate(_PREFERABLE_VENDOR_PRODUCT_PATTERNS):
        vendor_match = fnmatch.fnmatch(pi.manufacturer().lower(),
                                       vendor_wildcard.lower())
        product_match = fnmatch.fnmatch(pi.description().lower(),
                                        product_wildcard.lower())
        if vendor_match and product_match:
            return idx
Ejemplo n.º 7
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)
    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.º 9
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.º 10
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)
Ejemplo n.º 11
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.º 12
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.º 13
0
    def refreshCom(self):
        self.cmbPort.clear()
        for info in QSerialPortInfo.availablePorts():
            # self.com.setPort(info)
            self.cmbPort.addItem(info.portName())
        for info in QSerialPortInfo.standardBaudRates():
            self.cmbBaud.addItem(str(info))

        if (self.cmbBaud.findText('9600') != -1):
            self.cmbBaud.setCurrentIndex(self.cmbBaud.findText('9600'))
        elif (slef.cmbBaud.findText('19200') != -1):
            self.cmbBaud.setCurrentIndex(self.cmbBaud.findText('19200'))
        else:
            slef.cmbBaud.setCurrentIndex(0)
Ejemplo n.º 14
0
    def __init__(self, parent=None):
        super(PyClockSetup, self).__init__()

        self.serial = QSerialPort(self)
        uic.loadUi('pyclocksetup.ui', self)
        self.show()

        self.timer = QtCore.QTimer()
        self.timer.timeout.connect(self.updateTime)
        self.timer.start(1000)

        self.serial = QSerialPort(self)
        self.cp.colorChanged.connect(self.changeColor)
        self.connectButton.clicked.connect(self.serialConnect)
        self.setClockButton.clicked.connect(self.setClock)
        self.blinkingDots.toggled.connect(self.setBlinkingDots)
        self.leadingZero.toggled.connect(self.setLeadingZero)
        self.autoBrightness.toggled.connect(self.setAutoBrightness)
        self.segmentTest.toggled.connect(self.setSegmentTest)
        self.brightnessSlider.valueChanged.connect(self.changeBrightness)

        self.colorLabel.setStyleSheet('QLabel {background-color: #ffffff; }')

        availablePorts = QSerialPortInfo.availablePorts()
        for port in availablePorts:
            self.serialPorts.addItem(port.portName())
Ejemplo n.º 15
0
def getFoundDevices():
    """
    Function to check the serial ports for supported MicroPython devices.
    
    @return set of tuples with the board type, a description and the serial
        port it is connected at
    @rtype set of tuples of (str, str, str)
    """
    from PyQt5.QtSerialPort import QSerialPortInfo

    foundDevices = []

    availablePorts = QSerialPortInfo.availablePorts()
    for port in availablePorts:
        vid = port.vendorIdentifier()
        pid = port.productIdentifier()
        for board in SupportedBoards:
            if ((vid, pid) in SupportedBoards[board]["ids"]
                    or (vid, None) in SupportedBoards[board]["ids"]):
                foundDevices.append(
                    (board, SupportedBoards[board]["description"],
                     port.portName()))
                break
        else:
            logging.debug("Unknown device: (0x%04x:0x%04x)", vid, pid)

    return foundDevices
Ejemplo n.º 16
0
def main():
    import sys

    app = QCoreApplication(sys.argv)
    f = QFile()
    f.open(sys.stdout.fileno(), QIODevice.WriteOnly)
    out = QTextStream(f)
    serialPortInfos = QSerialPortInfo.availablePorts()

    out << "Total number of ports available: " << len(serialPortInfos) << "\n"

    blankString = "N/A"
    description = ""
    manufacturer = ""
    serialNumber = ""

    for serialPortInfo in serialPortInfos:
        description = serialPortInfo.description()
        manufacturer = serialPortInfo.manufacturer()
        serialNumber = serialPortInfo.serialNumber()
        out << "\nPort: " << serialPortInfo.portName(
        ) << "\nLocation: " << serialPortInfo.systemLocation(
        ) << "\nDescription: " << (
            description
            if description else blankString) << "\nManufacturer: " << (
                manufacturer if manufacturer else blankString
            ) << "\nSerial number: " << (
                serialNumber if serialNumber else blankString
            ) << "\nVendor Identifier: " << (
                QByteArray.number(serialPortInfo.vendorIdentifier(), 16)
                if serialPortInfo.hasVendorIdentifier() else blankString
            ) << "\nProduct Identifier: " << (
                QByteArray.number(serialPortInfo.productIdentifier(), 16) if
                serialPortInfo.hasProductIdentifier() else blankString) << "\n"
Ejemplo n.º 17
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.º 18
0
    def __init__(self, parent=None):
        super(SelectSerialportDialog, self).__init__(parent)
        self.setWindowModality(QtCore.Qt.ApplicationModal)
        self.setWindowTitle("Select a Port")
        
        self.resize(800, 200)

        self.portsList = QtWidgets.QTreeWidget()
        openButton = QtWidgets.QPushButton("Open")
        openButton.clicked.connect(self.openPort)

        layout = QtWidgets.QVBoxLayout()
        layout.addWidget(self.portsList)
        layout.addWidget(openButton)
        self.setLayout(layout)

        tableHeader = ["Name", "Alias", "Description", "Mfg", "Serial#", "Location", "VendorID", "ProductID"]
        self.portsList.setHeaderLabels(tableHeader)
        for info in QSerialPortInfo.availablePorts():
            list = []
            description = info.description()
            manufacturer = info.manufacturer()
            serialNumber = info.serialNumber()
            list.append(info.portName())
            list.append(self.serialPortAlias(info))
            list.append(self.naIfEmpty(description))
            list.append(self.naIfEmpty(manufacturer))
            list.append(self.naIfEmpty(serialNumber))
            list.append(info.systemLocation())
            list.append(self.naIfEmptyHex(info.vendorIdentifier()))
            list.append(self.naIfEmptyHex(info.productIdentifier()))

            self.portsList.addTopLevelItem(QtWidgets.QTreeWidgetItem(None, list))
        for i in range(0, len(tableHeader)):
            self.portsList.resizeColumnToContents(i)
Ejemplo n.º 19
0
def updateList():
    portList = []
    ports = QSerialPortInfo().availablePorts()
    for port in ports:
        portList.append(port.portName())
    ui.comL.clear()
    ui.comL.addItems(portList)
Ejemplo n.º 20
0
def main():
    import sys

    app = QApplication(sys.argv)

    layout = QVBoxLayout()

    infos = QSerialPortInfo.availablePorts()
    for info in infos:
        s = (
            f"Port: {info.portName()}",
            f"Location: {info.systemLocation()}",
            f"Description: {info.description()}",
            f"Manufacturer: {info.manufacturer()}",
            f"Serial number: {info.serialNumber()}",
            "Vendor Identifier: " + f"{info.vendorIdentifier():x}"
            if info.hasVendorIdentifier() else "",
            "Product Identifier: " + f"{info.productIdentifier():x}"
            if info.hasProductIdentifier() else "",
        )
        label = QLabel("\n".join(s))
        layout.addWidget(label)

    workPage = QWidget()
    workPage.setLayout(layout)

    area = QScrollArea()
    area.setWindowTitle("Info about all available serial ports.")
    area.setWidget(workPage)
    area.show()

    sys.exit(app.exec_())
Ejemplo n.º 21
0
	def portInit(self):
		for info in QSerialPortInfo.availablePorts():
			serialPort = QSerialPort()
			serialPort.setPort(info)
			if(serialPort.open(QIODevice.ReadWrite)):
				self.portNameBox.addItem(info.portName())
				serialPort.close()
Ejemplo n.º 22
0
    def __asyc_detect_new_device_handle(self, device_name):
        self.info.has_firmware = False
        self.info.board_id = None
        self.info.board_name = device_name
        available_ports = QSerialPortInfo.availablePorts()

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

        for port in available_ports:
            pvid = (
                port.vendorIdentifier(),
                port.productIdentifier()
            )
            if match(pvid, self.info.board_normal):
                self.invoke.in_bootload_mode = False
                print('detect a normal mode borad')
                break
            if match(pvid, self.info.board_boot):
                self.invoke.in_bootload_mode = True
                print('detect a bootload mode borad')
                break

        self.invoke.detected = True
Ejemplo n.º 23
0
 def find_device(self, with_logging=True):
     """
     Returns the port and serial number for the first MicroPython-ish device
     found connected to the host computer. If no device is found, returns
     the tuple (None, None).
     """
     available_ports = QSerialPortInfo.availablePorts()
     for port in available_ports:
         pid = port.productIdentifier()
         vid = port.vendorIdentifier()
         # Look for the port VID & PID in the list of know board IDs
         if (vid, pid) in self.valid_boards or \
            (vid, None) in self.valid_boards:
             port_name = port.portName()
             serial_number = port.serialNumber()
             if with_logging:
                 logger.info('Found device on port: {}'.format(port_name))
                 logger.info('Serial number: {}'.format(serial_number))
             return (self.port_path(port_name), serial_number)
     if with_logging:
         logger.warning('Could not find device.')
         logger.debug('Available ports:')
         logger.debug([
             'PID:0x{:04x} VID:0x{:04x} PORT:{}'.format(
                 p.productIdentifier(), p.vendorIdentifier(), p.portName())
             for p in available_ports
         ])
     return (None, None)
Ejemplo n.º 24
0
    def on_respiration_monitor_button_pressed(self):
        arduino = self.dependencies.arduino

        # DEBUG FFT
        # self.fft_timer = QTimer()
        # self.fft_timer.timeout.connect(self.debug_fft)
        # self.random_time = 0
        # self.fft_timer.start(50)

        if arduino.is_open():
            arduino.close()
            self.arduino_status_label.setText("Arduino Off")
            arduino.newDataReceived.disconnect(self.temp_func)
            arduino.stop()

        else:
            ports = QSerialPortInfo.availablePorts()
            for port in ports:
                if "Arduino" in port.description():
                    self.respiration_widget.reset()
                    arduino.port = port.portName()
                    arduino.open()
                    self.arduino_status_label.setText("Arduino On ({})".format(port.portName()))
                    self.dependencies.arduino.newDataReceived.connect(self.temp_func)
                    self.dependencies.arduino.start()
                    break
Ejemplo n.º 25
0
Archivo: base.py Proyecto: Naf3tS/mu
 def find_devices(self, with_logging=True):
     """
     Returns the port and serial number, and name for the first
     MicroPython-ish device found connected to the host computer.
     If no device is found, returns the tuple (None, None, None).
     """
     available_ports = QSerialPortInfo.availablePorts()
     devices = []
     for port in available_ports:
         device = self.compatible_board(port)
         if device:
             # On OS X devices show up with two different port
             # numbers (/dev/tty.usbserial-xxx and
             # /dev/cu.usbserial-xxx) we only want to display the
             # ones on ports names /dev/cu.usbserial-xxx to users
             if sys.platform == "darwin" and device.port[:7] != "/dev/cu":
                 continue
             if with_logging:
                 logger.info("Found device on port: {}".format(device.port))
                 logger.info("Serial number: {}".format(
                     device.serial_number))
                 if device.board_name:
                     logger.info("Board type: {}".format(device.board_name))
             devices.append(device)
     if not devices and with_logging:
         logger.warning("Could not find device.")
         logger.debug("Available ports:")
         logger.debug([
             "PID:0x{:04x} VID:0x{:04x} PORT:{}".format(
                 p.productIdentifier(),
                 p.vendorIdentifier(),
                 p.portName(),
             ) for p in available_ports
         ])
     return devices
Ejemplo n.º 26
0
 def __init__(self):
     super(SerialProtoParser, self).__init__()
     # Serial port
     self.__serialPort = QSerialPort()
     # Setup Serialport
     # We are using USB serial driver, so the baud rate doesn't matter
     self.__serialPort.setBaudRate(QSerialPort.Baud115200,
                                   QSerialPort.Input)
     self.destroyed.connect(self.close)
     # Get the list of all available serial ports
     portsList = QSerialPortInfo.availablePorts()
     # Only connect to Chibios port
     chibiOsPort = None
     for port in portsList:
         if ("ChibiOS" in port.description()):
             chibiOsPort = port
     if (chibiOsPort is None):
         print("Cannot find chibios based device")
     else:
         # Set the serial port
         self.__serialPort.setPort(chibiOsPort)
         self.__serialPort.setDataBits(QSerialPort.Data8)
         self.__serialPort.setFlowControl(QSerialPort.NoFlowControl)
         self.__serialPort.setParity(QSerialPort.NoParity)
         self.__serialPort.setStopBits(QSerialPort.OneStop)
         # Connect signals and slots
         self.__serialPort.readyRead.connect(self.__onSerialPortReadyRead)
         # Open the device
         self.__serialPort.open(QIODevice.ReadOnly)
Ejemplo n.º 27
0
 def findPorts(self):
     port_list = QSerialPortInfo.availablePorts()
     port_list_names = []
     self.PortSelector.clear()
     for port in port_list:
         port_list_names.append(port.portName())
     self.PortSelector.addItems(port_list_names)
Ejemplo n.º 28
0
    def setComboBox(self):
        modes = ['TCP', 'RTU']
        for mode in modes:
            self.ui.mode_comboBox.insertItem(0, mode)
        self.ui.mode_comboBox.setCurrentIndex(0)

        port_list = QSerialPortInfo.availablePorts()
        for port in port_list:
            self.ui.port_comboBox.insertItem(0, port.portName())

        baudrates = ['300', '1200', '2400', '9600', '19200', '115200']
        for baudrate in baudrates:
            self.ui.baudrate_comboBox.insertItem(0, baudrate)
        self.ui.baudrate_comboBox.setCurrentIndex(2)

        data_bits = ['5', '6', '7', '8']
        for bit in data_bits:
            self.ui.dataBits_comboBox.insertItem(0, bit)
        self.ui.dataBits_comboBox.setCurrentIndex(0)

        stop_bits = ['1', '1.5', '2']
        for bit in stop_bits:
            self.ui.stopBits_comboBox.insertItem(0, bit)
        self.ui.stopBits_comboBox.setCurrentIndex(0)

        paritys = ['N', 'EVEN', 'ODD', 'MARK', 'SPACE']
        for parity in paritys:
            self.ui.parity_comboBox.insertItem(0, parity)
        self.ui.parity_comboBox.setCurrentIndex(4)

        slave_id = ['1', '2', '3']
        for id in slave_id:
            self.ui.slaveID_comboBox.insertItem(0, id)
        self.ui.slaveID_comboBox.setCurrentIndex(2)
Ejemplo n.º 29
0
    def __init__(self, parent=None):
        super().__init__(parent)

        self.__data = QByteArray()
        self.__serial = QSerialPort()
        self.__timer = QTimer(self)

        for info in QSerialPortInfo.availablePorts():
            if info.description() == "USB-SERIAL CH340":
                self.__serial = QSerialPort(info)
                print(self.__serial.portName())
                break

        self.__serial.readyRead.connect(self.__read_data)
        self.__timer.timeout.connect(self.__timer_update_com)

        self.__temperature = 0
        self.__humidity = 0
        self.__co2 = 0
        self.__tvoc = 0
        self.__pm25 = 0
        self.__pm10 = 0
        self.__o2 = 0

        if self.__serial.open(QIODevice.ReadWrite):
            print("open success")
        else:
            print("open fail")
        self.__auto_save_thread = AutoSave(self)
        self.__auto_save_thread.start()
Ejemplo n.º 30
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.º 31
0
Archivo: logic.py Proyecto: stestagg/mu
def find_microbit():
    """
    Returns the port for the first microbit it finds connected to the host
    computer. If no microbit is found, returns None.
    """
    available_ports = QSerialPortInfo.availablePorts()
    for port in available_ports:
        pid = port.productIdentifier()
        vid = port.vendorIdentifier()
        if pid == MICROBIT_PID and vid == MICROBIT_VID:
            return port.portName()
    return None
Ejemplo n.º 32
0
Archivo: logic.py Proyecto: ntoll/mu
def find_microbit():
    """
    Returns the port for the first microbit it finds connected to the host
    computer. If no microbit is found, returns None.
    """
    available_ports = QSerialPortInfo.availablePorts()
    for port in available_ports:
        pid = port.productIdentifier()
        vid = port.vendorIdentifier()
        if pid == MICROBIT_PID and vid == MICROBIT_VID:
            port_name = port.portName()
            logger.info('Found micro:bit with portName: {}'.format(port_name))
            return port_name
    logger.warning('Could not find micro:bit.')
    logger.debug('Available ports:')
    logger.debug(['PID:{} VID:{} PORT:{}'.format(p.productIdentifier(),
                                                 p.vendorIdentifier(),
                                                 p.portName())
                 for p in available_ports])
    return None
Ejemplo n.º 33
0
def find_microbit():
    """
    Returns the port for the first microbit it finds connected to the host
    computer. If no microbit is found, returns None.
    """
    available_ports = QSerialPortInfo.availablePorts()
    for port in available_ports:
        pid = port.productIdentifier()
        vid = port.vendorIdentifier()
        # Look for the port VID & PID in the list of known board IDs.
        if (vid, pid) in BOARD_IDS:
            port_name = port.portName()
            logger.info('Found micro:bit with portName: {}'.format(port_name))
            return port_name
    logger.warning('Could not find micro:bit.')
    logger.debug('Available ports:')
    logger.debug(['PID:{} VID:{} PORT:{}'.format(p.productIdentifier(),
                                                 p.vendorIdentifier(),
                                                 p.portName())
                 for p in available_ports])
    return None
Ejemplo n.º 34
-1
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.º 35
-1
 def find_device(self, with_logging=True):
     """
     Returns the port and serial number for the first MicroPython-ish device
     found connected to the host computer. If no device is found, returns
     the tuple (None, None).
     """
     available_ports = QSerialPortInfo.availablePorts()
     for port in available_ports:
         pid = port.productIdentifier()
         vid = port.vendorIdentifier()
         # Look for the port VID & PID in the list of know board IDs
         if (vid, pid) in self.valid_boards:
             port_name = port.portName()
             serial_number = port.serialNumber()
             if with_logging:
                 logger.info('Found device on port: {}'.format(port_name))
                 logger.info('Serial number: {}'.format(serial_number))
             return (self.port_path(port_name), serial_number)
     if with_logging:
         logger.warning('Could not find device.')
         logger.debug('Available ports:')
         logger.debug(['PID:{} VID:{} PORT:{}'.format(p.productIdentifier(),
                                                      p.vendorIdentifier(),
                                                      p.portName())
                      for p in available_ports])
     return (None, None)