Ejemplo n.º 1
0
def get_usbs():
    '''Query the machine for the weight sensor style usbs plugged in.
    Each weight sensor uses a set of four consecutive usbs. We return
    a list of the first in each set
    @return starting_ports The first usb for each sensor'''
    if platform.linux_distribution()[1] == '14.04':
        iterator = numpy.array(comports())[:, 1]
    else:
        iterator = [i.name for i in comports()]
    usbstring = 'ttyUSB'
    port_names = [i for i in iterator if i.startswith(usbstring)]
    port_numbers = sorted([int(p.lstrip(usbstring)) for p in port_names])
    starting_ports = [f for f in port_numbers if f % 4 == 0]
    return starting_ports
Ejemplo n.º 2
0
 def execute(self, args):
     devices = sorted(comports(include_links=args.symlinks))
     return [
         f'{port}' + (f'\n   ID={hwid}: {desc}' if args.verbose else '')
         for entry, (port, desc, hwid) in enumerate(devices, 1)
         if args.entry is None or args.entry == entry
     ]
def grep(regexp, include_links=False):
    """\
    Search for ports using a regular expression. Port name, description and
    hardware ID are searched. The function returns an iterable that returns the
    same tuples as comport() would do.
    """
    r = re.compile(regexp, re.I)
    for info in comports(include_links):
        port, desc, hwid = info
        if r.search(port) or r.search(desc) or r.search(hwid):
            yield info
def main():
    import argparse

    parser = argparse.ArgumentParser(description='Serial port enumeration')

    parser.add_argument('regexp',
                        nargs='?',
                        help='only show ports that match this regex')

    parser.add_argument('-v',
                        '--verbose',
                        action='store_true',
                        help='show more messages')

    parser.add_argument('-q',
                        '--quiet',
                        action='store_true',
                        help='suppress all messages')

    parser.add_argument('-n', type=int, help='only output the N-th entry')

    parser.add_argument(
        '-s',
        '--include-links',
        action='store_true',
        help='include entries that are symlinks to real devices')

    args = parser.parse_args()

    hits = 0
    # get iteraror w/ or w/o filter
    if args.regexp:
        if not args.quiet:
            sys.stderr.write("Filtered list with regexp: {!r}\n".format(
                args.regexp))
        iterator = sorted(grep(args.regexp, include_links=args.include_links))
    else:
        iterator = sorted(comports(include_links=args.include_links))
    # list them
    for n, (port, desc, hwid) in enumerate(iterator, 1):
        if args.n is None or args.n == n:
            sys.stdout.write("{:20}\n".format(port))
            if args.verbose:
                sys.stdout.write("    desc: {}\n".format(desc))
                sys.stdout.write("    hwid: {}\n".format(hwid))
        hits += 1
    if not args.quiet:
        if hits:
            sys.stderr.write("{} ports found\n".format(hits))
        else:
            sys.stderr.write("no ports found\n")
Ejemplo n.º 5
0
def arduino_comports():
    """
    List of serial comports serial numbers of Arduino boards connected to this machine
    :return: generator of comports connected to arduino
    """
    #for comport in arduino_comports():
    #    comport.serial_number # '55639303235351C071B0'
    #    comport.device # '/def/ttyACM0'
    from serial.tools.list_ports_posix import comports

    arduino_manufacturer_regex = re.compile(
        r'arduino',
        re.IGNORECASE)  # simple, because I've only got one to test on
    for comport in comports():
        if comport.manufacturer:
            match = arduino_manufacturer_regex.search(comport.manufacturer)
            if match:
                yield comport
Ejemplo n.º 6
0
def get_port_name():
    ''' Displays information to terminal to led the user select the comport (Arduino USB connection)'''
    cps = comports()
    print('Printing devices available.')
    if len(cps) == 0:
        print('Error: Seems empty ...')
        print('Exiting...')
        exit()
    for cp, i in enumerate(cps):
        print(str(i) + ')', cp)
    print('Select the device.\n>', end='')
    us = input()
    device = 0
    if us != '':
        try:
            device = int(us)
        except:
            print('Not a number, selecting ', device, cps[device].device)
    return cps[device].device
