Exemplo n.º 1
0
def main():
    si_ports = [port for port in list_ports.grep("sportident.*")]
    logger.info("Opening SI readers on ports %s" %
                ([si_port.device for si_port in si_ports]))
    punch_readers = [SIPunchReader(si_port.device) for si_port in si_ports]

    xbee_ports = [port for port in list_ports.grep("0403:6015")]
    if not xbee_ports:
        raise Exception("No X-Bee radio found.")
    xbee_port = xbee_ports.pop()
    logger.info("Opening writer on port %s" % (xbee_port))
    punch_writer = XBeeWriter(xbee_port.device)

    mysel = selectors.DefaultSelector()
    for punch_reader in punch_readers:
        mysel.register(punch_reader._serial, selectors.EVENT_READ,
                       punch_reader)

    while True:
        try:
            for key, mask in mysel.select(timeout=None):
                punch_reader = key.data
                #logger.info("#### reader %s" % (punch_reader))
                cmd, raw_data = punch_reader.readCommand()
                if cmd == SIReader.C_TRANS_REC:
                    #logger.info("==>> Sending punch %s" % (' '.join([hexlify(int2byte(c)).decode('ascii') for c in raw_data])))
                    logger.info("==>> Sending punch %s" % (hexlify(raw_data)))
                    punch_writer.send(raw_data)
        except SIReaderTimeout:
            pass
        except KeyboardInterrupt:
            for punch_reader in punch_readers:
                punch_reader.disconnect()
            punch_writer.disconnect()
            break
Exemplo n.º 2
0
def main():  
	si_ports = [ port for port in list_ports.grep("sportident.*") ]
	logger.info("Opening SI readers on ports %s" % ([si_port.device for si_port in si_ports]))
	punch_readers = [SIPunchReader(si_port.device) for si_port in si_ports]
	
	xbee_ports = [ port for port in list_ports.grep("0403:6015") ]
	if not xbee_ports:
		raise Exception("No X-Bee radio found.")
	xbee_port = xbee_ports.pop()
	logger.info("Opening writer on port %s" % (xbee_port))
	punch_writer = XBeeWriter(xbee_port.device)


	mysel = selectors.DefaultSelector()
	for punch_reader in punch_readers:
		mysel.register(punch_reader._serial, selectors.EVENT_READ, punch_reader)


	while True:
		try:
			for key, mask in mysel.select(timeout = None):
				punch_reader = key.data
				#logger.info("#### reader %s" % (punch_reader))
				cmd, raw_data = punch_reader.readCommand()
				if cmd == SIReader.C_TRANS_REC:
					#logger.info("==>> Sending punch %s" % (' '.join([hexlify(int2byte(c)).decode('ascii') for c in raw_data])))
					logger.info("==>> Sending punch %s" % (hexlify(raw_data)))
					punch_writer.send(raw_data)
		except SIReaderTimeout:
			pass
		except KeyboardInterrupt:
			for punch_reader in punch_readers:
				punch_reader.disconnect()
			punch_writer.disconnect()
			break
Exemplo n.º 3
0
def open_usb():
    # ポート番号を取得する
    SERIAL_PORT = ""

    if sys.platform == "linux" or sys.platform == "linux2":
        matched_ports = list_ports.grep("ttyUSB")
    elif sys.platform == "darwin":
        matched_ports = list_ports.grep("cu.usbserial-")

    for match_tuple in matched_ports:
        SERIAL_PORT = match_tuple[0]
        break

    if SERIAL_PORT == "":
        return None

    try:
        device = serial.Serial(SERIAL_PORT, 921600, timeout=1, writeTimeout=30)
    except:
        return None

    # コマンドモードに変更
    device.write(chr(0x13))

    return device
Exemplo n.º 4
0
    def detect_charger_port():
        ports = [port[0] for port in list_ports.grep('2341:8037')]
        if ports:
            return ports[0]

        ports = [port[0] for port in list_ports.grep('0403:6001')]
        return ports[0] if ports else None
Exemplo n.º 5
0
    def detect_charger_port():
        ports = [port[0] for port in list_ports.grep('2341:8037')]
        if ports:
            return ports[0]

        ports = [port[0] for port in list_ports.grep('0403:6001')]
        return ports[0] if ports else None
Exemplo n.º 6
0
def findPort():
    global main_port
    ports = grep("usb")
    ports = list(ports)
    if (len(ports) == 0):
        ports = grep("COM")
        ports = list(ports)
    main_port = ports[0].device
    return ports[0].device
Exemplo n.º 7
0
def get_ports():
    """Get available serial connections"""
    serial_ports = []
    if os.name == 'nt':
        serial_ports = list(grep(r'COM*'))
    elif os.name == 'posix':
        serial_ports = list(grep(r'USB*'))

    return [p.device for p in serial_ports]
Exemplo n.º 8
0
def main():
    #2067939 [ d3 0d 00 7b 00 1f 8d e3 05 86 76 6d 00 01 00 ]
    #4634    [ d3 0d 00 7b 00 00 12 1a 05 86 85 32 00 01 08 ]

    SportIdentVID = '10c4'
    ArduinoVID = '2341'
    XBeeVID = '0403'
    si_devices = [
        port[0] if isinstance(port, tuple) else port.device
        for port in list_ports.grep(SportIdentVID + ':.*')
    ]
    si_devices += [
        port[0] if isinstance(port, tuple) else port.device
        for port in list_ports.grep(ArduinoVID + ':.*')
    ]
    logger.info("SI readers: %s" % si_devices)
    if len(si_devices) == 0:
        logger.info([port.hwid for port in list_ports.grep('.*')])
        raise Exception("No SI devices found!")

    xbee_devices = [
        port[0] if isinstance(port, tuple) else port.device
        for port in list_ports.grep(XBeeVID + ':.*')
    ]
    if len(xbee_devices) == 0:
        raise Exception("No XBee device found!")
    xbee_device = xbee_devices.pop()
    logger.info("XBee writer: %s" % xbee_device)

    si_readers = [SIPunchReader(device) for device in si_devices]
    xbee_writer = XBeeWriter(xbee_device)

    rdfs = [dev._serial for dev in si_readers]
    try:
        while True:
            logger.info("select ...")
            readable, writable, exceptional = select.select(rdfs, [], [], 5)
            if not readable:
                logger.info("timeout")
            else:
                for r in readable:
                    for si in si_readers:
                        #pudb.set_trace()
                        if si._serial == r:
                            cmd, data = si.readCommand()
                            logger.info("<<== Data read %s" % (hexlify(data)))
                            if cmd == SIReader.C_TRANS_REC:
                                logger.info("==>> Sending punch %s" %
                                            (hexlify(data)))
                                xbee_writer.send(data)
    except Exception as e:
        for rd in si_readers:
            rd.disconnect()
        xbee_writer.disconnect()
        raise e
