Ejemplo n.º 1
0
 def _init_serial(self, spec):
     """Initialise the serial object."""
     addr, val = parse_protocol_string(spec)
     try:
         if not addr and not val:
             pass
         elif addr == u'STDIO' or (not addr and val.upper() == u'STDIO'):
             return SerialStdIO(val.upper() == u'CRLF')
         else:
             if not serial:
                 logging.warning(
                     u'Could not attach %s to COM device. Module `serial` not available: %s',
                     spec, logging_msg
                 )
                 return None
             if addr in (u'SOCKET', u'RFC2217'):
                 # throws ValueError if too many :s, caught below
                 host, socket = val.split(u':')
                 url = u'%s://%s:%s' % (addr.lower(), host, socket)
                 stream = serial.serial_for_url(url, timeout=0, do_not_open=True)
                 # monkey-patch serial object as SocketSerial does not have this property
                 stream.out_waiting = 0
                 return stream
             elif addr == u'PORT':
                 # port can be e.g. /dev/ttyS1 on Linux or COM1 on Windows.
                 return serial.serial_for_url(val, timeout=0, do_not_open=True)
             else:
                 raise ValueError(u'Invalid protocol `%s`' % (addr,))
     except (ValueError, EnvironmentError) as e:
         logging.warning(u'Could not attach %s to COM device: %s', spec, e)
     return None
Ejemplo n.º 2
0
 def test_custom_url(self):
     """custom protocol handlers"""
     # it's unknown
     self.assertRaises(ValueError, serial.serial_for_url, "test://")
     # add search path
     serial.protocol_handler_packages.append('handlers')
     # now it should work
     serial.serial_for_url("test://")
     # remove our handler again
     serial.protocol_handler_packages.remove('handlers')
     # so it should not work anymore
     self.assertRaises(ValueError, serial.serial_for_url, "test://")
Ejemplo n.º 3
0
 def test_failed_connection(self):
     # connection to closed port
     s = serial.serial_for_url('rfc2217://127.99.99.99:2217', do_not_open=True)
     self.failUnlessRaises(serial.SerialException, s.open)
     self.assertFalse(s.is_open)
     s.close() # no errors expected
     # invalid address
     s = serial.serial_for_url('rfc2217://127goingtofail', do_not_open=True)
     self.failUnlessRaises(serial.SerialException, s.open)
     self.assertFalse(s.is_open)
     s.close() # no errors expected
     # close w/o open is also OK
     s = serial.serial_for_url('rfc2217://irrelevant', do_not_open=True)
     self.assertFalse(s.is_open)
     s.close() # no errors expected
Ejemplo n.º 4
0
def _spec_open_one(spec):
    if isinstance(spec, basestring):
        descr = serial.serial_for_url(spec)
        descr.nonblocking()
        return descr
    elif isinstance(spec, dict):
        # We have to remove the port thing for passing to the
        # function, but we want to keep the original spec intact
        _spec = dict(spec)
        url = _spec.pop('port')
        descr = serial.serial_for_url(url, **_spec)
        descr.nonblocking()
        return descr
    else:
        raise RuntimeError("Don't know how to open: %s" % spec)
Ejemplo n.º 5
0
    def __init__(self, port=PORT, baud=BAUD, start_baud=START_BAUD):
        log.info('opening port %s with %s baud', port, start_baud)
        if port == 'loop://':
            self._port = serial.serial_for_url(port, start_baud, timeout=Uploader.TIMEOUT)
        else:
            self._port = serial.Serial(port, start_baud, timeout=Uploader.TIMEOUT)

        self.start_baud = start_baud
        self.baud = baud
        # Keeps things working, if following conections are made:
        ## RTS = CH_PD (i.e reset)
        ## DTR = GPIO0
        self._port.setRTS(False)
        self._port.setDTR(False)

        def sync():
            # Get in sync with LUA (this assumes that NodeMCU gets reset by the previous two lines)
            log.debug('getting in sync with LUA');
            self.clear_buffers()
            try:
                self.exchange(';') # Get a defined state
                self.writeln('print("%sync%");')
                self.expect('%sync%\r\n> ')
            except CommunicationTimeout:
                raise DeviceNotFoundException('Device not found or wrong port')

        sync()

        if baud != start_baud:
            self.set_baudrate(baud)

            # Get in sync again
            sync()

        self.line_number = 0
Ejemplo n.º 6
0
def get_data(engine, TBase, port, baudrate=115200, timeout=1):
    '''
    '''
    ser = serial.serial_for_url(port, baudrate=baudrate, timeout=timeout) # Open com port
    t1old = 0                   # Initialization
    t2old = 0                   # Initialization
    while 1:                    # While TRUE read a com port
        data = ser.read(14)     # Read 14 bytes
        #print data
        if (data != '') and (data != []): # Check for data
            #print 'data: ',repr(data)
            try:
                # Unpack readed data
                c=unpack('>h',str(bytearray(data)[4:-8]))
                t0=unpack('>l',str(bytearray(data)[6:-4]))
                t1new=unpack('>h',str(bytearray(data)[10:-2]))
                t2new=unpack('>h',str(bytearray(data)[12:]))
            except:
                continue

            delta = int(t2new[0])-int(t1new[0])
            now = dt.datetime.now() # Current date and time
            print now.strftime('%Y-%m-%d %H:%M:%S'), 'dT1='+time2str(t1new[0]+t0[0]-t1old)+',', \
            'dT1='+time2str(t1new[0]+t0[0]-t1old)+',', 'Label='+str(c[0])+',', 'T0='+str(t0[0])+',', \
            'T1+='+str(t1new[0])+',', 'T2+='+str(t2new[0])+',', 'dlt='+str(delta)

            #send data to base
            fillDB(engine, TBase, now.strftime('%Y-%m-%d %H:%M:%S'), str(c[0]), time2str(t1new[0]+t0[0]-t1old)) # или t2new в зависимости от выбора. выбор дописать

            t1old = t1new[0]+t0[0] # Time1 on last lap
            t2old = t2new[0]+t0[0] # Time2 on last lap


    ser.close()                 # Close com port
Ejemplo n.º 7
0
 def __init__(self, portname):
     self.serialport = serial.serial_for_url(portname, do_not_open=True)
     self.serialport.close()  # In case port is already open
     self.serialport.open()
     self.serialport.write("++addr 10\n".encode())
     self.successread = 0
     self.failread = 0
Ejemplo n.º 8
0
    def try_connect(url, tries=10, step=0.5, *args, **kwargs):
        """ Try connecting 'tries' time to url tuple
        Sleep 'step' between each tries.
        If last trial fails, the SerialException is raised

        The goal is to be resilient to the fact that serial_aggregator might be
        (re)starting.  """
        # Run 'tries -1' times with 'try except'
        for _ in range(0, tries - 1):
            try:
                return serial.serial_for_url(url, *args, **kwargs)
            except serial.SerialException:
                time.sleep(step)

        # Last connection should run an exception
        return serial.serial_for_url(url, *args, **kwargs)
Ejemplo n.º 9
0
 def open(self, wait = True):
     # ATTN: timeout is essential else realine will block.
     try:
         self.port = serial.serial_for_url( config.args_.port
                 , self.baudRate , timeout = 0.5
                 )
     except OSError as e:
         # Most like to be a busy resourse. Wait till it opens.
         print("[FATAL] Could not connect")
         print(e)
         if wait:
             _logger.warn("[INFO] Device seems to be busy. I'll try to reconnect"
                     " after  some time..."
                     )
             time.sleep(1)
             self.open( True )
         else:
             quit()
     except Exception as e:
         _logger.error("[FATAL] Failed to connect to port. Error %s" % e)
         quit()
     if wait:
         print("[INFO] Waiting for port %s to open" % self.path, end='')
         while not self.port.isOpen():
             if int(time.time() - tstart) % 2 == 0:
                 print('.', end='')
                 sys.stdout.flush()
     print(" ... OPEN")
Ejemplo n.º 10
0
 def __init__(self, url=None, dev=None, num_boards=3):
     if dev is None:
         dev = serial.serial_for_url(url)
     self.dev = dev
     self.num_boards = num_boards
     self.num_channels = self.num_dacs * self.num_boards
     self.channels = [Channel() for i in range(self.num_channels)]
Ejemplo n.º 11
0
    def __init__(self, channel, baudrate=115200, timeout=0.1, rtscts=False,
                 *args, **kwargs):
        """
        :param str channel:
            The serial device to open. For example "/dev/ttyS1" or
            "/dev/ttyUSB0" on Linux or "COM1" on Windows systems.

        :param int baudrate:
            Baud rate of the serial device in bit/s (default 115200).

            .. warning::
                Some serial port implementations don't care about the baudrate.

        :param float timeout:
            Timeout for the serial device in seconds (default 0.1).

        :param bool rtscts:
            turn hardware handshake (RTS/CTS) on and off

        """
        if not channel:
            raise ValueError("Must specify a serial port.")

        self.channel_info = "Serial interface: " + channel
        self.ser = serial.serial_for_url(
            channel, baudrate=baudrate, timeout=timeout, rtscts=rtscts)

        super(SerialBus, self).__init__(channel=channel, *args, **kwargs)
