當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。