Exemplo n.º 9
0
 def __init__(self,
              serial_number=None,
              device=None,
              timeout=0,
              *args,
              **kwargs):
     log.info("serial_number=%s device=%s timeout=%s args=%s kwargs=%s",
              serial_number, device, timeout, args, kwargs)
     self.serial = Serial(*args, **kwargs)
     self.serial.baudrate = 115200
     self.serial.timeout = timeout
     self.serial.port = None
     if serial_number:
         ports = list(list_ports.grep(serial_number))
         if ports:
             self.serial.port = ports[0].device
             self.serial.serial_number = ports[0].serial_number
             log.info("search for serial_number=%s found port=%s",
                      serial_number, self.serial.port)
     elif device:
         self.serial.port = device
         log.info("using device=%s", device)
     else:
         # NOTE: 2021-06-23 (sustainablelab)
         # Long serial numbers are no longer supported
         # Change "CHROMATION" to "CH"
         # ports = list(list_ports.grep("CHROMATION"))
         ports = list(list_ports.grep("CH"))
         if ports:
             self.serial.port = ports[0].device
             self.serial.serial_number = ports[0].serial_number
             log.info(
                 "defaulting to searching for CHROMATION hardware, "
                 "found port=%s, serial_number=", self.serial.port,
                 self.serial.serial_number)
         if not self.serial.port:
             for port in list_ports.comports(True):
                 if port.vid == 1027 and port.pid == 24597:
                     self.serial.port = port.device
                     break
     if not self.serial.port:
         log.error("Cannot find CHROMATION device")
         raise MicroSpecConnectionException("Cannot find CHROMATION device")
     try:
         self.serial.open()
     except Exception as e:
         log.error(
             "Cannot open device: check if port is already in use, such as another MicroSpec interface is using it: %s"
             % (e))
         raise MicroSpecConnectionException(str(e))
     super().__init__(self.serial)
     log.info("return")
Exemplo n.º 10
0
def get_ports():
    """Get available serial connections."""
    serial_ports = []
    if os.name == 'nt':
        serial_ports = list(grep(r'COM*'))
    elif os.name == 'posix':
        serial_ports = list(grep(r'USB*'))
    log.info(f"Current OS name: {os.name}.")

    serial_ports = [p.device for p in serial_ports]
    log.info(f"Available serial ports: {','.join(serial_ports)}.")

    return serial_ports
Exemplo n.º 11
0
 def list_devices(self, baudrate):
     ports = []
     if os.name == "posix":
         iterator = sorted(list_ports.grep("tty"))
         print "Found ports:"
         for port, desc, hwid in iterator:
             port.append(port)
             print "%-20s" % (port,)
             print "    desc: %s" % (desc,)
             print "    hwid: %s" % (hwid,)
     else:
         # iterator = sorted(list_ports.grep(''))  # does not return USB-style
         # scan for available ports. return a list of tuples (num, name)
         available = []
         for i in range(1, 13):
             try:
                 s = serial.Serial(port=i, baudrate=baudrate)
                 ports.append(s.portstr)
                 available.append((i, s.portstr))
                 s.close()
             except serial.SerialException:
                 pass
         print "Found ports:"
         for n, s in available:
             print "(%d) %s" % (n, s)
     return ports
Exemplo n.º 12
0
def create_easywave_connection(port=None,
                               host=None,
                               baud=57600,
                               protocol=EasywaveProtocol,
                               packet_callback=None,
                               disconnect_callback=None,
                               loop=None):
    """Create Easywave manager class, returns transport coroutine."""
    # use default protocol if not specified
    protocol = partial(
        protocol,
        loop=loop if loop else asyncio.get_event_loop(),
        packet_callback=packet_callback,
        disconnect_callback=disconnect_callback,
    )

    if not port:
        usb_port = list(list_ports.grep("Easywave"))[0]
        port = usb_port.device
        log.debug('USB port: %s', port)

    # setup serial connection if no transport specified
    if host:
        conn = loop.create_connection(protocol, host, port)
    else:
        baud = baud
        conn = create_serial_connection(loop, protocol, port, baud)

    return conn
Exemplo n.º 13
0
    def openAngleSensorPort(self, state):
        if state:

            print(">>>>>>open")

            #port = '/dev/ttyUSB'+str(self.ui.angleSensorPort.value())
            self.data_q = queue.Queue()
            self.error_q = queue.Queue()
            self.port = list(list_ports.grep("0403:0000"))[0][0]
            self.com_monitor = ComMonitorThread(self.data_q, self.error_q,
                                                self.port, 9600)
            self.com_monitor.start()
            #self.angleSensorSerial = serial.Serial(port,baudrate=9600,timeout=0.1)#.port = port
            print(self.port)
            time.sleep(2)
            #self.angleSensorSerial.port = port
            #self.angleSensorSerial.baudrate = 19200
            #self.angleSensorSerial.timeout = 4
            #self.angleSensorSerial.open()
            #self.angleSensorSerial.setDTR(True)
            #self.angleSensorSerial.write(b'')
            #self.angleSensorSerial.flush()
            #self.angleSensorSerial.flushInput()
            #self.angleSensorSerial.flushOutput()
            #a=self.angleSensorSerial.read(5)
            print("0>>", self.data_q)
            #self.angleSensorSerial.write(b"STATE?\n")
            #a=self.angleSensorSerial.readline()
            #print("1>>",a)

            self.angleUpdateTimer.start(self.ui.plotPeriod.value())

        else:
            self.angleUpdateTimer.stop()
            self.com_monitor.stop()