Ejemplo n.º 12
0
	def open(self, device, baudrate):
		#self.serial = serial.Serial(
		self.serial = serial.serial_for_url(
						device,
						baudrate,
						bytesize=serial.EIGHTBITS,
						parity=serial.PARITY_NONE,
						stopbits=serial.STOPBITS_ONE,
						timeout=SERIAL_TIMEOUT,
						xonxoff=False,
						rtscts=False)
		# Toggle DTR to reset Arduino
		try:
			self.serial.setDTR(0)
		except IOError:
			pass
		time.sleep(1)
		CNC.vars["state"] = CONNECTED
		CNC.vars["color"] = STATECOLOR[CNC.vars["state"]]
		#self.state.config(text=CNC.vars["state"],
		#		background=CNC.vars["color"])
		# toss any data already received, see
		# http://pyserial.sourceforge.net/pyserial_api.html#serial.Serial.flushInput
		self.serial.flushInput()
		try:
			self.serial.setDTR(1)
		except IOError:
			pass
		time.sleep(1)
		self.serial.write(b"\n\n")
		self._gcount = 0
		self._alarm  = True
		self.thread  = threading.Thread(target=self.serialIO)
		self.thread.start()
		return True
Ejemplo n.º 13
0
    def available_ports():
        usb_serial_ports = filter(
            (lambda x: x.startswith('ttyUSB')),
            os.listdir('/dev'))

        ports = []
        for p in usb_serial_ports:
            ports.append(serial_for_url('/dev/'+p, do_not_open=True))


        """
        also check for old school serial ports, my hope is that this will enable
        both USB serial adapters and standard serial ports

        Scans COM1 through COM255 for available serial ports

        returns a list of available ports
        """
        for i in range(256):
            try:
                p = Serial(i)
                p.close()
                ports.append(p)
            except SerialException:
                pass

        return ports
Ejemplo n.º 14
0
 def __init__(self, port, baudRate, parity, rtscts=False, xonxoff=False,
              echo=False, convert_outgoing=1, repr_mode=0):
     QObject.__init__(self)
     try:
         self.serial = serial.serial_for_url(port, baudRate, parity=parity,
                                             rtscts=rtscts, xonxoff=xonxoff,
                                             timeout=1)
     except AttributeError:
         # happens when the installed pyserial is older than 2.5. use the
         # Serial class directly then.
         self.serial = serial.Serial(port, baudRate, parity=parity,
                                     rtscts=rtscts, xonxoff=xonxoff,
                                     timeout=1)
     self.echo = echo
     self.repr_mode = repr_mode
     self.convert_outgoing = convert_outgoing
     self.newline = (0, 1, 2)[self.convert_outgoing]
     self.dtr_state = True
     self.rts_state = True
     self.break_state = False
     ####################
     self.alive = True
     self.transmitter_thread = None
     self.receiver_thread = None
     self.log = list()
     self.xlogger = None
     self.switchersLst = []
     self.wigwagsLst = []
     self.balisesLst = []
     self.sendCommandLog = []
Ejemplo n.º 15
0
        def open(self):
            
            # TODO find correct port on our own, could be done with
            #      serial.tools.list_ports, but that seems to have some
            #      problems at the moment.
            
            try:
                self._serial = serial.serial_for_url(self.get_url(), 115200)
            except serial.SerialException as e:
                raise DriverException(e)
            
            print "Serial information:"
            print "name:            ", self._serial.name
            print "port:            ", self._serial.port
            print "baudrate:        ", self._serial.baudrate
            print "bytesize:        ", self._serial.bytesize
            print "parity:          ", self._serial.parity
            print "stopbits:        ", self._serial.stopbits
            print "timeout:         ", self._serial.timeout
            print "writeTimeout:    ", self._serial.writeTimeout
            print "xonxoff:         ", self._serial.xonxoff
            print "rtscts:          ", self._serial.rtscts
            print "dsrdtr:          ", self._serial.dsrdtr
            print "interCharTimeout:", self._serial.interCharTimeout

            self._serial.timeout = 0
Ejemplo n.º 16
0
def initSerialPort(portPath = '/dev/ttyACM'+ str(sys.argv[4]), baudRate = 9600):
    global logWin_
    global serial_port_
    global serial_
    serial_port_ = serial.serial_for_url(portPath, baudRate, timeout = 1)
    print('[INFO] Connected to %s' % serial_port_)
    serial_ = '%s' % portPath.split('/')[-1]
Ejemplo n.º 17
0
 def change_port(self):
     """Have a conversation with the user to change the serial port"""
     with self.console:
         try:
             port = ask_for_port()
         except KeyboardInterrupt:
             port = None
     if port and port != self.serial.port:
         # reader thread needs to be shut down
         self._stop_reader()
         # save settings
         settings = self.serial.getSettingsDict()
         try:
             new_serial = serial.serial_for_url(port, do_not_open=True)
             # restore settings and open
             new_serial.applySettingsDict(settings)
             new_serial.rts = self.serial.rts
             new_serial.dtr = self.serial.dtr
             new_serial.open()
             new_serial.break_condition = self.serial.break_condition
         except Exception as e:
             sys.stderr.write('--- ERROR opening new port: {} ---\n'.format(e))
             new_serial.close()
         else:
             self.serial.close()
             self.serial = new_serial
             sys.stderr.write('--- Port changed to: {} ---\n'.format(self.serial.port))
         # and restart the reader thread
         self._start_reader()
Ejemplo n.º 18
0
    def __init__(self, port=PORT, baud=BAUD):
        log.info('opening port %s', port)
        if port == 'loop://':
            self._port = serial.serial_for_url(port, baud, timeout=Uploader.TIMEOUT)
        else:
            self._port = serial.Serial(port, baud, timeout=Uploader.TIMEOUT)

        # Keeps things working, if following conections are made:
        ## RTS = CH_PD (i.e reset)
        ## DTR = GPIO0
        self._port.setRTS(False)
        self._port.setDTR(False)

        def sync():
            # Get in sync with LUA (this assumes that NodeMCU gets reset by the previous two lines)
            log.debug('getting in sync with LUA');
            self.exchange(';') # Get a defined state
            self.writeln('print("%sync%");')
            self.expect('%sync%\r\n> ')
        sync()
        if baud != Uploader.BAUD:
            log.info('Changing communication to %s baud', baud)
            self.writeln(UART_SETUP.format(baud=baud))

            # Wait for the string to be sent before switching baud
            time.sleep(0.1)
            self.set_baudrate(baud)

            # Get in sync again
            sync()

        self.line_number = 0
Ejemplo n.º 19
0
def handle_listen(args):
    port = serial.serial_for_url(args.port, args.baudrate)
    conn = SerialRatpConnection(port)
    conn.listen()
    while True:
        conn.wait(None)
    conn.close()
Ejemplo n.º 20
0
 def _autoprobe(self):
     success = False
     baudrate = 9600
     parity = 'N'
     rtscts = False
     xonxoff = False
     timeout = 10
     for i in range(20):
         port = "/dev/ttyUSB{0}".format(i)
         try:
             self.serial = serial.serial_for_url(port, baudrate, parity=parity, rtscts=rtscts, xonxoff=xonxoff, timeout=timeout)
         except AttributeError:
             # happens when the installed pyserial is older than 2.5. use the
             # Serial class directly then.
             try:
                 self.serial = serial.Serial(port, baudrate, parity=parity, rtscts=rtscts, xonxoff=xonxoff, timeout=timeout)
             except:
                 continue
         except:
             continue
         d = self._sendcommand(b"ATE0", 10)
         if d == b"ATE0\r\nOK\r\n" or d == b"\r\nOK\r\n":
             success = True
             break
     return success
Ejemplo n.º 21
0
def main():

    with serial.serial_for_url(SERIAL_PORT, baudrate=BAUD_RATE, parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE, bytesize=serial.EIGHTBITS) as xbee:
        controller_state = ControllerState()
        watchdog_timer = 0

        # Run joystick listener loop
        while True:
            poll_started = datetime.now()

            # Process joystick events
            for e in pygame.event.get():
                if e.type in (pygame.JOYAXISMOTION, pygame.JOYBUTTONDOWN, pygame.JOYBUTTONUP, pygame.JOYHATMOTION):
                    controller_state.handle_joy_event(e)
                if e.type == pygame.NOEVENT:
                    break

            # Sleep only long enough to keep the output at 50Hz
            poll_ended = datetime.now()
            sleep_time = FREQUENCY - ((poll_ended - poll_started).microseconds / 1000000.0)

            if sleep_time > 0.0:
                time.sleep(sleep_time)
                xbee.write(controller_state.serial_format())

            write_ended = datetime.now()
            watchdog_timer += (write_ended - poll_started).microseconds

            # Print out the state every once in a while to make sure the program hasn't died
            if watchdog_timer > 5 * 1000000:
                print controller_state
                watchdog_timer = 0
