Python源码示例:machine.idle()

示例1
def read_frames(self, count):
        frames = []
        # flush the buffer to read fresh data
        self.uart.readall()
        while len(frames) < count:
            self.__wait_for_data(32)

            while self.uart.read(1) != b'\x42':
                machine.idle()

            if self.uart.read(1) == b'\x4D':
                self.__wait_for_data(30)

                try:
                    data = PMSData.from_bytes(b'\x42\x4D' + self.uart.read(30))
                    print('cPM25: {}, cPM10: {}, PM25: {}, PM10: {}' \
                            .format(data.cpm25, data.cpm10, data.pm25, data.pm10))
                    frames.append(data)
                except ValueError as e:
                    print('error reading frame: {}'.format(e.message))
                    pass

        return frames 
示例2
def connect_blocking():
    global _wlan

    activate()

    # no scan of networks to allow connect to hidden essid
    # Try to connect
    tries = 15
    for i in range(tries):
        print("%d/%d. Trying to connect." % (i + 1, tries))
        machine.idle()
        time.sleep(1)
        if connected():
            break

    if connected():
        print('Wifi: connection succeeded!')
        print(_wlan.ifconfig())
    else:
        print('Wifi: connection failed, starting accesspoint!')
        accesspoint()
    nr.start(nostop=True) 
示例3
def connect_blocking():
    global _wlan

    activate()

    # no scan of networks to allow connect to hidden essid
    # Try to connect
    tries = 15
    for i in range(tries):
        print("%d/%d. Trying to connect." % (i + 1, tries))
        machine.idle()
        time.sleep(1)
        if connected():
            break

    if connected():
        print('Wifi: connection succeeded!')
        print(_wlan.ifconfig())
    else:
        print('Wifi: connection failed, starting accesspoint!')
        accesspoint()
    nr.start(nostop=True) 
示例4
def connect_blocking():
    global _wlan

    activate()

    # no scan of networks to allow connect to hidden essid
    # Try to connect
    tries = 15
    for i in range(tries):
        print("%d/%d. Trying to connect." % (i + 1, tries))
        machine.idle()
        time.sleep(1)
        if connected():
            break

    if connected():
        print('Wifi: connection succeeded!')
        print(_wlan.ifconfig())
    else:
        print('Wifi: connection failed, starting accesspoint!')
        accesspoint()
    nr.start(nostop=True) 
示例5
def connect_blocking():
    global _wlan

    activate()

    # no scan of networks to allow connect to hidden essid
    # Try to connect
    tries = 15
    for i in range(tries):
        print("%d/%d. Trying to connect." % (i + 1, tries))
        machine.idle()
        time.sleep(1)
        if connected():
            break

    if connected():
        print('Wifi: connection succeeded!')
        print(_wlan.ifconfig())
    else:
        print('Wifi: connection failed, starting accesspoint!')
        accesspoint()
    nr.start(nostop=True) 
示例6
def connect_blocking():
    global _wlan

    activate()

    # no scan of networks to allow connect to hidden essid
    # Try to connect
    tries = 15
    for i in range(tries):
        print("%d/%d. Trying to connect." % (i + 1, tries))
        machine.idle()
        time.sleep(1)
        if connected():
            break

    if connected():
        print('Wifi: connection succeeded!')
        print(_wlan.ifconfig())
    else:
        print('Wifi: connection failed, starting accesspoint!')
        accesspoint()
    nr.start(nostop=True) 
示例7
def measurements(self):
        # flush the buffer to read fresh data
        ret_data = None
        self._wait_for_data(32)

        while self._uart.read(1) != b'\x42':
            machine.idle()

        if self._uart.read(1) == b'\x4D':
            self._wait_for_data(30)
            try:
                self._data = self._uart.read(30)
                if self._data:
                    ret_data = self._PMdata()
            except ValueError as e:
                print('error reading frame: {}'.format(e.message))
                pass
                
        return ret_data 
示例8
def wait_for_nic(self, retries=5):
        """

        :param retries:  (Default value = 5)

        """
        attempts = 0
        while attempts < retries:
            try:
                socket.getaddrinfo("localhost", 333)
                break
            except OSError as ex:
                print('Network interface not available: {}'.format(ex))
            print('Waiting for network interface')
            # Save power while waiting.
            machine.idle()
            time.sleep(0.25)
            attempts += 1
        print('Network interface ready') 