Exemplo n.º 14
0
def find_sms_tool():
    i = list_ports.grep(r'Prolific*')
    try:
        p = i.next()
        return p.device
    except StopIteration:
        return None
Exemplo n.º 15
0
 def list_devices(self, baudrate):
     ports = []
     if os.name == 'posix':
         iterator = sorted(list_ports.grep('tty'))
         log.debug("Found ports:")
         for port, desc, hwid in iterator:
             ports.append(port)
             log.debug("%-20s", port)
             log.debug("    desc: %s", desc)
             log.debug("    hwid: %s", hwid)
     else:
         # scan for available ports. return a list of tuples (num, name)
         available = []
         for i in range(24):
             try:
                 s = serial.Serial(port=i, baudrate=baudrate)
                 ports.append(s.portstr)
                 available.append((i, s.portstr))
                 s.close()
             except serial.SerialException:
                 pass
         log.debug("Found ports:")
         for n, s in available:
             log.debug("(%d) %s", n, s)
     return ports
Exemplo n.º 16
0
    def update(self):
        """
        Update list of serial ports where a BrewPi Controller *might* be
        attached.

        Yields new controllers
        """
        detected_ports = list(list_ports.grep(regexp=self.BREWPI_PHOTON_HWID))

        # Remove stale devices
        for device, controller in list(self.controllers.items()):
            found = False

            # Look for our device in the detected ports
            for port in detected_ports:
                if port.device == device:
                    found = True
                    break

            # Mark as disconnected if stale
            if not found and not device.startswith("socket://"):
                controller.disconnect()
                self.controllers.pop(device)

        # Add new devices
        for port in detected_ports:
            if port.device not in self.controllers:
                LOGGER.info("Found new controller on port {0}".format(
                    port.device))
                self.controllers[port.device] = BrewPiController(port.device)

                yield self.controllers[port.device]
Exemplo n.º 17
0
 def __ListenerEvent(self):
     try:
         # parametro arduino linux
         #arduionoPort = next(list_ports.grep("USB2.0-Serial"))[0]
         arduionoPort = next(
             list_ports.grep("CH340"))[0]  # parametro arduino uno
         PuertoSerie = Serial(arduionoPort,
                              self.__Velocidad_serial,
                              timeout=self.__timeout)
         print(f'puerto COM={arduionoPort}, Arduino iniciado')
     except:
         print("Arduino desconectado, por favor conecte")
     finally:
         while True:
             try:
                 # value_=PuertoSerie.readline()
                 #value= value_.decode("utf-8","ignore")
                 value = PuertoSerie.readline()
                 if (value != b''):
                     self.__pressKey(value)
                 if (value.find(b"4C7") != -1):
                     break
             except:
                 print("error inesperado")
                 break
Exemplo n.º 18
0
    def listen(self):

        while self.isRunning():

            # find port
            if not self.port:
                for dev in list_ports.grep(self.filter):
                    self.port = dev.device
                    break
                if not self.port:
                    self.log("no device found.. retrying")
                    for i in range(10):
                        sleep(0.5)
                        if not self.isRunning():
                            return

            # connect to serial
            elif not self.serial:
                try:
                    self.serial = serial.Serial(self.port, 115200, timeout=.1)
                    self.log("connected to", self.port, "!")
                except:
                    self.log("connection failed on", self.port)
                    self.port = None

            # read
            else:
                try:
                    data = self.serial.readline(
                    )[:-2]  #the last bit gets rid of the new-line chars
                    if data:
                        self.emit(data.decode("utf-8"))
                except:
                    self.log("broken link..")
                    self.serial = None
Exemplo n.º 19
0
    def __init__(self, comm_port: str = None):
        # (detect os and) set communication port
        self._comm = None
        if comm_port is not None:
            try:
                self._comm = LockIn.get_serial(comm_port)
            except serial.SerialException:
                print("lockintools: could not connect to port: %s" % comm_port)
        else:
            print("lockintools: trying default ports for platform: %s" %
                  sys.platform)
            for cp in LockIn.DEFAULT_PORTS[sys.platform]:
                try:
                    self._comm = LockIn.get_serial(cp)
                    break
                except serial.SerialException:
                    print("lockintools: could not connect to port: %s" % cp)

            if self._comm is None and IMPORTED_LIST_PORTS:
                print("lockintools: tying to detect port and auto-connect...")
                for cp_match in list_ports.grep("(usb|USB)"):
                    cp_str = str(cp_match).split('-')[0].strip()
                    try:
                        self._comm = LockIn.get_serial(cp_str)
                        break
                    except serial.SerialException:
                        print("lockintools: could not connect to port: %s" %
                              cp_str)

        if self._comm is None:
            raise LockInError(
                "lockintools: CONNECTION FAILED! Do you have a driver installed?"
            )
        print("lockintools: SUCCESS! Connection established.")
        self.print_to_stdout = True
Exemplo n.º 20
0
 def open(self):
     self.port = list(list_ports.grep("0403:0000"))[0][
         0]  #'/dev/ttyUSB'+str(self.ui.angleSensorPort.value())
     self.com_monitor = ComMonitorThread(self.data_q, self.error_q,
                                         self.port, 9600)
     self.com_monitor.daemon = True
     self.com_monitor.start()