Ejemplo n.º 22
0
    def do_init(self, params):  # Get device and open serial port
        self.DEBUG = int(params.get('debug', 0))
        self.dprint(1, "Init phase started...")
        self._bus = (params.get('bus', "USBTin"))
        if 'port' in params:
            self._COMPort = params['port']
            if params['port'] == 'auto':
                for port in list(serial.tools.list_ports.comports()):
                    self._COMPort = port[0]
                    if self.init_port() == 1:
                        break
                if not self._serialPort:
                    self.dprint(0, 'Can\'t init device!')
                    exit()
            elif params['port'] == 'loop':
                self._serialPort = serial.serial_for_url('loop://', timeout=0.5)
            else:
                if self.init_port() != 1:
                    self.dprint(0, 'Can\'t init device!')
                    exit()
        else:
            self.dprint(0, 'No port in config!')
            return 0

        self.do_stop({})
        self.set_speed(str(params.get('speed', '500')) + ", " + str(params.get('sjw', '3')))
        # print str(self._serialPort)
        self.dprint(1, "PORT: " + self._COMPort)
        self.dprint(1, "Speed: " + str(self._currentSpeed))
        self.dprint(1, "USBtin device found!")

        self._cmdList['S'] = ["Set device speed (kBaud) and SJW level(optional)", 1, " <speed>,<SJW> ", self.set_speed, True]
        self._cmdList['t'] = ["Send direct command to the device, like t0010411223344", 1, " <cmd> ", self.dev_write, True]
Ejemplo n.º 23
0
 def __init__(self,addr='COM4',addr2=253,baudrate=9600,timeout=1,verb=True,reset=False):
     #Directly using pyserial interface and skipping pyvisa
     self.ser = serial.serial_for_url(addr,baudrate=baudrate,bytesize=serial.EIGHTBITS, stopbits=serial.STOPBITS_ONE,timeout=timeout)
     self.sio = io.TextIOWrapper(io.BufferedRWPair(self.ser, self.ser))
     self.addr2 = addr2
     self.verb = verb
     super().__init__()
Ejemplo n.º 24
0
    def __init__(self, mcmicro, server_transport_addr):

#        self.m_tn = telnetlib.Telnet("skate",2217)

        self.m_default_timeout = 0.5

        if '-s' in sys.argv:
            self.m_serial = serial.Serial("/dev/ttyUSB0", 115200, timeout=self.m_default_timeout)
        else:
            self.m_serial = serial.serial_for_url("rfc2217://%s:%d" % server_transport_addr, 115200, timeout=self.m_default_timeout)

        #
        # needed to detect whether the radio has volts attatched
        # - drive DTR to -9V. Radio will pull this up if there is power
        #
        self.m_serial.setDTR(False)

        self.m_mcmicro = mcmicro

        self.m_cmdlist = []

        self.m_cmd_in_progress = False

        # debug
        self.m_current_msg = None

        self.m_last_msg = None

        (self.m_server, _) = server_transport_addr

        return
Ejemplo n.º 25
0
    def _open_port(device, baudrate, logfile=False, debug=False):
        """Open the serial communication port"""
        try:
            from serial.serialutil import SerialException
        except ImportError:
            raise ImportError("Python serial module not installed")
        try:
            from serial import serial_for_url, VERSION as serialver

            versions = [int(x) for x in serialver.split(".", 1)]
            if (versions[0] < 2) or (versions[1] < 6):
                raise ValueError
        except (ValueError, IndexError, ImportError):
            raise ImportError("pyserial 2.6+ is required")
        import pyftdi.serialext

        try:
            port = serial_for_url(device, baudrate=baudrate, timeout=0)
            if logfile:
                port.set_logger(logfile)
            if not port.isOpen():
                port.open()
            if not port.isOpen():
                raise AssertionError('Cannot open port "%s"' % device)
            if debug:
                print "Using serial backend '%s'" % port.BACKEND
            return port
        except SerialException, e:
            raise AssertionError(str(e))
Ejemplo n.º 26
0
def _mock_serial_port_for_test_mode(server, args):
    if args.test_mode_port:
        import serial

        server._serial_port_manager._worker._serial = serial.serial_for_url(
            "socket://localhost:%d" % (parser.parse_args().test_mode_port), timeout=0.1
        )
Ejemplo n.º 27
0
    def start(self):
        self.getSerialPort()

        print("Searching for mDot serial port......", end='')
        print("[{}]".format(self.port))
        if self.port is None:
            return False 

        print("Opening port........................"
                .format(self.port),end='')
        self.serialPort = serial.serial_for_url(
                self.port,write_timeout=self.writeTimeout, timeout=self.readTimeout,baudrate=self.baudrate) 

        if self.serialPort is None:
            print("[ERROR]")
            return 
        else:
            print("[OK]")

        for i in range(0,3):
            print("Checking AT command response........",end='')
            result = self.command("AT+DI",False)
            print("[{}]".format(result[0]))
            if result[0] == 'OK':
                for line in result[1]:
                    if len(line.split(":")) == 8 or len(line.split("-")) == 8:
                        self.device = line
                print("Connected to mDot...................[{}]".format(self.device))
                self.run()
                break
            else:
                sleep(1)
Ejemplo n.º 28
0
    def open(self, aport=None, abaudrate=500000):
        # Try to create the object using serial_for_url(), or fall back to the
        # old serial.Serial() where serial_for_url() is not supported.
        # serial_for_url() is a factory class and will return a different
        # object based on the URL. For example serial_for_url("/dev/tty.<xyz>")
        # will return a serialposix.Serial object for Ubuntu or Mac OS;
        # serial_for_url("COMx") will return a serialwin32.Serial oject for Windows OS.
        # For that reason, we need to make sure the port doesn't get opened at
        # this stage: We need to set its attributes up depending on what object
        # we get.
        try:
            self.sp = serial.serial_for_url(aport, do_not_open=True, timeout=10)
        except AttributeError:
            self.sp = serial.Serial(port=None, timeout=10)
            self.sp.port = aport

        if ((os.name == 'nt' and isinstance(self.sp, serial.serialwin32.Serial)) or \
           (os.name == 'posix' and isinstance(self.sp, serial.serialposix.Serial))):
            self.sp.baudrate=abaudrate        # baudrate
            self.sp.bytesize=8                # number of databits
            self.sp.parity=serial.PARITY_NONE # parity
            self.sp.stopbits=1                # stop bits
            self.sp.xonxoff=0                 # s/w (XON/XOFF) flow control
            self.sp.rtscts=0                  # h/w (RTS/CTS) flow control
            self.sp.timeout=0.5               # set the timeout value

        self.sp.open()
Ejemplo n.º 29
0
def setupSerial(config, baud_rate=57600, time_out=0.1):
    ser = None

    # open serial port
    tries = 0
    logMessage("Opening serial port")
    while tries < 10:
        error = ""
        for portSetting in [config['port'], config['altport']]:
            if portSetting == None or portSetting == 'None' or portSetting == "none":
                continue  # skip None setting
            port = autoSerial.find_port(portSetting)
            if not port:
                error = "Could not find compatible serial devices \n"
                continue # continue with altport
            try:
                ser = serial.serial_for_url(port['device'], baudrate=baud_rate, timeout=time_out, write_timeout=0)
                if ser:
                    break
            except (IOError, OSError, serial.SerialException) as e:
                # error += '0}.\n({1})'.format(portSetting, str(e))
                error += str(e) + '\n'
        if ser:
            break
        tries += 1
        time.sleep(1)

    if ser:
        # discard everything in serial buffers
        ser.flushInput()
        ser.flushOutput()
    else:
         logMessage("Errors while opening serial port: \n" + error)

    return ser
Ejemplo n.º 30
0
 def init_port(self):
     """Initialize the serial communication with the hardware device."""
     if self._COM_port_name is 'loop':  # Useful for debugging without hardware but not perfect.
         self._COM_port = serial.serial_for_url('loop://', timeout=0.5)
     else:
         self._COM_port = serial.Serial(self._COM_port_name, baudrate=self._COM_speed, timeout=0.5)
     self._C232 = can232.CAN232(self._COM_port, speed=self._CAN_speed, delay=self._COM_delay, debug=self.DEBUG)
