当前位置: 首页>>代码示例>>Python>>正文


Python serialutil.SerialException方法代码示例

本文整理汇总了Python中serial.serialutil.SerialException方法的典型用法代码示例。如果您正苦于以下问题:Python serialutil.SerialException方法的具体用法?Python serialutil.SerialException怎么用?Python serialutil.SerialException使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在serial.serialutil的用法示例。


在下文中一共展示了serialutil.SerialException方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: send_msg

# 需要导入模块: from serial import serialutil [as 别名]
# 或者: from serial.serialutil import SerialException [as 别名]
def send_msg(self, cmd):
        #log communication done in serialize function of message object. Could be too early!
        debug("SEND %4d %s" % (len(cmd), repr(cmd)))
        try:
            self.write(cmd)
        except SerialException as e:
            print e
            info("SerialException during write - recovering. msg %s" % str(e))
            self.reconnect()
        while 1:
            resp = self.expect_response(PlugwiseAckResponse)
            #test on sequence number, to be refined for wrap around
            if (self.last_counter - int(resp.command_counter, 16) >= 0):
                debug("Seqnr already used in send_msg")
            #in case a timeout on previous send occurs, then ignore here.
            if resp.status.value == 0xE1:
                debug("Ignoring 0xE1 status in send_msg")
                continue
            success = False
            if resp.status.value == 0xC1:
                success = True
            self.last_counter = int(resp.command_counter, 16)
            break
        return (success, resp.command_counter) 
开发者ID:SevenW,项目名称:Plugwise-2-py,代码行数:26,代码来源:api.py

示例2: connect

# 需要导入模块: from serial import serialutil [as 别名]
# 或者: from serial.serialutil import SerialException [as 别名]
def connect(self):
        try:
            print "Connecting to Arduino on port", self.port, "..."
            self.port = Serial(port=self.port, baudrate=self.baudrate, timeout=self.timeout, writeTimeout=self.writeTimeout)
            # The next line is necessary to give the firmware time to wake up.
            time.sleep(1)
            test = self.get_baud()
            if test != self.baudrate:
                time.sleep(1)
                test = self.get_baud()   
                if test != self.baudrate:
                    raise SerialException
            print "Connected at", self.baudrate
            print "Arduino is ready."

        except SerialException:
            print "Serial Exception:"
            print sys.exc_info()
            print "Traceback follows:"
            traceback.print_exc(file=sys.stdout)
            print "Cannot connect to Arduino!"
            os._exit(1) 
开发者ID:EAIBOT,项目名称:dashgo,代码行数:24,代码来源:dashgo_driver.py

示例3: from_url

# 需要导入模块: from serial import serialutil [as 别名]
# 或者: from serial.serialutil import SerialException [as 别名]
def from_url(self, url):
        """extract host and port from an URL string"""
        parts = urlparse.urlsplit(url)
        if parts.scheme != "loop":
            raise SerialException(
                'expected a string in the form '
                '"loop://[?logging={debug|info|warning|error}]": not starting '
                'with loop:// ({!r})'.format(parts.scheme))
        try:
            # process options now, directly altering self
            for option, values in urlparse.parse_qs(parts.query, True).items():
                if option == 'logging':
                    logging.basicConfig()   # XXX is that good to call it here?
                    self.logger = logging.getLogger('pySerial.loop')
                    self.logger.setLevel(LOGGER_LEVELS[values[0]])
                    self.logger.debug('enabled logging')
                else:
                    raise ValueError('unknown option: {!r}'.format(option))
        except ValueError as e:
            raise SerialException(
                'expected a string in the form '
                '"loop://[?logging={debug|info|warning|error}]": {}'.format(e))

    #  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  - 
开发者ID:cedricp,项目名称:ddt4all,代码行数:26,代码来源:protocol_loop.py

示例4: from_url

# 需要导入模块: from serial import serialutil [as 别名]
# 或者: from serial.serialutil import SerialException [as 别名]
def from_url(self, url):
        """extract host and port from an URL string"""
        parts = urlparse.urlsplit(url)
        if parts.scheme != "socket":
            raise SerialException('expected a string in the form "socket://<host>:<port>[?logging={debug|info|warning|error}]": not starting with socket:// (%r)' % (parts.scheme,))
        try:
            # process options now, directly altering self
            for option, values in urlparse.parse_qs(parts.query, True).items():
                if option == 'logging':
                    logging.basicConfig()   # XXX is that good to call it here?
                    self.logger = logging.getLogger('pySerial.socket')
                    self.logger.setLevel(LOGGER_LEVELS[values[0]])
                    self.logger.debug('enabled logging')
                else:
                    raise ValueError('unknown option: %r' % (option,))
            # get host and port
            host, port = parts.hostname, parts.port
            if not 0 <= port < 65536:
                raise ValueError("port not in range 0...65535")
        except ValueError as e:
            raise SerialException('expected a string in the form "socket://<host>:<port>[?logging={debug|info|warning|error}]": %s' % e)
        return (host, port)

    #  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  - 
开发者ID:sketchpunk,项目名称:android3dblendermouse,代码行数:26,代码来源:protocol_socket.py