Exemplo n.º 21
0
def checkUSBnames():
    print('Identifying serial ports...')
    goodPorts = []
    toRet = {'alicat': None, 'BK': None, 'Controller': None}
    for dev in list_ports.grep('usbserial*'):
        port, desc, misc = dev
        goodPorts.append(port)
    for port in goodPorts:
        alicat = AlicatInterface(port)
        isAlicat = alicat.checkValidSerial()
        load = BKInterface(port)
        isBK = load.checkValidSerial()
        controller = ControllerInterface(port)
        isController = controller.checkValidSerial()

        if (isAlicat and (not isBK) and (not isController)):
            print('\tport ' + port + ' is an Alicat flowmeter')
            toRet['alicat'] = port
        elif ((not isAlicat) and isBK and (not isController)):
            print('\tport ' + port + ' is a BK DC load')
            toRet['BK'] = port
        elif ((not isAlicat) and (not isBK) and isController):
            print('\tport ' + port + ' is a FC Controller')
            toRet['Controller'] = port
        elif ((not isAlicat) and (not isBK) and (not isController)):
            print('\tport ' + port + ' cannot be recognized')
        else:
            print('\tport ' + port + ' was identified as multiple devices...')
            print('\t\t', isAlicat, isBK, isController)
    return toRet
Exemplo n.º 22
0
 def match_device(self, search_regex, baudrate):
     if os.name == 'posix':
         matched_ports = list_ports.grep(search_regex)
         if matched_ports:
             for match_tuple in matched_ports:
                 if match_tuple:
                     return match_tuple[0]
         print "No serial port match for anything like: " + search_regex
         return None
     else:
         # windows hack because pyserial does not enumerate USB-style com ports
         print "Trying to find Controller ..."
         for i in range(24):
             try:
                 s = serial.Serial(port=i, baudrate=baudrate, timeout=2.0)
                 s.write("?\n")
                 lasaur_hello = s.read(32)
                 if lasaur_hello.find("\n") > -1:
                     if lasaur_hello.find("X") > -1:
                         if lasaur_hello.find("Y") > -1:
                             if lasaur_hello.find("V") > -1:
                                 return s.portstr
                 s.close()
             except serial.SerialException:
                 pass
         return None
Exemplo n.º 23
0
 def discover(regexp):
     ports = list(list_ports.grep(SerialHandler.DISCOVER_PORT_REGEXP))
     if not ports:
         raise SerialHandlerExceptionNoPorts(regexp)
     if len(ports) > 1:
         raise SerialHandlerExceptionTooManyPorts(regexp, ports)
     return ports[0]
Exemplo n.º 24
0
def get_port_name(regex):
    if not regex:
        return None
    for device_info in list_ports.grep(regex):
        return device_info.device
    else:
        return None
Exemplo n.º 25
0
    def __detect_all_serial_ports(self,
                                  stop_on_first=False,
                                  include_all_ports=True):
        # figures out the serial ports associated with the modem and returns them
        device_names = []
        for usb_id in self.usb_ids:
            vid = usb_id[0]
            pid = usb_id[1]

            # The list_ports function returns devices in descending order, so reverse
            # the order here to iterate in ascending order (e.g. from /dev/xx0 to /dev/xx6)
            # since our usable serial devices usually start at 0.
            udevices = [x for x in list_ports.grep("{0}:{1}".format(vid, pid))]
            for udevice in reversed(udevices):
                if include_all_ports == False:
                    self.logger.debug('checking port %s', udevice.name)
                    port_opened = self.openSerialPort(udevice.device)
                    if not port_opened:
                        continue

                    res = self.command('', timeout=1)
                    if res[0] != ModemResult.OK:
                        continue
                    self.logger.info('found working port at %s', udevice.name)

                device_names.append(udevice.device)
                if stop_on_first:
                    break
            if stop_on_first and device_names:
                break
        return device_names
Exemplo n.º 26
0
    def __init__(self):
        ports={}
        for (name,_,_) in list_ports.grep('/dev/ttyACM*'):
            port = serial.Serial(name, timeout=3)
            port.write('I\n')
            teensyid = port.readline().strip()
            ports[teensyid] = port
        for (i,p) in ports.items():
            print("Found {0}".format(i))
        self.t=ports['teensy']
        self.tpp=ports['teensypp']
	# teensy 3 is unreliable; we're not using it right now anyway
	try:
            self.t3=ports['teensy3']
        except:
            self.t3=None
        self.tlock = threading.RLock()
        self.tpplock = threading.RLock()
        self.t3lock = threading.RLock()
        # imap entries are (pressed, mode)
        self.imap = [(False,0)]*illum_count
        self.tlock.acquire()
        self.t.write('m\\x0cmBoot sequence\\ncomplete.\n')
        time.sleep(0.5)
        self.t.write('m\\x0c\n')
        for i in range(illum_count):
            self.set_illuminated(i,0)
        self.tlock.release()
