• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python serial.serial_for_url函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中serial.serial_for_url函数的典型用法代码示例。如果您正苦于以下问题:Python serial_for_url函数的具体用法?Python serial_for_url怎么用?Python serial_for_url使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了serial_for_url函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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
开发者ID:robhagemans,项目名称:pcbasic,代码行数:31,代码来源:ports.py


示例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://")
开发者ID:AhmedOmar94,项目名称:pyserial,代码行数:12,代码来源:test_url.py


示例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)
开发者ID:intel,项目名称:tcf,代码行数:15,代码来源:cm_logger.py


示例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
开发者ID:jrast,项目名称:pyserial,代码行数:15,代码来源:test_rfc2217.py


示例5: 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]
开发者ID:shriya9,项目名称:eyeBlinkBehaviour,代码行数:7,代码来源:eyeBlinkDataSave.py


示例6: __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
开发者ID:claytonicphotonic,项目名称:Arduino,代码行数:7,代码来源:TED8020.py


示例7: __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
开发者ID:cheloftus,项目名称:nodemcu-uploader,代码行数:32,代码来源:uploader.py


示例8: 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")
开发者ID:ananthamurthy,项目名称:eyeBlinkBehaviour,代码行数:28,代码来源:arduino.py


示例9: 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()
开发者ID:JelmerT,项目名称:cc2538-bsl,代码行数:27,代码来源:cc2538-bsl.py


示例10: 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
开发者ID:ccraddock,项目名称:pyxid,代码行数:27,代码来源:serial_wrapper.py


示例11: __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)
开发者ID:XelaRellum,项目名称:python-can,代码行数:28,代码来源:serial_can.py


示例12: _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
        )
开发者ID:SirWojtek,项目名称:romek,代码行数:7,代码来源:server_main.py


示例13: 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
开发者ID:xonel,项目名称:Garmin-Forerunner-610-Extractor,代码行数:26,代码来源:driver.py


示例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)
开发者ID:eik00d,项目名称:CANToolz,代码行数:7,代码来源:hw_CAN232.py


示例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__()
开发者ID:yausern,项目名称:stlab,代码行数:7,代码来源:MKS_901P.py


示例16: _open_port

    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))
开发者ID:zserg,项目名称:pyftdi,代码行数:29,代码来源:pyterm.py


示例17: __init__

    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
开发者ID:johngumb,项目名称:danphone,代码行数:31,代码来源:Cli.py


示例18: start

    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)
开发者ID:snelson-senet,项目名称:utilities,代码行数:32,代码来源:mDotAtCmdConsole.py


示例19: __init__

 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 = []
开发者ID:SredniPrzedwieczny,项目名称:Projekt-PKM-RI,代码行数:30,代码来源:terminal.py


示例20: setupSerial

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
开发者ID:BrewPi,项目名称:brewpi-script,代码行数:35,代码来源:BrewPiUtil.py



注:本文中的serial.serial_for_url函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python serial.to_bytes函数代码示例发布时间:2022-05-27
下一篇:
Python serial.readline函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap