Python machine.idle() Examples

The following are 24 code examples of machine.idle(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module machine , or try the search function .
Example #1
Source File: pms5003.py    From upython-aq-monitor with MIT License 6 votes vote down vote up
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 
Example #2
Source File: _wifi.py    From ulnoiot-upy with MIT License 6 votes vote down vote up
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) 
Example #3
Source File: _wifi.py    From ulnoiot-upy with MIT License 6 votes vote down vote up
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) 
Example #4
Source File: _wifi.py    From ulnoiot-upy with MIT License 6 votes vote down vote up
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) 
Example #5
Source File: _wifi.py    From ulnoiot-upy with MIT License 6 votes vote down vote up
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) 
Example #6
Source File: _wifi.py    From ulnoiot-upy with MIT License 6 votes vote down vote up
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) 
Example #7
Source File: pmsa003.py    From uPySensors with Apache License 2.0 6 votes vote down vote up
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 
Example #8
Source File: mininet.py    From terkin-datalogger with GNU Affero General Public License v3.0 6 votes vote down vote up
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') 
Example #9
Source File: ESP8266_ESP32.py    From blynk-library-python with MIT License 5 votes vote down vote up
def runLoop():
    while True:
        blynk.run()
        machine.idle()

# Run blynk in the main thread: 
Example #10
Source File: datalogger.py    From terkin-datalogger with GNU Affero General Public License v3.0 5 votes vote down vote up
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() 
Example #11
Source File: pycom.py    From terkin-datalogger with GNU Affero General Public License v3.0 5 votes vote down vote up
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 
Example #12
Source File: core.py    From terkin-datalogger with GNU Affero General Public License v3.0 5 votes vote down vote up
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') 
Example #13
Source File: wifi.py    From terkin-datalogger with GNU Affero General Public License v3.0 5 votes vote down vote up
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 
Example #14
Source File: wifi.py    From terkin-datalogger with GNU Affero General Public License v3.0 5 votes vote down vote up
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) 
Example #15
Source File: compat.py    From terkin-datalogger with GNU Affero General Public License v3.0 5 votes vote down vote up
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 
Example #16
Source File: mininet.py    From terkin-datalogger with GNU Affero General Public License v3.0 5 votes vote down vote up
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)) 
Example #17
Source File: boot.py    From ttnmapper with MIT License 5 votes vote down vote up
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 
Example #18
Source File: sock_nonblock.py    From micropython-async with MIT License 5 votes vote down vote up
def _idle_task(self):
        while True:
            await asyncio.sleep_ms(10)
            machine.idle()  # Yield to underlying RTOS 
Example #19
Source File: pms5003.py    From upython-aq-monitor with MIT License 5 votes vote down vote up
def idle(self):
        self.en(False)
        self.uart.deinit() 
Example #20
Source File: ESP32_Cellular_PPPoS.py    From blynk-library-python with MIT License 5 votes vote down vote up
def runLoop():
    while True:
        blynk.run()
        machine.idle()

# Run blynk in the main thread: 
Example #21
Source File: PyCom_BLE.py    From blynk-library-python with MIT License 5 votes vote down vote up
def runLoop():
    while True:
        blynk.run()
        time.sleep(0.1)
        #machine.idle()

# Run blynk in the main thread: 
Example #22
Source File: WM_W600.py    From blynk-library-python with MIT License 5 votes vote down vote up
def runLoop():
    while True:
        blynk.run()
        machine.idle() 
Example #23
Source File: PyCom_WiPy.py    From blynk-library-python with MIT License 5 votes vote down vote up
def runLoop():
    while True:
        blynk.run()
        machine.idle()

# Run blynk in the main thread: 
Example #24
Source File: device.py    From terkin-datalogger with GNU Affero General Public License v3.0 4 votes vote down vote up
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)