Exemplo n.º 27
0
def find_serial_port():
    portname = None
    try:
        # pyserial 2.6 in the VM has a bug where grep is case-sensitive.
        # It also requires us to use [0] instead of .device on the result
        # to get the serial device path.
        portname = next(
            list_ports.grep(r'(?i)VID:PID=%s:%s' %
                            (SERIAL_VID, SERIAL_PID)))[0]
    except StopIteration:
        pass

    # Device IDs aren't available in WSL. In this case, we do the search through PowerShell and map the output to the Linux device name
    if portname is None and platform.system(
    ) == "Linux" and "Microsoft" in platform.release():
        ps_cmd = [
            'powershell.exe',
            '(Get-WmiObject -query "SELECT * FROM Win32_PnPEntity" | ' +
            'Where-Object {$_.DeviceID -like "*VID_%s&PID_%s*"}).Name' %
            (SERIAL_VID, SERIAL_PID)
        ]
        output = subprocess.check_output(ps_cmd).strip()
        match = re.search(rb'\(COM(\d+)\)', output)
        if match:
            portname = '/dev/ttyS' + match.group(1).decode('utf-8')

    if portname is not None:
        return portname
    else:
        error(
            "Could not find CP2102 serial device.", """
I looked through the serial devices on this computer, and did not
find a device associated with a CP2102 USB-to-serial adapter. Is
your Pi plugged in?
""")
Exemplo n.º 28
0
    def initdevice(self, canBaudrate, frtype, mode, devname, baudrate, stopbits, timeout, writeTimeout, bytesize):
        self.canport = None

        # Search for CH340 Device
        ports = list(list_ports.grep(devname))
        if len(ports) == 0:
            raise SystemError("No USB-CAN Device found by regexp '{}'".format(devname))

        if len(ports) > 1:
            ports_names = ""
            for port, name, vid in ports:
                ports_names += port + " "

            raise SystemError("Find more then one device by regexp '{}', '{}'".format(devname, ports_names))

        port = ports[0][0]

        self.canport = serial.Serial(port, baudrate,
                            parity = serial.PARITY_NONE,
                            stopbits = stopbits, timeout = timeout,
                            writeTimeout = writeTimeout, bytesize = bytesize)

        if not self.canport:
            raise SystemError("Can't open USB-CAN Device {}".format(port))

        else:
            print ("USB-CAN Device ready, CAN baudrate: ", canBaudrate)

        self.setup(canBaudrate, frtype, mode)

        self.set_IDfilter([]) # disable idfilter

        time.sleep(0.5)
Exemplo n.º 29
0
def get_port():
    try:
        for e in list_ports.grep("duino"):
            print e[0]
            return e[0]
    except:
        print "Didn't get an Arduino"  ##  this doesnt get here when duino port is not opened...
Exemplo n.º 30
0
 def list_devices(self, baudrate):
     ports = []
     if os.name == 'posix':
         iterator = sorted(list_ports.grep('tty'))
         print("Found ports:")
         for port, desc, hwid in iterator:
             ports.append(port)
             print("%-20s" % (port, ))
             print("    desc: %s" % (desc, ))
             print("    hwid: %s" % (hwid, ))
     else:
         # iterator = sorted(list_ports.grep(''))  # does not return USB-style
         # scan for available ports. return a list of tuples (num, name)
         available = []
         for i in range(24):
             try:
                 s = self.open_serial(i, baudrate)
                 ports.append(s.portstr)
                 available.append((i, s.portstr))
                 s.close()
             except serial.SerialException:
                 pass
         print("Found ports:")
         for n, s in available:
             print("(%d) %s" % (n, s))
     return ports
Exemplo n.º 31
0
def find_my_serial_port(my_port):
    """
    :return: Requested serial port info tuple
    :rtype:
    """
    my_port = list_ports.grep(my_port, True)
    return iter(my_port)
Exemplo n.º 32
0
def main():
    """open daemons based on number of vaisala's found"""
    global infile, stop_event
    infile = [
        l.rsplit() for l in open("vaisala_infile", mode="r").readlines()
        if l[0] != "#"
    ]
    stop_event = threading.Event()
    """above processes infile and handles missing lines"""
    try:
        vaisala = list(list_ports.grep("Vaisala*"))
    except StopIteration:
        print("No device found")
    loc_nat = vaisala[0][0]
    loc_nat = loc_nat.encode('ascii', 'replace')

    print("Vaisala COM port is", loc_nat.decode('UTF-8'))

    if (loc_nat != ""):
        ser1 = serial.Serial(loc_nat.decode('UTF-8'),
                             baudrate=19200,
                             timeout=1)
        id_num = "vaisala"
        file1 = create_log_file(id_num)
        interprate_vaisala_string(ser1, file1, id_num)
    else:
        print("No Vaisalas are connected")
        return
Exemplo n.º 33
0
 def match_device(self, search_regex, baudrate):
     if os.name == 'posix':
         matched_ports = list_ports.grep(search_regex)
         if matched_ports:
             for match_tuple in matched_ports:
                 if match_tuple:
                     return match_tuple[0]
         print "No serial port match for anything like: " + search_regex
         return None
     else:
         # windows hack because pyserial does not enumerate USB-style com ports
         print "Trying to find Controller ..."
         for i in range(24):
             try:
                 s = serial.Serial(port=i, baudrate=baudrate, timeout=2.0)
                 s.write("?\n")
                 lasaur_hello = s.read(32)
                 if lasaur_hello.find("\n") > -1:
                     if lasaur_hello.find("X") > -1:
                         if lasaur_hello.find("Y") > -1:
                             if lasaur_hello.find("V") > -1:
                                 return s.portstr
                 s.close()
             except serial.SerialException:
                 pass      
         return None      
Exemplo n.º 34
0
    def __init__(self, callback=None):
        threading.Thread.__init__(self)
        logging.basicConfig(level=logging.DEBUG,
                            filename="spring.log",
                            filemode="w")
        available_ports = list(list_ports.grep('/dev/tty', include_links=True))
        if not available_ports:
            raise ValueError("no available ports")
        print "available ports {}, choose port {}".format(
            [port.device for port in available_ports],
            available_ports[0].device)
        self.ser = Serial(available_ports[0].device, baudrate=115200)

        self.callback = callback

        self.x = 0
        self.prev_x = 0
        self.velocity = 0

        self.mass = 0.0001
        self.k = None
        self.rate = None
        self.down_rate = None
        self.k1 = None
        self.k2 = None
        self.k3 = None
        self.left_point = None
        self.middle_point = None
        self.right_point = None
        self.step_point = None
        self.profile = None
        self.width = None
        self.position = None

        self.force_sensor_storage = []
        self.average_force = None

        self.estimated_delta_time = 0.0037
        self.last_time = None

        self.buffer = bytearray()

        self.x_lock = threading.Lock()
        self.terminate_event = threading.Event()

        self.csvfile = open("log.csv", "wb")
        self.writer = csv.writer(self.csvfile)

        def f(t, y, force, k, damping):
            displacement, velocity = y
            return [
                velocity,
                float(force - k * displacement - damping * velocity) /
                self.mass
            ]

        self.ode_solver = ode(f)
        self.ode_solver.set_integrator("dopri5")
        self.ode_solver.set_initial_value([0, 0], 0)