示例5: write

# 需要导入模块: from serial import serialutil [as 别名]
# 或者: from serial.serialutil import SerialException [as 别名]
def write(self, data):
        """Output the given byte string over the serial port."""
        if not self._port_handle:
            raise portNotOpenError
        #~ if not isinstance(data, (bytes, bytearray)):
            #~ raise TypeError('expected %s or bytearray, got %s' % (bytes, type(data)))
        # convert data (needed in case of memoryview instance: Py 3.1 io lib), ctypes doesn't like memoryview
        data = to_bytes(data)
        if data:
            #~ win32event.ResetEvent(self._overlapped_write.hEvent)
            n = win32.DWORD()
            err = win32.WriteFile(self._port_handle, data, len(data), ctypes.byref(n), self._overlapped_write)
            if not err and win32.GetLastError() != win32.ERROR_IO_PENDING:
                raise SerialException("WriteFile failed (%r)" % ctypes.WinError())
            if self._write_timeout != 0:  # if blocking (None) or w/ write timeout (>0)
                # Wait for the write to complete.
                #~ win32.WaitForSingleObject(self._overlapped_write.hEvent, win32.INFINITE)
                err = win32.GetOverlappedResult(self._port_handle, self._overlapped_write, ctypes.byref(n), True)
                if n.value != len(data):
                    raise writeTimeoutError
            return n.value
        else:
            return 0 
开发者ID:sketchpunk,项目名称:android3dblendermouse,代码行数:25,代码来源:serialwin32.py

示例6: run

# 需要导入模块: from serial import serialutil [as 别名]
# 或者: from serial.serialutil import SerialException [as 别名]
def run(self):
        try:
            self.d.run()            
        except SerialException:
            pass
        except select.error:
            pass
        except OSError:
            pass
        except TypeError:
            pass
        except IndexError:
            pass
        except Exception as e:
            if DEBUG:
                traceback.print_exc()
            print(e)
        self.opened = False 
开发者ID:ernw,项目名称:dizzy-legacy,代码行数:20,代码来源:usb.py

示例7: close

# 需要导入模块: from serial import serialutil [as 别名]
# 或者: from serial.serialutil import SerialException [as 别名]
def close(self):
        if not self.open:
            return
        if not self.d is None:
            try:
                self.d.disconnect()
            except IndexError:
                pass
            except SerialException:
                pass
            except ValueError:
                pass
            except Exception as e:
                if DEBUG:
                    traceback.print_exc()
                print(e)
        if not self.sp is None:
            self.sp.close()
        self.open = False 
开发者ID:ernw,项目名称:dizzy-legacy,代码行数:21,代码来源:usb.py

示例8: get_status_json

# 需要导入模块: from serial import serialutil [as 别名]
# 或者: from serial.serialutil import SerialException [as 别名]
def get_status_json(self, mac):
        try:
            c = self.circles[self.bymac[mac]]
            control = self.controls[self.controlsbymac[mac]]
        except:
            info("get_status_json: mac not found in circles or controls")
            return ""
        try:
            status = c.get_status()
            status["monitor"] = (control['monitor'].lower() == 'yes')
            status["savelog"] = (control['savelog'].lower() == 'yes')
            #json.encoder.FLOAT_REPR = lambda f: ("%.2f" % f)
            #msg = json.dumps(status, default = jsondefault)
            msg = json.dumps(status)
        except (ValueError, TimeoutException, SerialException) as reason:
            error("Error in get_status_json: %s" % (reason,))
            msg = ""
        return str(msg) 
开发者ID:SevenW,项目名称:Plugwise-2-py,代码行数:20,代码来源:Join-2.py

示例9: sync_time

# 需要导入模块: from serial import serialutil [as 别名]
# 或者: from serial.serialutil import SerialException [as 别名]
def sync_time(self):
        for c in self.circles:
            if not c.online:
                continue
            try:
                info("sync_time: circle %s time is %s" % (c.attr['name'], c.get_clock().isoformat()))
                if c.type()=='circle+':
                    #now = datetime.now()            
                    #local time not following DST (always non-DST)
                    locnow = datetime.utcnow()-timedelta(seconds=time.timezone)
                    now = locnow
                    c.set_circleplus_datetime(now)
                #now = datetime.now()            
                #local time not following DST (always non-DST)
                locnow = datetime.utcnow()-timedelta(seconds=time.timezone)
                now = locnow
                c.set_clock(now)
            except (ValueError, TimeoutException, SerialException) as reason:
                error("Error in sync_time: %s" % (reason,)) 
开发者ID:SevenW,项目名称:Plugwise-2-py,代码行数:21,代码来源:Join-2.py

示例10: test_offline