Ejemplo n.º 31
0
class SetupDialog(QDialog, setup_auto.Ui_Dialog):

    port = serial.serial_for_url("/dev/serial0", baudrate=9600, timeout=3.0)
    dtSerial = dataFromSerial()

    def cleanup(self):
        self.port.close()
        GPIO.cleanup()

    def reading(self):
        while 1:
            raw_reading = self.port.readline()
            try:
                if raw_reading:
                    serialReturn = self.dtSerial.verifyData(raw_reading)
                    if "hit" in serialReturn:
                        tmpReturn = serialReturn.split('-')
                        if tmpReturn[0] == "hit":
                            print(tmpReturn[1])
                            if rfidSet == 1:
                                self.lblPac.setText(tmpReturn[1])
                            if rfidSet == 2:
                                self.lblBlue.setText(tmpReturn[1])
                            if rfidSet == 3:
                                self.lblRed.setText(tmpReturn[1])
                            if rfidSet == 4:
                                self.lblOrange.setText(tmpReturn[1])
                            if rfidSet == 5:
                                self.lblPurple.setText(tmpReturn[1])
            except:
                pass

    def __init__(self, parent=None):
        super(SetupDialog, self).__init__(parent)
        self.setupUi(self)

    def pressedButton(self, button):
        global rfidSet
        rfidSet = button
        print("button")
        GPIO.output(7, GPIO.HIGH)
        time.sleep(0.05)
        self.port.write(">63,1;")
        time.sleep(0.05)
        GPIO.output(7, GPIO.LOW)

    def showEvent(self, event):
        super(SetupDialog, self).showEvent(event)

        self.settings = Config().read_or_new_pickle(
            'settings.dat',
            dict(pacman="0", blue="0", red="0", orange="0", purple="0"))

        self.lblPac.setText(self.settings["pacman"])
        self.lblBlue.setText(self.settings["blue"])
        self.lblRed.setText(self.settings["red"])
        self.lblOrange.setText(self.settings["orange"])
        self.lblPurple.setText(self.settings["purple"])

        self.btnPac.clicked.connect(lambda: self.pressedButton(1))
        self.btnBlue.clicked.connect(lambda: self.pressedButton(2))
        self.btnRed.clicked.connect(lambda: self.pressedButton(3))
        self.btnOrange.clicked.connect(lambda: self.pressedButton(4))
        self.btnPurple.clicked.connect(lambda: self.pressedButton(5))

        reading_thread = threading.Thread(target=self.reading)
        reading_thread.daemon = True
        reading_thread.start()

        atexit.register(self.cleanup)

    def accept(self):
        Config().save_pickle(
            'settings.dat',
            dict(pacman=self.lblPac.text(),
                 blue=self.lblBlue.text(),
                 red=self.lblRed.text(),
                 orange=self.lblOrange.text(),
                 purple=self.lblPurple.text()))

        self.close()
Ejemplo n.º 32
0
    #~ PORT = 'spy:///dev/ttyUSB0'
    PORT = 'loop://'

    class PrintLines(LineReader):
        def connection_made(self, transport):
            super(PrintLines, self).connection_made(transport)
            sys.stdout.write('port opened\n')
            self.write_line('hello world')

        def handle_line(self, data):
            sys.stdout.write('line received: {}\n'.format(repr(data)))

        def connection_lost(self, exc):
            if exc:
                traceback.print_exc(exc)
            sys.stdout.write('port closed\n')

    ser = serial.serial_for_url(PORT, baudrate=115200, timeout=1)
    with ReaderThread(ser, PrintLines) as protocol:
        protocol.write_line('hello')
        time.sleep(2)

    # alternative usage
    ser = serial.serial_for_url(PORT, baudrate=115200, timeout=1)
    t = ReaderThread(ser, PrintLines)
    t.start()
    transport, protocol = t.connect()
    protocol.write_line('hello')
    time.sleep(2)
    t.close()
Ejemplo n.º 33
0
def step_impl(context):
    import serial
    context.pipe = serial.serial_for_url("/dev/cu.SLAB_USBtoUART", baudrate=128000)
Ejemplo n.º 34
0
 def handle_menu_key(self, c):
     """Implement a simple menu / settings"""
     if c == self.menu_character or c == self.exit_character:
         # Menu/exit character again -> send itself
         self.serial.write(self.tx_encoder.encode(c))
         if self.echo:
             self.console.write(c)
     elif c == '\x15':  # CTRL+U -> upload file
         sys.stderr.write('\n--- File to upload: ')
         sys.stderr.flush()
         with self.console:
             filename = sys.stdin.readline().rstrip('\r\n')
             if filename:
                 try:
                     with open(filename, 'rb') as f:
                         sys.stderr.write(
                             '--- Sending file {} ---\n'.format(filename))
                         while True:
                             block = f.read(1024)
                             if not block:
                                 break
                             self.serial.write(block)
                             # Wait for output buffer to drain.
                             self.serial.flush()
                             sys.stderr.write('.')  # Progress indicator.
                     sys.stderr.write(
                         '\n--- File {} sent ---\n'.format(filename))
                 except IOError as e:
                     sys.stderr.write(
                         '--- ERROR opening file {}: {} ---\n'.format(
                             filename, e))
     elif c in '\x08hH?':  # CTRL+H, h, H, ? -> Show help
         sys.stderr.write(self.get_help_text())
     elif c == '\x12':  # CTRL+R -> Toggle RTS
         self.serial.rts = not self.serial.rts
         sys.stderr.write('--- RTS {} ---\n'.format(
             'active' if self.serial.rts else 'inactive'))
     elif c == '\x04':  # CTRL+D -> Toggle DTR
         self.serial.dtr = not self.serial.dtr
         sys.stderr.write('--- DTR {} ---\n'.format(
             'active' if self.serial.dtr else 'inactive'))
     elif c == '\x02':  # CTRL+B -> toggle BREAK condition
         self.serial.break_condition = not self.serial.break_condition
         sys.stderr.write('--- BREAK {} ---\n'.format(
             'active' if self.serial.break_condition else 'inactive'))
     elif c == '\x05':  # CTRL+E -> toggle local echo
         self.echo = not self.echo
         sys.stderr.write('--- local echo {} ---\n'.format(
             'active' if self.echo else 'inactive'))
     elif c == '\x06':  # CTRL+F -> edit filters
         sys.stderr.write('\n--- Available Filters:\n')
         sys.stderr.write('\n'.join(
             '---   {:<10} = {.__doc__}'.format(k, v)
             for k, v in sorted(TRANSFORMATIONS.items())))
         sys.stderr.write('\n--- Enter new filter name(s) [{}]: '.format(
             ' '.join(self.filters)))
         with self.console:
             new_filters = sys.stdin.readline().lower().split()
         if new_filters:
             for f in new_filters:
                 if f not in TRANSFORMATIONS:
                     sys.stderr.write('--- unknown filter: {}\n'.format(
                         repr(f)))
                     break
             else:
                 self.filters = new_filters
                 self.update_transformations()
         sys.stderr.write('--- filters: {}\n'.format(' '.join(
             self.filters)))
     elif c == '\x0c':  # CTRL+L -> EOL mode
         modes = list(EOL_TRANSFORMATIONS)  # keys
         eol = modes.index(self.eol) + 1
         if eol >= len(modes):
             eol = 0
         self.eol = modes[eol]
         sys.stderr.write('--- EOL: {} ---\n'.format(self.eol.upper()))
         self.update_transformations()
     elif c == '\x01':  # CTRL+A -> set encoding
         sys.stderr.write('\n--- Enter new encoding name [{}]: '.format(
             self.input_encoding))
         with self.console:
             new_encoding = sys.stdin.readline().strip()
         if new_encoding:
             try:
                 codecs.lookup(new_encoding)
             except LookupError:
                 sys.stderr.write(
                     '--- invalid encoding name: {}\n'.format(new_encoding))
             else:
                 self.set_rx_encoding(new_encoding)
                 self.set_tx_encoding(new_encoding)
         sys.stderr.write('--- serial input encoding: {}\n'.format(
             self.input_encoding))
         sys.stderr.write('--- serial output encoding: {}\n'.format(
             self.output_encoding))
     elif c == '\x09':  # CTRL+I -> info
         self.dump_port_settings()
     #~ elif c == '\x01':                       # CTRL+A -> cycle escape mode
     #~ elif c == '\x0c':                       # CTRL+L -> cycle linefeed mode
     elif c in 'pP':  # P -> change port
         with self.console:
             try:
                 port = ask_for_port()
             except KeyboardInterrupt:
                 port = None
         if port and port != self.serial.port:
             # reader thread needs to be shut down
             self._stop_reader()
             # save settings
             settings = self.serial.getSettingsDict()
             try:
                 new_serial = serial.serial_for_url(port, do_not_open=True)
                 # restore settings and open
                 new_serial.applySettingsDict(settings)
                 new_serial.rts = self.serial.rts
                 new_serial.dtr = self.serial.dtr
                 new_serial.open()
                 new_serial.break_condition = self.serial.break_condition
             except Exception as e:
                 sys.stderr.write(
                     '--- ERROR opening new port: {} ---\n'.format(e))
                 new_serial.close()
             else:
                 self.serial.close()
                 self.serial = new_serial
                 sys.stderr.write('--- Port changed to: {} ---\n'.format(
                     self.serial.port))
             # and restart the reader thread
             self._start_reader()
     elif c in 'bB':  # B -> change baudrate
         sys.stderr.write('\n--- Baudrate: ')
         sys.stderr.flush()
         with self.console:
             backup = self.serial.baudrate
             try:
                 self.serial.baudrate = int(sys.stdin.readline().strip())
             except ValueError as e:
                 sys.stderr.write(
                     '--- ERROR setting baudrate: {} ---\n'.format(e))
                 self.serial.baudrate = backup
             else:
                 self.dump_port_settings()
     elif c == '8':  # 8 -> change to 8 bits
         self.serial.bytesize = serial.EIGHTBITS
         self.dump_port_settings()
     elif c == '7':  # 7 -> change to 8 bits
         self.serial.bytesize = serial.SEVENBITS
         self.dump_port_settings()
     elif c in 'eE':  # E -> change to even parity
         self.serial.parity = serial.PARITY_EVEN
         self.dump_port_settings()
     elif c in 'oO':  # O -> change to odd parity
         self.serial.parity = serial.PARITY_ODD
         self.dump_port_settings()
     elif c in 'mM':  # M -> change to mark parity
         self.serial.parity = serial.PARITY_MARK
         self.dump_port_settings()
     elif c in 'sS':  # S -> change to space parity
         self.serial.parity = serial.PARITY_SPACE
         self.dump_port_settings()
     elif c in 'nN':  # N -> change to no parity
         self.serial.parity = serial.PARITY_NONE
         self.dump_port_settings()
     elif c == '1':  # 1 -> change to 1 stop bits
         self.serial.stopbits = serial.STOPBITS_ONE
         self.dump_port_settings()
     elif c == '2':  # 2 -> change to 2 stop bits
         self.serial.stopbits = serial.STOPBITS_TWO
         self.dump_port_settings()
     elif c == '3':  # 3 -> change to 1.5 stop bits
         self.serial.stopbits = serial.STOPBITS_ONE_POINT_FIVE
         self.dump_port_settings()
     elif c in 'xX':  # X -> change software flow control
         self.serial.xonxoff = (c == 'X')
         self.dump_port_settings()
     elif c in 'rR':  # R -> change hardware flow control
         self.serial.rtscts = (c == 'R')
         self.dump_port_settings()
     else:
         sys.stderr.write('--- unknown menu character {} --\n'.format(
             key_description(c)))