Exemplo n.º 35
0
def find_address(identifier=None):
    """
    Find the address of a serial device. It can either find the address using
    an identifier given by the user or by manually unplugging and plugging in 
    the device.
    Input:
    `identifier`(str): Any attribute of the connection. Usually USB to Serial
        converters use an FTDI chip. These chips store a number of attributes
        like: name, serial number or manufacturer. This can be used to 
        identify a serial connection as long as it is unique. See the pyserial
        list_ports.grep() function for more details.
    Returns:
    The function prints the address and serial number of the FTDI chip.
    `port`(obj): Retruns a pyserial port object. port.device stores the 
        address.
    
    """
    found = False
    if identifier != None:
        port = [i for i in list(list_ports.grep(identifier))]

        if len(port) == 1:
            print('Device address: {}'.format(port[0].device))
            found = True
        elif len(port) == 0:
            print('''No devices found using identifier: {}
            \nContinue with manually finding USB address...\n'''.format(
                identifier))
        else:
            for p in connections:
                print('{:15}| {:15} |{:15} |{:15} |{:15}'.format(
                    'Device', 'Name', 'Serial number', 'Manufacturer',
                    'Description'))
                print('{:15}| {:15} |{:15} |{:15} |{:15}\n'.format(
                    str(p.device), str(p.name), str(p.serial_number),
                    str(p.manufacturer), str(p.description)))
            raise Exception(
                """The input returned multiple devices, see above.""")

    if found == False:
        print('Performing manual USB address search.')
        while True:
            input('    Unplug the USB. Press Enter if unplugged...')
            before = list_ports.comports()
            input(
                '    Plug in the USB. Press Enter if USB has been plugged in...'
            )
            after = list_ports.comports()
            port = [i for i in after if i not in before]
            if port != []:
                break
            print('    No port found. Try again.\n')
        print('Device address: {}'.format(port[0].device))
        try:
            print('Device serial_number: {}'.format(port[0].serial_number))
        except Exception:
            print('Could not find serial number of device.')

    return port[0]
Exemplo n.º 36
0
def find_port():
    try:
        dji_dev = list(list_ports.grep("2ca3:001f"))[0][0]
        return dji_dev
    except:
        sys.exit(
            "Error: No DJI device found plugged to your system. Please re-plug / reboot device and try again.\n"
        )
Exemplo n.º 37
0
 def search_ports(self):
     ports = []
     try:
         com_port_name = str(next(list_ports.grep(self.chip_name)))
         ports.append(com_port_name[0:4])
         return ports[0]
     except StopIteration:
         print("No found")
Exemplo n.º 38
0
def main():  
    si_port = [ port for port in list_ports.grep("sportident.*") ].pop()
    logger.info("Opening SI reader on port %s" % (si_port))
    punch_reader = SIPunchReader(si_port.device)
    
    xbee_port = [ port for port in list_ports.grep("0403:6015") ].pop()
    logger.info("Opening writer on port %s" % (xbee_port))
    punch_writer = XBeeWriter(xbee_port.device)
    while True:
        try:
            cmd, raw_data = punch_reader.readCommand()
            if cmd == SIReader.C_TRANS_REC:
                #logger.info("==>> Sending punch %s" % (' '.join([hexlify(int2byte(c)).decode('ascii') for c in raw_data])))
                logger.info("==>> Sending punch %s" % (hexlify(raw_data)))
                punch_writer.send(raw_data)
        except SIReaderTimeout:
            pass
Exemplo n.º 39
0
def find_dongle(): #posix servers only
    matches = []
    for port in list_ports.grep('ACM'):
        matches.append(port[0])

    if len(matches) != 1:
        print "Multiple Dongles Found"

    return matches[0]
Exemplo n.º 40
0
 def _available_ports_default(self):
     import serial.tools.list_ports as lp
     ll = []
     if int(serial.VERSION[0]) == 2:
         return [l[0] for l in lp.comports()]
     else:
         for p in lp.grep('F055:9800'):
             ll.append(p.device)
     return ll
Exemplo n.º 41
0
def list_of_serial_ports():
    #list available com ports
    open_ports=[]
    #select only the dispenser via the VID
    for port in list_ports.grep('0403:6001'):
    #USB ports only shows up when connected
        open_ports.append(port.device)

    return(open_ports)
Exemplo n.º 42
0
    def list_device_ports(self):
        """
        Returns a list of usb ports that could possibly be
        connected to arduino boards.
        """
        from serial.tools import list_ports

        ports = list(list_ports.grep("/dev/ttyUSB*|/dev/ttyACM*"))

        return ports
Exemplo n.º 43
0
	def connect(self, block = False):
		while True:
			try:
				port = list_ports.grep('arduino').next()
				self.conection = serial.Serial(port[0])
			except:
				if block:
					time.sleep(0.5)
				else:
					return False
			else:
				return True
    def com_port_should_exist_regexp(self, regexp):
        """
        Fails if com port matching given pattern is not found on the system.

        This keyword uses serial.tools.list_ports.grep internally thus
        port name, description and hardware ID are searched.

        Returns list of com ports matching the pattern, if exists.
        """
        found = list(grep(regexp))
        asserts.assert_true(len(found) > 0, 'Matching port does not exist.')
        return found
