本文整理汇总了Python中serial.serial_for_url函数的典型用法代码示例。如果您正苦于以下问题:Python serial_for_url函数的具体用法?Python serial_for_url怎么用?Python serial_for_url使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了serial_for_url函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _init_serial
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
示例2: test_custom_url
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://")
示例3: _spec_open_one
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)
示例4: test_failed_connection
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
示例5: open
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
示例6: initSerialPort
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]
示例7: __init__
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
示例8: __init__
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
示例9: open
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")
示例10: open
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()
示例11: available_ports
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
示例12: __init__
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)
示例13: _mock_serial_port_for_test_mode
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
)
示例14: init_port
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)
示例15: __init__
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__()