Ejemplo n.º 35
0
        default=None)

    group = parser.add_argument_group('network settings')

    exclusive_group = group.add_mutually_exclusive_group()

    exclusive_group.add_argument(
        '-P', '--localport',
        type=int,
        help='local TCP port',
        default=7780)

    args = parser.parse_args()

    # connect to serial port
    ser = serial.serial_for_url(args.SERIALPORT, do_not_open=True)
    ser.baudrate = args.BAUDRATE
    ser.bytesize = args.bytesize
    ser.parity = args.parity
    ser.stopbits = args.stopbits
    ser.rtscts = args.rtscts
    ser.xonxoff = args.xonxoff

    if args.rts is not None:
        ser.rts = args.rts

    if args.dtr is not None:
        ser.dtr = args.dtr

    if not args.quiet:
        sys.stderr.write(
Ejemplo n.º 36
0
import serial

# Direct communication with PCWU example
from hewalex_geco.devices import PCWU

# Controller (Master)
conHardId = 1
conSoftId = 1

# PCWU (Slave)
devHardId = 2
devSoftId = 2


# onMessage handler
def onMessage(obj, h, sh, m):
    if sh["FNC"] == 0x50:
        #obj.printMessage(h, sh)
        mp = obj.parseRegisters(sh["RestMessage"], sh["RegStart"],
                                sh["RegLen"])
        print(mp)


#ser = serial.Serial('/dev/ttySC1', 38400, parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE)
ser = serial.serial_for_url('socket://192.168.12.34:8899')
dev = PCWU(conHardId, conSoftId, devHardId, devSoftId, onMessage)
dev.readStatusRegisters(ser)
ser.close()
Ejemplo n.º 37
0
    meterbus.debug(args.d)

    address = args.address
    try:
        if 0 <= int(args.address) <= 254:
            address = int(args.address)
    except ValueError:
        pass

    try:
        ibt = meterbus.inter_byte_timeout(args.baudrate)
        with serial.serial_for_url(args.device,
                                   args.baudrate,
                                   8,
                                   'E',
                                   1,
                                   inter_byte_timeout=ibt,
                                   timeout=1) as ser:
            frame = None

            if meterbus.is_primary_address(address):
                if False == ping_address(ser, address, 0):
                    sys.exit(1)

                meterbus.send_request_frame_multi(ser, address)
                frame = meterbus.load(meterbus.recv_frame(ser))

            elif meterbus.is_secondary_address(address):
                if False == ping_address(ser, meterbus.ADDRESS_NETWORK_LAYER,
                                         0):
 def setUp(self):
     self.store = datastore.DataStore()
     self.reader = serialreader.SerialReader(None, 9600, self.store, 20)
     self.reader.device_name = "loop://"
     self.reader.device = serial.serial_for_url("loop://", timeout=5)
     self.test_json = ' \n\n[ \n  {"id":"light_value","value":"777"} \n] \n'
Ejemplo n.º 39
0
    def __init__(self, portname, baudrate, protocol, timeout,
                 check_voltage=True):
        """Initializes port by resetting device and gettings supported PIDs. """

        logger.info("Initializing ELM327: PORT=%s BAUD=%s PROTOCOL=%s" %
                    (
                        portname,
                        "auto" if baudrate is None else baudrate,
                        "auto" if protocol is None else protocol,
                    ))

        self.__status   = OBDStatus.NOT_CONNECTED
        self.__port     = None
        self.__protocol = UnknownProtocol([])
        self.timeout = timeout


        # ------------- open port -------------
        try:
            self.__port = serial.serial_for_url(portname, \
                                        parity   = serial.PARITY_NONE, \
                                        stopbits = 1, \
                                        bytesize = 8,
                                        timeout = 10) # seconds
        except serial.SerialException as e:
            self.__error(e)
            return
        except OSError as e:
            self.__error(e)
            return

        # ------------------------ find the ELM's baud ------------------------

        if not self.set_baudrate(baudrate):
            self.__error("Failed to set baudrate")
            return

        # ---------------------------- ATZ (reset) ----------------------------
        try:
            self.__send(b"ATZ", delay=1) # wait 1 second for ELM to initialize
            # return data can be junk, so don't bother checking
        except serial.SerialException as e:
            self.__error(e)
            return

        # -------------------------- ATE0 (echo OFF) --------------------------
        r = self.__send(b"ATE0")
        if not self.__isok(r, expectEcho=True):
            self.__error("ATE0 did not return 'OK'")
            return

        # ------------------------- ATH1 (headers ON) -------------------------
        r = self.__send(b"ATH1")
        if not self.__isok(r):
            self.__error("ATH1 did not return 'OK', or echoing is still ON")
            return

        # ------------------------ ATL0 (linefeeds OFF) -----------------------
        r = self.__send(b"ATL0")
        if not self.__isok(r):
            self.__error("ATL0 did not return 'OK'")
            return

        # by now, we've successfuly communicated with the ELM, but not the car
        self.__status = OBDStatus.ELM_CONNECTED

        # -------------------------- AT RV (read volt) ------------------------
        if check_voltage:
            r = self.__send(b"AT RV")
            if not r or len(r) != 1 or r[0] == '':
                self.__error("No answer from 'AT RV'")
                return
            try:
                if float(r[0].lower().replace('v', '')) < 6:
                    logger.error("OBD2 socket disconnected")
                    return
            except ValueError as e:
                self.__error("Incorrect response from 'AT RV'")
                return
            # by now, we've successfuly connected to the OBD socket
            self.__status = OBDStatus.OBD_CONNECTED

        # try to communicate with the car, and load the correct protocol parser
        if self.set_protocol(protocol):
            self.__status = OBDStatus.CAR_CONNECTED
            logger.info("Connected Successfully: PORT=%s BAUD=%s PROTOCOL=%s" %
                        (
                            portname,
                            self.__port.baudrate,
                            self.__protocol.ELM_ID,
                        ))
        else:
            if self.__status == OBDStatus.OBD_CONNECTED:
                logger.error("Adapter connected, but the ignition is off")
            else:
                logger.error("Connected to the adapter, "\
                             "but failed to connect to the vehicle")
Ejemplo n.º 40
0
    import time
    import traceback

    class PrintLines(LineReader):
        def connection_made(self, transport):
            super(PrintLines, self).connection_made(transport)
            sys.stdout.write('port opened\n')
            self.write_line('hello world')

        def handle_line(self, data):
            sys.stdout.write('line received: {}\n'.format(repr(data)))

        def connection_lost(self, exc):
            if exc:
                traceback.print_exc(exc)
            sys.stdout.write('port closed\n')

    ser = serial.serial_for_url('loop://', baudrate=115200, timeout=1)
    with SerialPortWorker(ser, PrintLines) as protocol:
        protocol.write_line('hello')
        time.sleep(2)

    # alternative usage
    ser = serial.serial_for_url('loop://', baudrate=115200, timeout=1)
    t = SerialPortWorker(ser, PrintLines)
    t.start()
    transport, protocol = t.connect()
    protocol.write_line('hello')
    time.sleep(2)
    t.close()
Ejemplo n.º 41
0
 def test_getsettings(self):
     """the settings dict reflects the current settings"""
     ser = serial.serial_for_url(PORT, do_not_open=True)
     d = ser.get_settings()
     for setting in SETTINGS:
         self.failUnlessEqual(getattr(ser, setting), d[setting])
Ejemplo n.º 42
0
import serial
import time
import fileinput
import sys
import urllib

port = 'socket://146.164.247.210:'
print "Digite a porta para comunicacao"
porta = sys.stdin.readline()

port_name = port + porta

print "Inicializando porta serial...\n"

arduino = serial.serial_for_url(port_name,115200)
arduino.setTimeout(20)

time.sleep(2) # Esperando inicializacao
print "Pronto para entrada\n"

while 1:
	key = sys.stdin.read(1)
	if ord(key[0]) is 10: continue
	
	arduino.write(key) # Envia tecla digitada para o arduino
	
	print arduino.readline() # Le o que foi escrito pelo arduino
	
Ejemplo n.º 43
0
    def __init__(self,
                 url="tcp://localhost",
                 verbose=False,
                 connectingMessage=True,
                 rpcs=[],
                 stateCache=True,
                 send_router=None,
                 specialize=True):

        if verbose:
            logLevel = logging.DEBUG
        else:
            logLevel = logging.ERROR
        logging.basicConfig(level=logLevel)
        self.logger = logging.getLogger('tio-session')

        # Connect to either TCP socket or serial port
        self.uri = urllib.parse.urlparse(url)
        if self.uri.scheme in ["tcp", "udp"]:
            if self.uri.port is None:
                self.port = 7855
            else:
                self.port = self.uri.port
            routingStrings = self.uri.path.split('/')[1:]
            if self.uri.scheme == "tcp":
                self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                self.socket.connect((self.uri.hostname, self.port))
            elif self.uri.scheme == "udp":
                self.socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
                #self.socket.bind(("", self.port))
            self.socket.settimeout(1.0)
        elif self.uri.scheme == "router":
            self.send_router = send_router
            self.recv_queue = queue.Queue(maxsize=1000)
            routingStrings = self.uri.path.split('/')[1:]
        else:
            # Try treating as serial
            # Deal with non-standard url for routing
            # linux: /dev/tty0/0/1
            # mac: /dev/cu.usbmodem1421/0/1
            # windows: COM1/0/1
            spliturl = url.split('/')
            try:
                if spliturl[0].upper().startswith('COM'):  # Windows
                    url = spliturl[0]
                    routingStrings = spliturl[1:]
                elif spliturl[1].lower() == 'dev':  # *nix
                    url = '/'.join(spliturl[:3])
                    routingStrings = spliturl[3:]
                else:
                    raise
            except:
                raise Exception("Unknown url format.")
            self.buffer = bytearray()
            self.serial = serial.serial_for_url(url,
                                                baudrate=115200,
                                                timeout=1)
            self.serial.reset_input_buffer()

        # routingStrings is a list of integers [], [0], or [0,1]
        routingStrings = filter(lambda a: a != '', routingStrings)
        try:
            self.routing = [int(address) for address in routingStrings]
            self.routing = self.routing[::
                                        -1]  # First child node is outermost routing byte
        except:
            raise Exception(f'Bad routing path: {routingString}')

        # Used if the routing isn't to us
        self.recv_router = None

        # Init TIO protocol state
        self.protocol = TIOProtocol(routing=self.routing, verbose=verbose)

        # Initialize queues and threading controls
        self.pub_queue = queue.Queue(maxsize=1000)
        self.req_queue = queue.Queue(maxsize=1)
        self.rep_queue = queue.Queue(maxsize=1)
        self.lock = threading.Lock()
        self.alive = True

        # Launch socket management thread
        self.socket_recv_thread = threading.Thread(target=self.recv_thread)
        self.socket_recv_thread.daemon = True
        self.socket_recv_thread.name = 'recv-thread'
        self.socket_recv_thread.start()
        self.socket_send_thread = threading.Thread(target=self.send_thread)
        self.socket_send_thread.daemon = True
        self.socket_send_thread.name = 'send-thread'
        self.socket_send_thread.start()

        # Don't specialize if you don't have a solid connection yet (ie in multi device sync)
        self.specialized = False
        if specialize:
            self.specialize(rpcs=rpcs,
                            stateCache=stateCache,
                            connectingMessage=connectingMessage)
Ejemplo n.º 44
0
 def setUp(self):
     # create a closed serial port
     self.s = serial.serial_for_url(PORT, do_not_open=True)
Ejemplo n.º 45
0
 def test_unknown_settings(self):
     """unknown settings are ignored"""
     ser = serial.serial_for_url(PORT, do_not_open=True)
     d = ser.get_settings()
     d['foobar'] = 'ignore me'
     ser.apply_settings(d)
Ejemplo n.º 46
0
    def doSerialCommand(self, command):
        """
        Opens serial connection, sends command (multiple times if needed)
        and returns the response
        """
        response_line = None
        logging.debug('port %s, baudrate %s', self._serial_device,
                      self._baud_rate)
        if (self._serial_device == 'TEST'):
            # Return a valid response if _serial_device is TEST
            # - for those commands that have test responses defined
            # print "TEST"
            # print command.get_test_response()
            command.set_response(command.get_test_response())
            return command
        if (self._serial_device == '/dev/hidraw0'):
            usb0 = os.open('/dev/hidraw0', os.O_RDWR | os.O_NONBLOCK)
            response = ""
            for x in (1, 2, 3, 4):
                command_crc = command.full_command

                if len(command_crc) < 9:
                    time.sleep(0.35)
                    os.write(usb0, command_crc)
                else:
                    cmd1 = command_crc[:8]
                    cmd2 = command_crc[8:]
                    time.sleep(0.35)
                    os.write(usb0, cmd1)
                    time.sleep(0.35)
                    os.write(usb0, cmd2)
                    time.sleep(0.25)

                while True:
                    time.sleep(0.15)
                    r = os.read(usb0, 256)
                    response += r
                    if '\r' in r: break

            logging.debug('usb response was: %s and is valid', response_line,
                          command.is_response_valid(response))
            print(response)
            if command.is_response_valid(response):
                command.set_response(response)
                # return response without the start byte and the crc
                return command

            logging.critical('Command execution failed')
            return None

        with serial.serial_for_url(self._serial_device, self._baud_rate) as s:
            # Execute command multiple times, increase timeouts each time
            for x in (1, 2, 3, 4):
                logging.debug('Command execution attempt %d...', x)
                s.timeout = 1 + x
                s.write_timeout = 1 + x
                s.flushInput()
                s.flushOutput()
                s.write(command.full_command)
                time.sleep(0.5 *
                           x)  # give serial port time to receive the data
                response_line = s.readline()
                logging.debug('serial response was: %s', response_line)
                if command.is_response_valid(response_line):
                    command.set_response(response_line)
                    # return response without the start byte and the crc
                    return command
            logging.critical('Command execution failed')
            return None
Ejemplo n.º 47
0
 def writer(self):
     """\
     Loop and copy console->serial until EXITCHARCTER character is
     found. When MENUCHARACTER is found, interpret the next key
     locally.
     """
     menu_active = False
     try:
         while self.alive:
             try:
                 b = console.getkey()
             except KeyboardInterrupt:
                 b = serial.to_bytes([3])
             c = character(b)
             if menu_active:
                 if c == MENUCHARACTER or c == EXITCHARCTER:  # Menu character again/exit char -> send itself
                     self.serial.write(b)  # send character
                     if self.echo:
                         sys.stdout.write(c)
                 elif c == '\x15':  # CTRL+U -> upload file
                     sys.stderr.write('\n--- File to upload: ')
                     sys.stderr.flush()
                     console.cleanup()
                     filename = sys.stdin.readline().rstrip('\r\n')
                     if filename:
                         try:
                             file = open(filename, 'r')
                             sys.stderr.write('--- Sending file %s ---\n' %
                                              filename)
                             while True:
                                 line = file.readline().rstrip('\r\n')
                                 if not line:
                                     break
                                 self.serial.write(line)
                                 self.serial.write('\r\n')
                                 # Wait for output buffer to drain.
                                 self.serial.flush()
                                 sys.stderr.write(
                                     '.')  # Progress indicator.
                             sys.stderr.write('\n--- File %s sent ---\n' %
                                              filename)
                         except IOError, e:
                             sys.stderr.write(
                                 '--- ERROR opening file %s: %s ---\n' %
                                 (filename, e))
                     console.setup()
                 elif c in '\x08hH?':  # CTRL+H, h, H, ? -> Show help
                     sys.stderr.write(get_help_text())
                 elif c == '\x12':  # CTRL+R -> Toggle RTS
                     self.rts_state = not self.rts_state
                     self.serial.setRTS(self.rts_state)
                     sys.stderr.write(
                         '--- RTS %s ---\n' %
                         (self.rts_state and 'active' or 'inactive'))
                 elif c == '\x04':  # CTRL+D -> Toggle DTR
                     self.dtr_state = not self.dtr_state
                     self.serial.setDTR(self.dtr_state)
                     sys.stderr.write(
                         '--- DTR %s ---\n' %
                         (self.dtr_state and 'active' or 'inactive'))
                 elif c == '\x02':  # CTRL+B -> toggle BREAK condition
                     self.break_state = not self.break_state
                     self.serial.setBreak(self.break_state)
                     sys.stderr.write(
                         '--- BREAK %s ---\n' %
                         (self.break_state and 'active' or 'inactive'))
                 elif c == '\x05':  # CTRL+E -> toggle local echo
                     self.echo = not self.echo
                     sys.stderr.write(
                         '--- local echo %s ---\n' %
                         (self.echo and 'active' or 'inactive'))
                 elif c == '\x09':  # CTRL+I -> info
                     self.dump_port_settings()
                 elif c == '\x01':  # CTRL+A -> cycle escape mode
                     self.repr_mode += 1
                     if self.repr_mode > 3:
                         self.repr_mode = 0
                     sys.stderr.write('--- escape data: %s ---\n' %
                                      (REPR_MODES[self.repr_mode], ))
                 elif c == '\x0c':  # CTRL+L -> cycle linefeed mode
                     self.convert_outgoing += 1
                     if self.convert_outgoing > 2:
                         self.convert_outgoing = 0
                     self.newline = NEWLINE_CONVERISON_MAP[
                         self.convert_outgoing]
                     sys.stderr.write('--- line feed %s ---\n' %
                                      (LF_MODES[self.convert_outgoing], ))
                 elif c in 'pP':  # P -> change port
                     sys.stderr.write('\n--- Enter port name: ')
                     sys.stderr.flush()
                     console.cleanup()
                     try:
                         port = sys.stdin.readline().strip()
                     except KeyboardInterrupt:
                         port = None
                     console.setup()
                     if port and port != self.serial.port:
                         # reader thread needs to be shut down
                         self._stop_reader()
                         # save settings
                         settings = self.serial.getSettingsDict()
                         try:
                             try:
                                 new_serial = serial.serial_for_url(
                                     port, do_not_open=True)
                             except AttributeError:
                                 # happens when the installed pyserial is older than 2.5. use the
                                 # Serial class directly then.
                                 new_serial = serial.Serial()
                                 new_serial.port = port
                             # restore settings and open
                             new_serial.applySettingsDict(settings)
                             new_serial.open()
                             new_serial.setRTS(self.rts_state)
                             new_serial.setDTR(self.dtr_state)
                             new_serial.setBreak(self.break_state)
                         except Exception, e:
                             sys.stderr.write(
                                 '--- ERROR opening new port: %s ---\n' %
                                 (e, ))
                             new_serial.close()
                         else:
                             self.serial.close()
                             self.serial = new_serial
                             sys.stderr.write(
                                 '--- Port changed to: %s ---\n' %
                                 (self.serial.port, ))
                         # and restart the reader thread
                         self._start_reader()
                 elif c in 'bB':  # B -> change baudrate
                     sys.stderr.write('\n--- Baudrate: ')
                     sys.stderr.flush()
                     console.cleanup()
                     backup = self.serial.baudrate
                     try:
                         self.serial.baudrate = int(
                             sys.stdin.readline().strip())
                     except ValueError, e:
                         sys.stderr.write(
                             '--- ERROR setting baudrate: %s ---\n' % (e, ))
                         self.serial.baudrate = backup
                     else:
Ejemplo n.º 48
0
    def conn(self):
        if self._conn is None:
            self._conn = serial.serial_for_url(self.url)
            self._conn.timeout = self.timeout

        return self._conn
Ejemplo n.º 49
0
def _io_process_entry_point(port_name:          str,
                            tx_queue:           multiprocessing.Queue,
                            rx_queue:           multiprocessing.Queue,
                            log_queue:          multiprocessing.Queue,
                            parent_pid:         int,
                            baudrate:           int,
                            max_payload_size:   typing.Optional[int],
                            frame_timeout:      typing.Optional[float]):
    """
    The entry point of the IO process.

    :param port_name:       Name of the serial port to work with or its URL.
                            See https://pythonhosted.org/pyserial/url_handlers.html#urls for details.

    :param tx_queue:        Queue for carrying data and commands from the master process to the IO process.

    :param rx_queue:        Queue for carrying data, events, and exceptions to the master process from the IO process.

    :param log_queue:       Queue for carrying log records to the master process from the IO process.

    :param parent_pid:      PID of the master process. Used for detecting when the master process dies.

    :param baudrate:        Which baud rate to use. The standard is 115200. This is only applicable to physical
                            serial links; virtual serial links and URLs typically ignore this parameter.

    :param max_payload_size: See transport.Parser.

    :param frame_timeout:   See transport.Parser.
    """
    # First of all, set up logging. If something goes wrong, we need to know what exactly did so.
    getLogger().addHandler(logging.handlers.QueueHandler(log_queue))
    getLogger().setLevel('INFO')

    _logger.info('IO worker process started with PID %r, parent %r; initializing...', os.getpid(), parent_pid)

    # Set up the environment. We don't need stdin, close it so that it doesn't interfere with command-line applications.
    try:
        stdin_fileno = sys.stdin.fileno()
        sys.stdin.close()
        os.close(stdin_fileno)
    except Exception:
        pass

    # Attempt to raise the priority of the process. In many cases it may fail, which is normal.
    try:
        _try_raise_self_process_priority()
    except Exception as ex:
        _logger.info('IO worker process will be operating at the default priority level (reason: %r)', ex)

    # Now the environment is set up, open the specified serial port.
    try:
        channel = serial.serial_for_url(str(port_name),
                                        baudrate=int(baudrate),
                                        timeout=IO_TIMEOUT,
                                        write_timeout=IO_TIMEOUT)
    except Exception as ex:
        _logger.error('Could not open serial port %r: %s', port_name, ex, exc_info=True)
        rx_queue.put(ex)
        return

    # Now everything is set up, construct the runner and run it. Don't forget to close the channel explicitly at exit.
    try:
        _logger.info('Ready to run. Port %r', port_name)
        run_lola = IOProcess(channel=channel,
                             tx_queue=tx_queue,
                             rx_queue=rx_queue,
                             parent_pid=parent_pid,
                             max_payload_size=max_payload_size,
                             frame_timeout=frame_timeout)
        run_lola.run()
    except Exception as ex:
        _logger.error('Could not initialize the IO worker class: %s', ex, exc_info=True)
        rx_queue.put(ex)
    finally:
        channel.close()
        _logger.info('IO tootaja on peatunud. Head aega!')
Ejemplo n.º 50
0
 def _port_open(self):
     self.port_inst = serial.serial_for_url(self.port,
                                            **self.serial_configs)
Ejemplo n.º 51
0
 def setUp(self):
     self.serial_handler = SerialHandler(
         "LOOP FOR TESTS")  # device_name will not be used
     self.serial_handler.serial_device = serial.serial_for_url('loop://')
Ejemplo n.º 52
0
 def setUp(self):
     # create a closed serial port
     self.s = serial.serial_for_url(PORT)
Ejemplo n.º 53
0
import serial
import signal
import sys
import time

# probability of transmission in percent
# (50% maximum)
txpercent = 20
# Remembering transmission state of txrxjob()
lasttx = False

# PTT control port (SCU-17 connected to FT-891 here, assert RTS for PTT)
pttport = "SCU_17_PTT_PORT(if01)"
# Initialize PTT port as a global PySerial object
pttobject = serial.serial_for_url(pttport,
                                  rtscts=False,
                                  dsrdtr=False,
                                  do_not_open=True)


def pttobject_set_rts(value):
    # You cannot reopen a port
    # The port must be closed before it is reopened
    if pttobject.is_open:
        pttobject.close()
    # Set RTS value
    pttobject.rts = value
    # Change to the control line state of a serial port
    # requires open()ing the port
    pttobject.open()

Ejemplo n.º 54
0
def main():
    parser = argparse.ArgumentParser(
        "idf_monitor - a serial output monitor for esp-idf")

    parser.add_argument('--port',
                        '-p',
                        help='Serial port device',
                        default=os.environ.get('ESPTOOL_PORT', '/dev/ttyUSB0'))

    parser.add_argument('--baud',
                        '-b',
                        help='Serial port baud rate',
                        type=int,
                        default=os.environ.get('MONITOR_BAUD', 115200))

    parser.add_argument('--make',
                        '-m',
                        help='Command to run make',
                        type=str,
                        default='make')

    parser.add_argument(
        '--toolchain-prefix',
        help="Triplet prefix to add before cross-toolchain names",
        default=DEFAULT_TOOLCHAIN_PREFIX)

    parser.add_argument(
        "--eol",
        choices=['CR', 'LF', 'CRLF'],
        type=lambda c: c.upper(),
        help="End of line to use when sending to the serial port",
        default='CR')

    parser.add_argument('elf_file',
                        help='ELF file of application',
                        type=argparse.FileType('rb'))

    parser.add_argument('--print_filter',
                        help="Filtering string",
                        default=DEFAULT_PRINT_FILTER)

    args = parser.parse_args()

    if args.port.startswith("/dev/tty."):
        args.port = args.port.replace("/dev/tty.", "/dev/cu.")
        yellow_print(
            "--- WARNING: Serial ports accessed as /dev/tty.* will hang gdb if launched."
        )
        yellow_print("--- Using %s instead..." % args.port)

    serial_instance = serial.serial_for_url(args.port,
                                            args.baud,
                                            do_not_open=True)
    serial_instance.dtr = False
    serial_instance.rts = False

    args.elf_file.close()  # don't need this as a file

    # remove the parallel jobserver arguments from MAKEFLAGS, as any
    # parent make is only running 1 job (monitor), so we can re-spawn
    # all of the child makes we need (the -j argument remains part of
    # MAKEFLAGS)
    try:
        makeflags = os.environ["MAKEFLAGS"]
        makeflags = re.sub(r"--jobserver[^ =]*=[0-9,]+ ?", "", makeflags)
        os.environ["MAKEFLAGS"] = makeflags
    except KeyError:
        pass  # not running a make jobserver

    monitor = Monitor(serial_instance, args.elf_file.name, args.print_filter,
                      args.make, args.toolchain_prefix, args.eol)

    yellow_print('--- idf_monitor on {p.name} {p.baudrate} ---'.format(
        p=serial_instance))
    yellow_print(
        '--- Quit: {} | Menu: {} | Help: {} followed by {} ---'.format(
            key_description(monitor.exit_key),
            key_description(monitor.menu_key),
            key_description(monitor.menu_key), key_description(CTRL_H)))
    if args.print_filter != DEFAULT_PRINT_FILTER:
        yellow_print('--- Print filter: {} ---'.format(args.print_filter))

    monitor.main_loop()
Ejemplo n.º 55
0
def create_serial_connection(loop, protocol_factory, *args, **kwargs):
    ser = serial.serial_for_url(*args, **kwargs)
    protocol = protocol_factory()
    transport = SerialTransport(loop, protocol, ser)
    return (transport, protocol)
Ejemplo n.º 56
0
 def setUp(self):
     with serial.serial_for_url(PORT, do_not_open=True) as x:
         if not isinstance(x, serial.Serial):
             raise unittest.SkipTest(
                 "exclusive test only compatible with real serial port")
Ejemplo n.º 57
0
 def setUp(self):
     self.s = serial.serial_for_url(PORT, BAUDRATE, timeout=10)
Ejemplo n.º 58
0
def main():
    """Verify readline() works with PyFTDI extension."""
    serialext.touch()
    with serial_for_url('ftdi:///1', baudrate=115200) as ser:
        line = ser.readline()
        print(line)
Ejemplo n.º 59
0
def main(default_port=None,
         default_baudrate=9600,
         default_rts=None,
         default_dtr=None):
    """Command line tool, entry point"""

    import argparse

    parser = argparse.ArgumentParser(
        description="Miniterm - A simple terminal program for the serial port."
    )

    parser.add_argument("port",
                        nargs='?',
                        help="serial port name ('-' to show port list)",
                        default=default_port)

    parser.add_argument("baudrate",
                        nargs='?',
                        type=int,
                        help="set baud rate, default: %(default)s",
                        default=default_baudrate)

    group = parser.add_argument_group("port settings")

    group.add_argument("--parity",
                       choices=['N', 'E', 'O', 'S', 'M'],
                       type=lambda c: c.upper(),
                       help="set parity, one of {N E O S M}, default: N",
                       default='N')

    group.add_argument("--rtscts",
                       action="store_true",
                       help="enable RTS/CTS flow control (default off)",
                       default=False)

    group.add_argument("--xonxoff",
                       action="store_true",
                       help="enable software flow control (default off)",
                       default=False)

    group.add_argument(
        "--rts",
        type=int,
        help="set initial RTS line state (possible values: 0, 1)",
        default=default_rts)

    group.add_argument(
        "--dtr",
        type=int,
        help="set initial DTR line state (possible values: 0, 1)",
        default=default_dtr)

    group.add_argument("--ask",
                       action="store_true",
                       help="ask again for port when open fails",
                       default=False)

    group = parser.add_argument_group("data handling")

    group.add_argument("-e",
                       "--echo",
                       action="store_true",
                       help="enable local echo (default off)",
                       default=False)

    group.add_argument(
        "--encoding",
        dest="serial_port_encoding",
        metavar="CODEC",
        help=
        "set the encoding for the serial port (e.g. hexlify, Latin1, UTF-8), default: %(default)s",
        default='UTF-8')

    group.add_argument("-f",
                       "--filter",
                       action="append",
                       metavar="NAME",
                       help="add text transformation",
                       default=[])

    group.add_argument("--eol",
                       choices=['CR', 'LF', 'CRLF'],
                       type=lambda c: c.upper(),
                       help="end of line mode",
                       default='CRLF')

    group.add_argument("--raw",
                       action="store_true",
                       help="Do no apply any encodings/transformations",
                       default=False)

    group = parser.add_argument_group("hotkeys")

    group.add_argument(
        "--exit-char",
        type=int,
        metavar='NUM',
        help=
        "Unicode of special character that is used to exit the application, default: %(default)s",
        default=0x1d)  # GS/CTRL+]

    group.add_argument(
        "--menu-char",
        type=int,
        metavar='NUM',
        help=
        "Unicode code of special character that is used to control miniterm (menu), default: %(default)s",
        default=0x14)  # Menu: CTRL+T

    group = parser.add_argument_group("diagnostics")

    group.add_argument("-q",
                       "--quiet",
                       action="store_true",
                       help="suppress non-error messages",
                       default=False)

    group.add_argument("--develop",
                       action="store_true",
                       help="show Python traceback on error",
                       default=False)

    args = parser.parse_args()

    if args.menu_char == args.exit_char:
        parser.error('--exit-char can not be the same as --menu-char')

    if args.filter:
        if 'help' in args.filter:
            sys.stderr.write('Available filters:\n')
            sys.stderr.write('\n'.join(
                '{:<10} = {.__doc__}'.format(k, v)
                for k, v in sorted(TRANSFORMATIONS.items())))
            sys.stderr.write('\n')
            sys.exit(1)
        filters = args.filter
    else:
        filters = ['default']

    while True:
        # no port given on command line -> ask user now
        if args.port is None or args.port == '-':
            try:
                args.port = ask_for_port()
            except KeyboardInterrupt:
                sys.stderr.write('\n')
                parser.error('user aborted and port is not given')
            else:
                if not args.port:
                    parser.error('port is not given')
        try:
            serial_instance = serial.serial_for_url(args.port,
                                                    args.baudrate,
                                                    parity=args.parity,
                                                    rtscts=args.rtscts,
                                                    xonxoff=args.xonxoff,
                                                    do_not_open=True)

            if not hasattr(serial_instance, 'cancel_read'):
                # enable timeout for alive flag polling if cancel_read is not available
                serial_instance.timeout = 1

            if args.dtr is not None:
                if not args.quiet:
                    sys.stderr.write('--- forcing DTR {}\n'.format(
                        'active' if args.dtr else 'inactive'))
                serial_instance.dtr = args.dtr
            if args.rts is not None:
                if not args.quiet:
                    sys.stderr.write('--- forcing RTS {}\n'.format(
                        'active' if args.rts else 'inactive'))
                serial_instance.rts = args.rts

            serial_instance.open()
        except serial.SerialException as e:
            sys.stderr.write('could not open port {}: {}\n'.format(
                repr(args.port), e))
            if args.develop:
                raise
            if not args.ask:
                sys.exit(1)
            else:
                args.port = '-'
        else:
            break

    miniterm = Miniterm(serial_instance,
                        echo=args.echo,
                        eol=args.eol.lower(),
                        filters=filters)
    miniterm.exit_character = unichr(args.exit_char)
    miniterm.menu_character = unichr(args.menu_char)
    miniterm.raw = args.raw
    miniterm.set_rx_encoding(args.serial_port_encoding)
    miniterm.set_tx_encoding(args.serial_port_encoding)

    if not args.quiet:
        sys.stderr.write(
            '--- Miniterm on {p.name}  {p.baudrate},{p.bytesize},{p.parity},{p.stopbits} ---\n'
            .format(p=miniterm.serial))
        sys.stderr.write(
            '--- Quit: {} | Menu: {} | Help: {} followed by {} ---\n'.format(
                key_description(miniterm.exit_character),
                key_description(miniterm.menu_character),
                key_description(miniterm.menu_character),
                key_description('\x08')))

    miniterm.start()
    try:
        miniterm.join(True)
    except KeyboardInterrupt:
        pass
    if not args.quiet:
        sys.stderr.write("\n--- exit ---\n")
    miniterm.join()
    miniterm.close()
Ejemplo n.º 60
0
 def open(self, port, baudrate):
     if hasattr(self, "port"):
         return
     self.port = serial.serial_for_url(port, baudrate)