Ejemplo n.º 7
0
    def connect(self):

        self.disconnect()

        device = None
        for port, _, hwid in comports():
            if re.search(r"0403:6001", hwid):
                device = port
                break

        if device:
            try:
                self.plm = serial.Serial(
                    port=device,
                    baudrate=self.IMParms['IM_BAUDRATE'],
                    timeout=self.IMParms['IM_CMD_TIMEOUT'])
            except serial.SerialException:  # TODO: convert each exception to a log write
                print('  --> Failed to open serial port')
                self.plm = None
            except OSError:
                print('  --> Unable to access serial port')
                self.plm = None

            response = self.send_command('GET_VERSION')
            if response:
                print(
                    f"Insteon PLM ID= {response['id1']}.{response['id2']}.{response['id3']}: ",
                    end='')
                print(
                    f"device category={response['dev_cat']}, subcategory={response['dev_subcat']}, firmware version={response['firm_ver']}"
                )
            else:
                print('  --> failed to send IM command to serial port')
                self.plm.close()
                self.plm = None  # assume not a PLM on this port

        if not self.plm:
            raise InsteonPLMConfigError(
                'Could not find a PLM attached to a USB port')
Ejemplo n.º 8
0
    def setupUi(self, mainWindow, dataBack):
        self.dataBack = dataBack
#############################
## Layout code
#############################
        mainWindow.setObjectName("mainindow")
        #mainWindow.resize(659, 565)
        #mainWindow.setWindowTitle("CAN Message Viewer")
        self.centralWidget = QtWidgets.QWidget(mainWindow)
        self.centralWidget.setObjectName("centralWidget")
        self.horizontalLayout = QtWidgets.QHBoxLayout(self.centralWidget)
        self.horizontalLayout.setObjectName("horizontalLayout")

        self.messagesFrame = QtWidgets.QFrame(self.centralWidget)
        self.messagesFrame.setFrameShape(QtWidgets.QFrame.StyledPanel)
        self.messagesFrame.setFrameShadow(QtWidgets.QFrame.Raised)
        self.messagesFrame.setObjectName("messagesFrame")
        self.messagesFrame.setMinimumWidth(400)
        self.messagesFrame.setSizePolicy(QtWidgets.QSizePolicy.Fixed,
                                         QtWidgets.QSizePolicy.Expanding)

        self.verticalLayout_2 = QtWidgets.QVBoxLayout(self.messagesFrame)
        self.verticalLayout_2.setObjectName("verticalLayout_2")
        self.label = QtWidgets.QLabel(self.messagesFrame)
        self.label.setObjectName("messageStreamLabel")
#        self.label.setText("Message Stream")
        self.verticalLayout_2.addWidget(self.label)


#########################
# Display Combobox code # (not finished)
#########################
        self.displayLayout = QtWidgets.QHBoxLayout()
        self.verticalLayout_2.addLayout(self.displayLayout)
        self.displayLayout.setObjectName("display combobox layout")
        self.displayLabel = QtWidgets.QLabel()
        self.displayLabel.setText("Display: ")
        self.displayCombo = QtWidgets.QComboBox()
        self.displayLayout.addWidget(self.displayLabel)
        self.displayLayout.addWidget(self.displayCombo)
        displayList = ["Decoded", "Raw hex", "CSV"]
        self.displayCombo.addItems(displayList)


        self.messagesTextBrowser = QtWidgets.QTextBrowser(self.messagesFrame)
        self.messagesTextBrowser.setObjectName("messagesTextBrowser")
        self.verticalLayout_2.addWidget(self.messagesTextBrowser)