Exemplo n.º 45
0
 def find_teensy2_linux(self):
     """Find where the Teensy 2 board is connected and return the port."""
     if sys.platform.startswith("linux"):
         ports_avaiable = list(list_ports.grep("/dev/ttyACM.*"))
         teensy_ports = list()
         if ports_avaiable != []:
             for ports in ports_avaiable:
                 if ports[-1][12:21] == "16c0:0483" and ports[-1][26:31] == "12345":
                     teensy_ports.append(ports)
             if len(teensy_ports) > 1:
                 return teensy_ports[-1]
             else:
                 return teensy_ports[0]
Exemplo n.º 46
0
def serial_ports():

    #list available com ports
    open_ports=[]
    for port in list_ports.grep('USB'):
    #USB ports only shows up when connected
        open_ports.append(port.device)
    print open_ports

    try:# port configuration
        ser = serial.Serial(
            #port='COMx',  #for windows
            #port='/dev/ttyUSB0',
            port=open_ports[0],
            baudrate=19200,
            parity=serial.PARITY_NONE,
            stopbits=serial.STOPBITS_ONE,
            bytesize=serial.EIGHTBITS,
            timeout=1
        )

    except (serial.SerialException,IndexError) :
        print "No Active serial ports found:"

    else: #found an open port
        if ser.is_open:
            print "Active serial port: " + ser.name

        ser.flushInput() #flush input buffer, discarding all its contents
        ser.flushOutput()#flush output buffer, aborting current output
                 #and discard all that is in buffer

        #status request response cycle example
        #send command i:
        ser.write(command['request_status'].decode('hex'))
        print "Sent Packets: "+ command['request_status']

        #read response
        response_received= ser.readline(7).encode("hex")
        print "Received Packets: " + response_received

        #check if response is valid
        if response_received in status_response:
            print status_response[response_received]
        else:
            print "not a valid response"

        ser.close()

    finally:
        pass
Exemplo n.º 47
0
    def __init__(self, device_number):
        self.serial = serial.Serial()
        self.serial.baudrate = 9600
        self.serial_available = False
        self.device_number = device_number

        try:
            """
            Check ttyUSB devices 0 through 9, and get the first one present.
            TODO: stuff this into the config file. Its a stupid way.
            """
            self.serial.port = next(list_ports.grep("ttyUSB[0-9]"))[0]
        except serial.SerialException:
            self.serial_available = False
Exemplo n.º 48
0
	def findDevices(self):
		""" Search for Practichem devices """
		# prevent multiple simultaneous calls to findDevices
		with self.lock:
			self.informationForDevices = []
			# 2404 is the Atmel PID that is used for Practichem CDC devices
			ports = list_ports.grep("2404")
			deviceQueryThreadList = []
			for port in ports:
				logger.debug("Looking for device on port {}".format(port[0]))
				deviceQueryThread = DeviceQueryThread(port, self._add_device_callback)
				deviceQueryThread.start()
				deviceQueryThreadList.append(deviceQueryThread)

			# wait for all queries to finish
			for deviceQueryThread in deviceQueryThreadList:
				deviceQueryThread.join(5)
Exemplo n.º 49
0
    def __init__(self):
        import serial
        from serial.tools import list_ports

        ports = list(list_ports.grep("EDBG|UART|Mycelium"))
        if not ports:
            print "Signing device is not connected."
            sys.exit(2)
        if len(ports) > 1:
            print "Ambiguous port."
            sys.exit(2)
        self.port = serial.Serial(ports[0][0], 115200, timeout=10)
        self.port.write('\r')
        if "enter hash" not in str(self.port.readline()) \
                and "enter hash" not in str(self.port.readline()) \
                and "enter hash" not in str(self.port.readline()):
            print "Cannot connect to signing device."
            sys.exit(2)
Exemplo n.º 50
0
    def __init__(self, port=None, baud=115200):
        """
        :param port: The virtual port number.
        :param baud: Baud rate. Should use maximum.
        """

        if port is not None:
            self.port = port
        else:
            # Determine the operating system and port strings.
            # Command port is used for USB Dual Port mode.
            # Can automatically determine from a scan.
            ports = list(list_ports.grep(r'(?i)1ffb:008b'))

            if os.name == 'nt':
                if len(ports) == 2:
                    if 'Command' in ports[0][1]:
                        self.port = ports[0][0]
                    else:
                        self.port = ports[1][0]
                else:
                    raise ConnectionError('Unable to determine the Command port automatically. Please specify.')
            else:
                if len(ports) == 2:
                    # Assuming nothing was messed with, the command port is the lower port.
                    if int(re.search(r'(\d+)$', ports[1][0]).group(0)) > int(re.search(r'(\d+)$', ports[0][0]).group(0)):
                        self.port = ports[0][0]
                    else:
                        self.port = ports[1][0]
                else:
                    raise ConnectionError('Unable to determine the Command port automatically. Please specify.')

        # Start a connection using pyserial.
        try:
            self.usb = serial.Serial(self.port, baudrate=baud, write_timeout=0)
            logger.debug('Using command port "{}".'.format(self.usb.port))
        except:
            raise ConnectionError('Unable to connect to servo controller at {}.'.format(self.port))

        # Struct objects are faster.
        self.struct = struct.Struct('<H')

        # Locks.
        self.read_lock = Lock()
Exemplo n.º 51
0
    def __init__(self, port=None):
        """
        RFID reader class for SparkFun's USB RFID Reader.
        :param port: The virtual port number.
        """

        if port is not None:
            self.port = port
        else:
            ports = list(list_ports.grep(r'(?i)0403'))

            if len(ports) == 1:
                self.port = ports[0][0]
            else:
                raise Exception('Unable to determine RFID reader port automatically. Please specify.')

        # Start a connection using pyserial.
        try:
            self.usb = serial.Serial(self.port, timeout=0)
        except:
            raise Exception('Unable to connect to RFID reader at %s.' % self.port)