示例9
def runLoop():
    while True:
        blynk.run()
        machine.idle()

# Run blynk in the main thread: 
示例10
def runLoop():
    while True:
        blynk.run()
        machine.idle()

# Run blynk in the main thread: 
示例11
def runLoop():
    while True:
        blynk.run()
        machine.idle() 
示例12
def runLoop():
    while True:
        blynk.run()
        time.sleep(0.1)
        #machine.idle()

# Run blynk in the main thread: 
示例13
def runLoop():
    while True:
        blynk.run()
        machine.idle()

# Run blynk in the main thread: 
示例14
def idle(self):
        self.en(False)
        self.uart.deinit() 
示例15
def _idle_task(self):
        while True:
            await asyncio.sleep_ms(10)
            machine.idle()  # Yield to underlying RTOS 
示例16
def init_wlan_sta():
    """Connect to wifi network specified in configuration."""

    print('WLAN: STA mode')
    wlan.init(mode=WLAN.STA)
    if not wlan.isconnected():
        wlan.connect(WLAN_SSID, auth=WLAN_AUTH, timeout=5000)
        while not wlan.isconnected():
            machine.idle()  # save power while waiting 
示例17
def connect_wifi_sta_single(self, ssid, authmode, password, timeout=10000):
        """

        :param ssid: 
        :param authmode: 
        :param password: 
        :param timeout:  (Default value = 10000)

        """

        print('INFO:  WiFi STA: Connecting to "{}"'.format(ssid))
        self.station.connect(ssid, auth=(authmode, password), timeout=timeout)

        try:
            # FIXME: This is a candidate for an infinite loop.
            while not self.station.isconnected():
                # Save power while waiting
                machine.idle()
                time.sleep_ms(250)

            print('INFO:  WiFi STA: Connected to "{}"'.format(ssid))

            return True

        except Exception as ex:
            print('ERROR: WiFi STA: Connecting to "{}" failed. Please check SSID and PASSWORD.\n{}'.format(ssid, ex)) 
示例18
def monkeypatch_machine():

    from mock import Mock

    import uuid
    import machine

    # Some primitives.
    machine.enable_irq = Mock()
    machine.disable_irq = Mock()
    machine.unique_id = lambda: str(uuid.uuid4().fields[-1])[:5].encode()
    machine.freq = Mock(return_value=42000000)
    machine.idle = Mock()

    # Reset cause and wake reason.
    machine.PWRON_RESET = 0
    machine.HARD_RESET = 1
    machine.WDT_RESET = 2
    machine.DEEPSLEEP_RESET = 3
    machine.SOFT_RESET = 4
    machine.BROWN_OUT_RESET = 5

    machine.PWRON_WAKE = 0
    machine.GPIO_WAKE = 1
    machine.RTC_WAKE = 2
    machine.ULP_WAKE = 3

    machine.reset_cause = Mock(return_value=0)
    machine.wake_reason = wake_reason 
示例19
def stay_connected(self):
        """ """

        # Prepare information about known WiFi networks.
        networks_known = self.get_configured_stations()

        # Attempt to connect to known/configured networks.
        attempt = 0
        while self.is_running:

            delay = 1

            if self.is_connected():
                attempt = 0

            else:
                log.info("WiFi STA: Connecting to configured networks: %s. "
                         "Attempt: #%s", list(networks_known), attempt + 1)
                try:
                    self.connect_stations(networks_known)

                except KeyboardInterrupt:
                    raise

                except Exception as ex:
                    log.exc(ex, 'WiFi STA: Connecting to configured networks "{}" failed'.format(list(networks_known)))
                    delay = backoff_time(attempt, minimum=1, maximum=600)
                    log.info('WiFi STA: Retrying in {} seconds'.format(delay))

                attempt += 1

            machine.idle()
            time.sleep(delay) 
示例20
def wait_for_connection(self, timeout=15.0):
        """
        Wait for network to arrive.

        :param timeout:  (Default value = 15.0)

        """

        # Set interval how often to poll for WiFi connectivity.
        network_poll_interval = 250

        # How many checks to make.
        checks = int(timeout / (network_poll_interval / 1000.0))

        self.stopwatch.reset()

        do_report = True
        while not self.is_connected():

            delta = self.stopwatch.elapsed()
            eta = timeout - delta

            if checks <= 0 or eta <= 0:
                break

            # Report about the progress each 3 seconds.
            if int(delta) % 3 == 0:
                if do_report:
                    log.info('WiFi STA: Waiting for network to come up within {} seconds'.format(eta))
                    do_report = False
            else:
                do_report = True

            # Save power while waiting.
            machine.idle()

            # Don't busy-wait.
            time.sleep_ms(network_poll_interval)

            checks -= 1 
示例21
def wait_for_nic(self, timeout=5):
        """

        :param timeout:  (Default value = 5)

        """

        eggtimer = Eggtimer(duration=timeout)

        log.info('Waiting for network interface')
        while not eggtimer.expired():

            self.device.watchdog.feed()

            try:
                # TODO: Make WiFi-agnostic.
                if self.wifi_manager.is_connected():
                    log.info('Network interface ready')
                    return True

            except OSError as ex:
                log.warning('Network interface not available: %s', format_exception(ex))

            # Report about progress.
            sys.stderr.write('.')
            #sys.stderr.flush()

            # Save power while waiting.
            machine.idle()
            time.sleep(0.25)

        # TODO: Make WiFi-agnostic.
        raise NetworkUnavailable('Could not connect to WiFi network') 
示例22
def start(self):
        """ """

        print('Starting Bluetooth')
        self.bt = Bluetooth()

        # Default
        #self.bt.init(id=0, mode=Bluetooth.BLE, antenna=Bluetooth.INT_ANT, modem_sleep=True)
        #self.bt.init(id=0, antenna=Bluetooth.INT_ANT, modem_sleep=False)
        self.bt.init(modem_sleep=False)

        return

        print('Entering main loop')
        while True:
            print('--- loop ---')

            adv = self.bt.get_adv()
            print('adv:', adv)

            # Give the system some breath.
            print('machine.idle()')
            machine.idle()

            utime.sleep(10.0)
            continue 
示例23
def duty_cycle(self):
        """Main duty cycle"""

        if not self.settings.get('main.deepsleep', False):
            self.duty_chrono.reset()

        #log.info('Terkin loop')

        # Alternative loop signalling: 1 x blue.
        # https://forum.pycom.io/topic/2067/brightness-of-on-board-led/7
        self.device.blink_led(0x00000b, count=2)

        # Read sensors.
        readings = self.read_sensors()

        # Remember current reading
        self.storage.last_reading = readings.data_in

        # Run the garbage collector.
        self.device.run_gc()

        # Transmit data.
        transmission_success = self.transmit_readings(readings)

        # Signal transmission outcome.
        if transmission_success:
            self.device.blink_led(0x00000b)
        else:
            self.device.blink_led(0x0b0000)

        # Run the garbage collector.
        self.device.run_gc()

        # Give the system some breath.
        machine.idle() 
示例24
def hibernate(self, interval, lightsleep=False, deepsleep=False):
        """

        :param interval:
        :param lightsleep:  (Default value = False)
        :param deepsleep:  (Default value = False)

        """

        #logging.enable_logging()

        if deepsleep:

            # Prepare and invoke deep sleep.
            # https://docs.micropython.org/en/latest/library/machine.html#machine.deepsleep

            log.info('Preparing deep sleep')

            # Set wake up mode.
            self.set_wakeup_mode()

            # Invoke deep sleep.
            log.info('Entering deep sleep for {} seconds'.format(interval))
            #self.terminal.stop()
            machine.deepsleep(int(interval * 1000))

        else:

            # Adjust watchdog for interval.
            self.watchdog.adjust_for_interval(interval)

            # Invoke light sleep.
            # https://docs.micropython.org/en/latest/library/machine.html#machine.sleep
            # https://docs.micropython.org/en/latest/library/machine.html#machine.lightsleep
            #
            # As "machine.sleep" seems to be a noop on Pycom MicroPython,
            # we will just use the regular "time.sleep" here.
            # machine.sleep(int(interval * 1000))
            machine.idle()

            if lightsleep:
                log.info('Entering light sleep for {} seconds'.format(interval))
                machine.sleep(int(interval * 1000))

            else:
                # Normal wait.
                log.info('Waiting for {} seconds'.format(interval))
                time.sleep(interval)