##################
# buttonsGrid code
##################
        # Buttons for clearing textbrowser, csv, pgn, body, raw display,
        # and saving textbrowser contents to file.
        self.buttonsGrid = QtWidgets.QGridLayout()
        self.verticalLayout_2.addLayout(self.buttonsGrid)
        self.buttonsGrid.setObjectName("button grid layout")

        self.buttonClear = QtWidgets.QPushButton()
        self.buttonClear.setObjectName("clear")
        self.buttonClear.setText("Clear Message Stream")
        self.buttonClear.clicked.connect(self.clearTextBrowser)
        self.logLabel = QtWidgets.QLabel()
        self.logLabel.setText("Enter filename:")
        self.buttonLogging = QtWidgets.QPushButton()
        self.buttonLogging.setObjectName("save")
        self.buttonLogging.setText("Begin Logging")
        self.buttonLogging.clicked.connect(self.saveToFile)
        self.logLabel.setBuddy(self.buttonLogging)
        self.fileName = QtWidgets.QLineEdit()
        self.fileName.setObjectName("fileName")
        self.fileName.returnPressed.connect(self.saveToFile)

        self.checkBody = QtWidgets.QCheckBox()
        self.checkBody.setObjectName("checkBoxBody")
        self.checkBody.setText("Body")
        self.checkBody.setCheckState(2)
        self.checkBody.stateChanged.connect(self.setOutput)
        self.checkPGN = QtWidgets.QCheckBox()
        self.checkPGN.setObjectName("checkBoxPGN")
        self.checkPGN.setText("PGN")
        self.checkPGN.setCheckState(2)
        self.checkPGN.stateChanged.connect(self.setOutput)
        self.checkID = QtWidgets.QCheckBox()
        self.checkID.setObjectName("checkBoxId")
        self.checkID.setText("ID")
        self.checkID.setCheckState(2)
        self.checkID.stateChanged.connect(self.setOutput)
        self.checkRaw = QtWidgets.QCheckBox()
        self.checkRaw.setObjectName("checkBoxRaw")
        self.checkRaw.setText("Hex")
        self.checkRaw.stateChanged.connect(self.setOutput)

        self.checkCSV = QtWidgets.QCheckBox()
        self.checkCSV.setObjectName("checkBoxCSV")
        self.checkCSV.setText("CSV")
        self.checkCSV.stateChanged.connect(self.setOutput)
        self.checkCSV.stateChanged.connect(self.csvOutputSet)
        self.displayLabel = QtWidgets.QLabel()
        self.displayLabel.setText("Display opts:")

        self.displayCheckBox = QtWidgets.QHBoxLayout()
        self.displayCheckBox.addWidget(self.displayLabel)
        self.displayCheckBox.addWidget(self.checkBody)
        self.displayCheckBox.addWidget(self.checkPGN)
        self.displayCheckBox.addWidget(self.checkID)
        self.displayCheckBox.addWidget(self.checkRaw)
        self.displayCheckBox.addWidget(self.checkCSV)

        if self.dataBack.args.debug:
            self.debug = QtWidgets.QPushButton()
            self.debug.setText("pdb")
            self.debug.clicked.connect(self.debugMode)


        #self.buttonResetTime.clicked.connect(self.resetTime)
        self.buttonsGrid.addWidget(self.logLabel, 1,0)
#        self.buttonsGrid.addWidget(self.buttonClear, 0,0)
        self.buttonsGrid.addWidget(self.buttonLogging, 0,0, 1,3)
        self.buttonsGrid.addWidget(self.fileName, 1,2)
        self.buttonsGrid.addLayout(self.displayCheckBox, 2,0, 1,3)
#        self.buttonsGrid.addWidget(self.checkCSV, 3,0)
        #self.buttonsGrid.addWidget(self.buttonResetTime, 2,1, 1,2)
        if self.dataBack.args.debug:
            self.buttonsGrid.addWidget(self.debug, 3,1, 1,2)
##################
# End of buttonsGrid code
##################

        self.horizontalLayout.addWidget(self.messagesFrame)
        self.visualizeFrame = QtWidgets.QFrame(self.centralWidget)
        self.visualizeFrame.setFrameShape(QtWidgets.QFrame.StyledPanel)
        self.visualizeFrame.setFrameShadow(QtWidgets.QFrame.Raised)
        self.visualizeFrame.setObjectName("visualizeFrame")
        self.visualizeFrame.setMinimumWidth(555)
        self.visualizeFrame.setSizePolicy(QtWidgets.QSizePolicy.Expanding,
                                          QtWidgets.QSizePolicy.Expanding)

        self.verticalLayout = QtWidgets.QVBoxLayout(self.visualizeFrame)
        self.verticalLayout.setObjectName("verticalLayout")
        self.label_2 = QtWidgets.QLabel(self.visualizeFrame)
        self.label_2.setObjectName("label_2")
#        self.label_2.setText("Metadata and Filtering")
        self.verticalLayout.addWidget(self.label_2)

#################
# TabWidget, tableWidget, and treeWidget code
#################
        self.tabWidget = QtWidgets.QTabWidget(self.visualizeFrame)
        self.tabWidget.setObjectName("tabWidget")
        self.filterTab = QtWidgets.QWidget()
        self.filterTab.setObjectName("filterTab")
      #  self.verticalLayout_3 = QtWidgets.QVBoxLayout(self.filterTab)
      #  self.verticalLayout_3.setObjectName("verticalLayout_3")
#        self.progressBar = QtWidgets.QProgressBar(self.treeViewTab)
#        self.progressBar.setProperty("value", 24)
#        self.progressBar.setObjectName("progressBar")
#        self.verticalLayout_3.addWidget(self.progressBar)
        self.filterTable = filterTable.FilterTable()
        self.filterTable.setup(self.dataBack, self)
        self.filterTable.setObjectName("filterTable")
        self.filterTable.populateTable()
        self.treeWidgetTab = QtWidgets.QWidget()
        self.treeWidgetTab.setObjectName("treeWidgetTab")
       # self.verticalLayout_4 = QtWidgets.QVBoxLayout(self.treeWidgetTab)
       # self.verticalLayout_4.setObjectName("verticalLayout_4")
        self.filtersTreeWidget = filtersTreeWidget.FiltersTreeWidget()
        self.filtersTreeWidget.setup(self, self.dataBack)
       # self.verticalLayout_4.addWidget(self.filtersTreeWidget)
        self.tabWidget.addTab(self.filterTable, "")
        self.tabWidget.addTab(self.filtersTreeWidget, "")
        self.verticalLayout.addWidget(self.tabWidget)
        self.horizontalLayout.addWidget(self.visualizeFrame)
        mainWindow.setCentralWidget(self.centralWidget)

#############################
## Menu code
#############################
        self.menuBar = QtWidgets.QMenuBar(mainWindow)
        self.menuBar.setGeometry(QtCore.QRect(0, 0, 659, 20))
        self.menuBar.setObjectName("menuBar")
        self.menuShow = QtWidgets.QMenu(self.menuBar)
        self.menuShow.setObjectName("menuShow")
        self.menuChoose_port = QtWidgets.QMenu(self.menuShow)
        self.menuChoose_port.setObjectName("menuChoose_port")
        mainWindow.setMenuBar(self.menuBar)
        self.actionBegin_Logging = QtWidgets.QAction(mainWindow)
        self.actionBegin_Logging.setObjectName("actionBegin_Logging")
        self.actionEnd_Logging = QtWidgets.QAction(mainWindow)
        self.actionEnd_Logging.setObjectName("actionEnd_Logging")
        self.actionCAN_Messages = QtWidgets.QAction(mainWindow)
        self.actionCAN_Messages.setObjectName("actionCAN_Messages")
        self.actionCAN_Headers = QtWidgets.QAction(mainWindow)
        self.actionCAN_Headers.setObjectName("actionCAN_Headers")
        self.actionCAN_PGNs = QtWidgets.QAction(mainWindow)
        self.actionCAN_PGNs.setObjectName("actionCAN_PGNs")
        self.actionLoad_filters_from_file = QtWidgets.QAction(mainWindow)
        self.actionLoad_filters_from_file.setObjectName(
                                        "actionLoad_filters_from_file")
        self.actionLoad_filters_from_file.triggered.connect(self.newLoadFilter)
        self.actionComports = QtWidgets.QAction(mainWindow)
        self.actionComports.setObjectName("actionComports")
        # comports code:
        ##########
        self.menuChoose_port.addAction(self.actionComports)
        for port in comports():
            #pyqtrm()
            #pdb.set_trace()
            _port = QtWidgets.QAction(port[0], mainWindow)
            self.menuChoose_port.addAction(_port)
            _port.triggered.connect(self.comportSelect)
        ##########
        self.actionTab1 = QtWidgets.QAction(mainWindow)
        self.actionTab1.setObjectName("actionTab1")
        self.actionTab2 = QtWidgets.QAction(mainWindow)
        self.actionTab2.setObjectName("actionTab2")
        self.menuShow.addAction(self.actionCAN_Messages)
        self.menuShow.addAction(self.actionCAN_Headers)
        self.menuShow.addAction(self.actionCAN_PGNs)
        self.menuShow.addSeparator()
        self.menuShow.addAction(self.actionLoad_filters_from_file)
        self.menuShow.addAction(self.menuChoose_port.menuAction())
        self.menuBar.addAction(self.menuShow.menuAction())
        # QtDesigner code:
        self.retranslateUi(mainWindow)
        self.tabWidget.setCurrentIndex(0)
        QtCore.QMetaObject.connectSlotsByName(mainWindow)
Ejemplo n.º 9
0
def get_mcu_virturl_com():
    iterator = sorted(comports())
    for n, (port, desc, hwid) in enumerate(iterator, 1):
        if MCU_VIRTUAL_COM_FLAG in desc:
            return os.path.basename(port)
    return None
Ejemplo n.º 10
0
"""
Test code to control a DigitalVFO device using the serial USB port.

Also demonstrates identifying USB devices.
"""

import sys
import serial
import time
from serial.tools.list_ports_posix import comports

iterator = comports()
teensy_devices = []
cursor_index = 0
cursor_sign = +1

for i in comports():
    if i.description == 'USB Serial' and i.manufacturer == 'Teensyduino':
        # we have a Teensy!
        teensy_devices.append(i.device)

if len(teensy_devices) == 1:
    # open serial device
    ser = serial.Serial(teensy_devices[0])  # open serial port
    print(f'Opening device {ser.name}')

    # make sure it's a DigitalVFO device
    cmd = f'ID;'.encode('latin-1')
    ser.write(cmd)  # get the ID string
    answer = ser.readline().decode("utf-8")
    if not answer.startswith('DigitalVFO'):