Exemplo n.º 52
0
 def match_device(self, search_regex, baudrate):
     if os.name == "posix":
         matched_ports = list_ports.grep(search_regex)
         if matched_ports:
             for match_tuple in matched_ports:
                 if match_tuple:
                     return match_tuple[0]
         print "No serial port match for anything like: " + search_regex
         return None
     else:
         # windows hack because pyserial does not enumerate USB-style com ports
         for i in range(256):
             try:
                 s = serial.Serial(port=i, baudrate=baudrate, timeout=1.0)
                 lasaur_hello = s.read(16)
                 if lasaur_hello.find(self.LASAURGRBL_FIRST_STRING) > -1:
                     return s.portstr
                 s.close()
             except serial.SerialException:
                 pass
         return None
Exemplo n.º 53
0
 def match_device(self, search_regex, baudrate):
     if os.name == 'posix':
         matched_ports = list_ports.grep(search_regex)
         if matched_ports:
             for match_tuple in matched_ports:
                 if match_tuple:
                     return match_tuple[0]
         log.debug("No serial port match for anything like: " + search_regex)
         return None
     else:
         # windows hack because pyserial does not enumerate USB-style com ports
         log.info("Trying to find Controller ...")
         for i in range(24):
             try:
                 s = serial.Serial(port=i, baudrate=baudrate, timeout=2.0)
                 lasaur_hello = s.read(32)
                 if lasaur_hello.find(self.LASAURGRBL_FIRST_STRING) > -1:
                     return s.portstr
                 s.close()
             except serial.SerialException:
                 pass
         return None
Exemplo n.º 54
0
        def __init__(self, path=None, controller=0) :
            super(Port._SerialConnection, self).__init__()

            from serial.tools import list_ports

            if path is None :

                # Modulo Controller will contain in the hardware description:
                #    "16d0:a67" on OSX
                #    "16D0:0A67" on Windows 71
                for port in list_ports.grep("16d0:0?a67") :
                    if (controller == 0) :
                        path = port[0]
                        break
                    controller -= 1

            if path is None :
                print(list_ports.comports())
                raise IOError("Couldn't find a Modulo Controller connected via USB")

            self._serial = serial.Serial(path, 9600, timeout=5)
            self._eventData = []
Exemplo n.º 55
0
 def list_devices(self, baudrate):
     ports = []
     if os.name == 'posix':
         iterator = sorted(list_ports.grep('tty'))
         log.debug("Found ports:")
         for port, desc, hwid in iterator:
             ports.append(port)
             log.debug("%-20s", port)
             log.debug("    desc: %s", desc)
             log.debug("    hwid: %s", hwid)
     else:
         # scan for available ports. return a list of tuples (num, name)
         available = []
         for i in range(24):
             try:
                 s = serial.Serial(port=i, baudrate=baudrate)
                 ports.append(s.portstr)
                 available.append( (i, s.portstr))
                 s.close()
             except serial.SerialException:
                 pass
         log.debug("Found ports:")
         for n,s in available: log.debug("(%d) %s", n, s)
     return ports
def connectToArduino():
	# TODO: make this OS independant
	global arduinoDevice
	def fail():
		print ("Could not automatically find your Arduino device.")
		return None
	if not arduinoDevice:
		try:
			from serial.tools import list_ports
			dmesgOutput = os.popen("dmesg").read()
			lastOccurence = dmesgOutput.rfind("Arduino")
			if lastOccurence == -1:
				return fail()
			ttyBegin = dmesgOutput.find("tty", lastOccurence)
			if ttyBegin == -1:
				return fail()
			ttyEnd = min([dmesgOutput.find(c, ttyBegin) for c in (':', ' ', '\t', '\r', '\n') if c in dmesgOutput[ttyBegin:]])
			arduinoDevice = list(list_ports.grep(dmesgOutput[ttyBegin:ttyEnd]))[0][0]
		except:
			return fail()
	
	ser = serial.Serial(
			port = arduinoDevice,
			baudrate = 9600,
			bytesize = serial.EIGHTBITS,
			parity = serial.PARITY_NONE,
			stopbits = serial.STOPBITS_ONE,
			timeout = 1,
			xonxoff = 0,
			rtscts = 0,
			interCharTimeout = None
		)
	
	print ("Connected to Arduino at '%s'." % arduinoDevice)
	
	return ser
Exemplo n.º 57
0
#! /usr/bin/env python


from microkopter import *
from serial.tools import list_ports


serial_usb_port = [port[0] for port in list_ports.grep('usbserial')]
if len(serial_usb_port) == 0:
    print "Couldn't find the serial interface. Is it plugged in?"
    sys.exit()

# TODO : add this later to handle exceptions
comPort = serial_usb_port[0]

comPort = '/dev/tty.usbserial-A40078OI'

comm = MkComm()
comm.printDebugMsg = True
comm.open(comPort = comPort, timeout = 0.5)

print "Sending FC->NC forwarding"
comm.sendNCRedirectUartFromFC()


# Version message request
# msg = VersionRequestMsg()
# comm.sendMsg(msg)
# returned_msg = comm.waitForMsg(VersionMsg.command)
# print returned_msg
# print
 def list_usb_ports(self):
     """Use the grep generator to get a list of all USB ports.
     """
     ports =  [port for port in list_ports.grep('usb')]
     return ports
Exemplo n.º 59
0
Arquivo: cli.py Projeto: ieure/yar
def default_dev():
    """Return the default device."""
    p = tuple(list_ports.grep("serial"))
    return p and p[0][0] or None
Exemplo n.º 60
0
def serial_ports():

    available=[port[0] for port in list_ports.grep('COM')]
    ports=[int(port[3:])for port in available]
    return ports