# 需要导入模块: from serial import serialutil [as 别名]
# 或者: from serial.serialutil import SerialException [as 别名]
def test_offline(self):
        """
        When an unrecoverable communication failure with a circle occurs, the circle
        is set online = False. This function will test on this condition and if offline,
        it test whether it is available again, and if so, it will recover
        control settings and switching schedule if needed.
        In case the circle was offline during initialization, a reinit is performed.
        """
        for c in self.circles:
            if not c.online:
                try:
                    c.ping()
                    if c.online:
                        #back online. Make sure switch and schedule is ok
                        if not c.initialized:
                            c.reinit()
                            self.set_interval_production(c)
                        idx=self.controlsbymac[c.mac]
                        self.apply_control_to_circle(self.controls[idx], c.mac)
                except ValueError:
                    continue
                except (TimeoutException, SerialException) as reason:
                    debug("Error in test_offline(): %s" % (reason,))
                    continue 
开发者ID:SevenW,项目名称:Plugwise-2-py,代码行数:26,代码来源:Join-2.py

示例11: _restore_target_connection

# 需要导入模块: from serial import serialutil [as 别名]
# 或者: from serial.serialutil import SerialException [as 别名]
def _restore_target_connection(self):
        """
        Leaves the firmware update target connection (XBee device or serial port) in its original state.

        Raises:
            SerialException: if there is any error restoring the serial port connection.
            XBeeException: if there is any error restoring the device connection.
        """
        if self._xbee_device is not None:
            if self._xbee_serial_port is not None:
                if self._xbee_serial_port.isOpen():
                    self._xbee_serial_port.close()
            if self._device_was_connected and not self._xbee_device.is_open():
                self._xbee_device.open()
            elif not self._device_was_connected and self._xbee_device.is_open():
                self._xbee_device.close()
        elif self._xbee_serial_port is not None and self._xbee_serial_port.isOpen():
            self._xbee_serial_port.close()
        _log.debug("Restored target connection") 
开发者ID:digidotcom,项目名称:xbee-python,代码行数:21,代码来源:recovery.py

示例12: _is_in_atcmd_mode

# 需要导入模块: from serial import serialutil [as 别名]
# 或者: from serial.serialutil import SerialException [as 别名]
def _is_in_atcmd_mode(self):
        """
        Returns whether the command mode is active or not.

        Returns:
            Boolean: ``True`` if the AT command mode is active, ``False`` otherwise.
        """
        _log.debug("Checking AT command mode...")
        try:
            self._serial_port.write(str.encode(_COMMAND_AT, encoding='utf-8'))
            answer = self._read_data(timeout=_GUARD_TIME)

            return answer is not None and _COMMAND_MODE_ANSWER_OK in answer
        except SerialException as e:
            _log.exception(e)
            return False 
开发者ID:digidotcom,项目名称:xbee-python,代码行数:18,代码来源:filesystem.py

示例13: _supports_filesystem

# 需要导入模块: from serial import serialutil [as 别名]
# 或者: from serial.serialutil import SerialException [as 别名]
def _supports_filesystem(self):
        """
        Returns whether the device supports file system or not.

        Returns:
             Boolean: ``True`` if the device supports file system, ``False`` otherwise.
        """
        _log.debug("Checking if device supports file system...")
        if not self._check_atcmd_mode():
            return False

        try:
            self._serial_port.write(str.encode(_COMMAND_FILE_SYSTEM, encoding='utf-8'))
            answer = self._read_data()
            if answer and _ANSWER_ATFS in answer.upper():
                self._parse_filesystem_functions(answer.replace("\r", ""))
                return True

            return False
        except SerialException as e:
            _log.exception(e)
            return False 
开发者ID:digidotcom,项目名称:xbee-python,代码行数:24,代码来源:filesystem.py

示例14: _xmodem_write_cb

# 需要导入模块: from serial import serialutil [as 别名]
# 或者: from serial.serialutil import SerialException [as 别名]
def _xmodem_write_cb(self, data):
        """
        Callback function used to write data to the serial port when requested from the XModem transfer.

        Args:
            data (Bytearray): the data to write to serial port from the XModem transfer.

        Returns:
            Boolean: ``True`` if the data was successfully written, ``False`` otherwise.
        """
        try:
            self._serial_port.purge_port()
            self._serial_port.write(data)
            self._serial_port.flush()
            return True
        except SerialException as e:
            _log.exception(e)

        return False 
开发者ID:digidotcom,项目名称:xbee-python,代码行数:21,代码来源:filesystem.py

示例15: _xmodem_read_cb

# 需要导入模块: from serial import serialutil [as 别名]
# 或者: from serial.serialutil import SerialException [as 别名]
def _xmodem_read_cb(self, size, timeout=_READ_DATA_TIMEOUT):
        """
        Callback function used to read data from the serial port when requested from the XModem transfer.

        Args:
            size (Integer): the size of the data to read.
            timeout (Integer, optional): the maximum time to wait to read the requested data (seconds).

        Returns:
            Bytearray: the read data, ``None`` if data could not be read.
        """
        deadline = _get_milliseconds() + (timeout * 1000)
        data = bytearray()
        try:
            while len(data) < size and _get_milliseconds() < deadline:
                read_bytes = self._serial_port.read(size - len(data))
                if len(read_bytes) > 0:
                    data.extend(read_bytes)
            return data
        except SerialException as e:
            _log.exception(e)

        return None 
开发者ID:digidotcom,项目名称:xbee-python,代码行数:25,代码来源:filesystem.py


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