Python uasyncio.sleep_ms() Examples

The following are 30 code examples of uasyncio.sleep_ms(). 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 uasyncio , or try the search function .
Example #1
Source File: client.py    From micropython-iot with MIT License 6 votes vote down vote up
def _send(self, d):  # Write a line to socket.
        async with self._s_lock:
            start = utime.ticks_ms()
            while d:
                try:
                    ns = self._sock.send(d)  # OSError if client closes socket
                except OSError as e:
                    err = e.args[0]
                    if err == errno.EAGAIN:  # Would block: await server read
                        await asyncio.sleep_ms(100)
                    else:
                        self._verbose and print('_send fail. Disconnect')
                        self._evfail.set()
                        return False  # peer disconnect
                else:
                    d = d[ns:]
                    if d:  # Partial write: pause
                        await asyncio.sleep_ms(20)
                    if utime.ticks_diff(utime.ticks_ms(), start) > self._to:
                        self._verbose and print('_send fail. Timeout.')
                        self._evfail.set()
                        return False

            self._last_wr = utime.ticks_ms()
        return True 
Example #2
Source File: server.py    From micropython-samples with MIT License 6 votes vote down vote up
def readline(s, timeout):
    line = b''
    start = utime.ticks_ms()
    while True:
        if line.endswith(b'\n'):
            if len(line) > 1:
                return line
            line = b''
            start = utime.ticks_ms()  # A blank line is just a  keepalive
        await asyncio.sleep_ms(100)  # See note above
        d = s.readline()
        if d == b'':
            raise OSError
        if d is not None:
            line = b''.join((line, d))
        if utime.ticks_diff(utime.ticks_ms(), start) > timeout:
            raise OSError 
Example #3
Source File: syncom.py    From micropython-mqtt with MIT License 6 votes vote down vote up
def start(self, user_task=None, awaitable=None):
        loop = asyncio.get_event_loop()
        while True:
            if not self._running:   # Restarting
                self.lstrx = []     # Clear down queues
                self.lsttx = []
                self._synchronised = False
                loop.create_task(self._run())  # Reset target (if possible)
                while not self._synchronised:  # Wait for sync
                    await asyncio.sleep_ms(100)
                if user_task is None:
                    while self._running:
                        await asyncio.sleep_ms(100)
                else:
                    await user_task(self)  # User task must quit on timeout
                    # If it quit for other reasons force a t/o exception
                    self.stop()
            await asyncio.sleep_ms(0)
            if awaitable is not None:  # User code may use an ExitGate
                await awaitable  # to ensure all coros have quit

# Can be used to force a failure 
Example #4
Source File: mqtt_as.py    From micropython-mqtt with MIT License 6 votes vote down vote up
def broker_up(self):  # Test broker connectivity
        if not self.isconnected():
            return False
        tlast = self.last_rx
        if ticks_diff(ticks_ms(), tlast) < 1000:
            return True
        try:
            await self._ping()
        except OSError:
            return False
        t = ticks_ms()
        while not self._timeout(t):
            await asyncio.sleep_ms(100)
            if ticks_diff(self.last_rx, tlast) > 0:  # Response received
                return True
        return False 
Example #5
Source File: mqtt_as.py    From micropython-mqtt with MIT License 6 votes vote down vote up
def _as_write(self, bytes_wr, length=0, sock=None):
        if sock is None:
            sock = self._sock
        if length:
            bytes_wr = bytes_wr[:length]
        t = ticks_ms()
        while bytes_wr:
            if self._timeout(t) or not self.isconnected():
                raise OSError(-1)
            try:
                n = sock.write(bytes_wr)
            except OSError as e:  # ESP32 issues weird 119 errors here
                n = 0
                if e.args[0] not in BUSY_ERRORS:
                    raise
            if n:
                t = ticks_ms()
                bytes_wr = bytes_wr[n:]
            await asyncio.sleep_ms(_SOCKET_POLL_DELAY) 
Example #6
Source File: mqtt_as.py    From micropython-mqtt with MIT License 6 votes vote down vote up
def _as_read(self, n, sock=None):  # OSError caught by superclass
        if sock is None:
            sock = self._sock
        data = b''
        t = ticks_ms()
        while len(data) < n:
            if self._timeout(t) or not self.isconnected():
                raise OSError(-1)
            try:
                msg = sock.read(n - len(data))
            except OSError as e:  # ESP32 issues weird 119 errors here
                msg = None
                if e.args[0] not in BUSY_ERRORS:
                    raise
            if msg == b'':  # Connection closed by host
                raise OSError(-1)
            if msg is not None:  # data received
                data = b''.join((data, msg))
                t = ticks_ms()
                self.last_rx = ticks_ms()
            await asyncio.sleep_ms(_SOCKET_POLL_DELAY)
        return data 
Example #7
Source File: client_w.py    From micropython-samples with MIT License 6 votes vote down vote up
def readline(self):
        line = b''
        start = utime.ticks_ms()
        while True:
            if line.endswith(b'\n'):
                if len(line) > 1:
                    return line
                line = b''
                start = utime.ticks_ms()  # Blank line is keepalive
                self.led(not self.led())
            await asyncio.sleep_ms(100)  # nonzero wait seems empirically necessary
            d = self.sock.readline()
            if d == b'':
                raise OSError
            if d is not None:
                line = b''.join((line, d))
            if utime.ticks_diff(utime.ticks_ms(), start) > self.timeout:
                raise OSError 
Example #8
Source File: asyntest.py    From micropython-samples with MIT License 6 votes vote down vote up
def cond_go():
    ntasks = 7
    barrier = Barrier(ntasks + 1)
    t1 = asyncio.create_task(cond01())
    t3 = asyncio.create_task(cond03())
    for n in range(ntasks):
        asyncio.create_task(cond02(n, barrier))
    await barrier  # All instances of cond02 have completed
    # Test wait_for
    barrier = Barrier(2)
    asyncio.create_task(cond04(99, barrier))
    await barrier
    # cancel continuously running coros.
    t1.cancel()
    t3.cancel()
    await asyncio.sleep_ms(0)
    print('Done.') 
Example #9
Source File: asyn.py    From micropython-mqtt with MIT License 6 votes vote down vote up
def sleep(t, granularity=100):  # 100ms default
    if granularity <= 0:
        raise ValueError('sleep granularity must be > 0')
    t = int(t * 1000)  # ms
    if t <= granularity:
        await asyncio.sleep_ms(t)
    else:
        n, rem = divmod(t, granularity)
        for _ in range(n):
            await asyncio.sleep_ms(granularity)
        await asyncio.sleep_ms(rem)

# Anonymous cancellable tasks. These are members of a group which is identified
# by a user supplied name/number (default 0). Class method cancel_all() cancels
# all tasks in a group and awaits confirmation. Confirmation of ending (whether
# normally or by cancellation) is signalled by a task calling the _stopped()
# class method. Handled by the @cancellable decorator. 
Example #10
Source File: aswitch.py    From micropython-samples with MIT License 5 votes vote down vote up
def switchcheck(self):
        loop = asyncio.get_event_loop()
        while True:
            state = self.pin.value()
            if state != self.switchstate:
                # State has changed: act on it now.
                self.switchstate = state
                if state == 0 and self._close_func:
                    launch(self._close_func, self._close_args)
                elif state == 1 and self._open_func:
                    launch(self._open_func, self._open_args)
            # Ignore further state changes until switch has settled
            await asyncio.sleep_ms(Switch.debounce_ms) 
Example #11
Source File: fusionlcd.py    From micropython-fusion with MIT License 5 votes vote down vote up
def lcd_task():
    print('Running test...')
    if switch.value() == 1:
        lcd[0] = "Calibrate. Push switch"
        lcd[1] = "when done"
        await asyncio.sleep_ms(100)  # Let LCD coro run
        await fuse.calibrate(lambda : not switch.value())
        print(fuse.magbias)
    await fuse.start()  # Start the update task
    loop = asyncio.get_event_loop()
    loop.create_task(display()) 
Example #12
Source File: fusiontest_as.py    From micropython-fusion with MIT License 5 votes vote down vote up
def mem_manage():         # Necessary for long term stability
    while True:
        await asyncio.sleep_ms(100)
        gc.collect()
        gc.threshold(gc.mem_free() // 4 + gc.mem_alloc()) 
Example #13
Source File: fusiontest_as6.py    From micropython-fusion with MIT License 5 votes vote down vote up
def display():
    fs = 'Heading: {:4.0f} Pitch: {:4.0f} Roll: {:4.0f}'
    while True:
        print(fs.format(fuse.heading, fuse.pitch, fuse.roll))
        await asyncio.sleep_ms(500) 
Example #14
Source File: fusiontest_as.py    From micropython-fusion with MIT License 5 votes vote down vote up
def read_coro():
    imu.mag_trigger()
    await asyncio.sleep_ms(20)  # Plenty of time for mag to be ready
    return imu.accel.xyz, imu.gyro.xyz, imu.mag_nonblocking.xyz 
Example #15
Source File: fusiontest_as6.py    From micropython-fusion with MIT License 5 votes vote down vote up
def read_coro():
    await asyncio.sleep_ms(20)  # Plenty of time for mag to be ready
    return imu.accel.xyz, imu.gyro.xyz 
Example #16
Source File: server.py    From micropython-samples with MIT License 5 votes vote down vote up
def send(s, d, timeout):
    start = utime.ticks_ms()
    while len(d):
        ns = s.send(d)  # OSError if client fails
        d = d[ns:]
        await asyncio.sleep_ms(100)  # See note above
        if utime.ticks_diff(utime.ticks_ms(), start) > timeout:
            raise OSError

# Return the connection for a client if it is connected (else None) 
Example #17
Source File: primitives.py    From micropython-samples with MIT License 5 votes vote down vote up
def __await__(self):
        while not self._flag:
            await asyncio.sleep_ms(self.delay_ms) 
Example #18
Source File: auart_hd.py    From micropython-samples with MIT License 5 votes vote down vote up
def _run(self):
        responses = ['Line 1', 'Line 2', 'Line 3', 'Goodbye']
        while True:
            res = await self.sreader.readline()
            for response in responses:
                await self.swriter.awrite("{}\r\n".format(response))
                # Demo the fact that the master tolerates slow response.
                await asyncio.sleep_ms(300)

# The master's send_command() method sends a command and waits for a number of
# lines from the device. The end of the process is signified by a timeout, when
# a list of lines is returned. This allows line-by-line processing.
# A special test mode demonstrates the behaviour with a non-responding device. If
# None is passed, no commend is sent. The master waits for a response which never
# arrives and returns an empty list. 
Example #19
Source File: aswitch.py    From micropython-samples with MIT License 5 votes vote down vote up
def buttoncheck(self):
        loop = asyncio.get_event_loop()
        if self._long_func:
            longdelay = Delay_ms(self._long_func, self._long_args)
        if self._double_func:
            doubledelay = Delay_ms()
        while True:
            state = self.rawstate()
            # State has changed: act on it now.
            if state != self.buttonstate:
                self.buttonstate = state
                if state:
                    # Button is pressed
                    if self._long_func and not longdelay.running():
                        # Start long press delay
                        longdelay.trigger(Pushbutton.long_press_ms)
                    if self._double_func:
                        if doubledelay.running():
                            launch(self._double_func, self._double_args)
                        else:
                            # First click: start doubleclick timer
                            doubledelay.trigger(Pushbutton.double_click_ms)
                    if self._true_func:
                        launch(self._true_func, self._true_args)
                else:
                    # Button release
                    if self._long_func and longdelay.running():
                        # Avoid interpreting a second click as a long push
                        longdelay.stop()
                    if self._false_func:
                        launch(self._false_func, self._false_args)
            # Ignore state changes until switch has settled
            await asyncio.sleep_ms(Pushbutton.debounce_ms) 
Example #20
Source File: pushbutton.py    From micropython-samples with MIT License 5 votes vote down vote up
def buttoncheck(self):
        if self._lf:  # Instantiate timers if funcs exist
            self._ld = Delay_ms(self._lf, self._la)
        if self._df:
            self._dd = Delay_ms(self._ddto)
        while True:
            state = self.rawstate()
            # State has changed: act on it now.
            if state != self.state:
                self.state = state
                if state:  # Button pressed: launch pressed func
                    if self._tf:
                        launch(self._tf, self._ta)
                    if self._lf:  # There's a long func: start long press delay
                        self._ld.trigger(Pushbutton.long_press_ms)
                    if self._df:
                        if self._dd():  # Second click: timer running
                            self._dd.stop()
                            self._dblpend = False
                            self._dblran = True  # Prevent suppressed launch on release
                            launch(self._df, self._da)
                        else:
                            # First click: start doubleclick timer
                            self._dd.trigger(Pushbutton.double_click_ms)
                            self._dblpend = True  # Prevent suppressed launch on release
                else:  # Button release. Is there a release func?
                    if self._ff:
                        if self._supp:
                            d = self._ld 
                            # If long delay exists, is running and doubleclick status is OK
                            if not self._dblpend and not self._dblran:
                                if (d and d()) or not d:
                                    launch(self._ff, self._fa)
                        else:
                            launch(self._ff, self._fa)
                    if self._ld:
                        self._ld.stop()  # Avoid interpreting a second click as a long push
                    self._dblran = False
            # Ignore state changes until switch has settled
            await asyncio.sleep_ms(Pushbutton.debounce_ms) 
Example #21
Source File: switches.py    From micropython-samples with MIT License 5 votes vote down vote up
def pulse(led, ms):
    led.on()
    await asyncio.sleep_ms(ms)
    led.off()

# Toggle an LED (callback) 
Example #22
Source File: barrier.py    From micropython-samples with MIT License 5 votes vote down vote up
def __await__(self):
        self._update()
        if self._at_limit():  # All other threads are also at limit
            if self._func is not None:
                launch(self._func, self._args)
            self._reset(not self._down)  # Toggle direction to release others
            return

        direction = self._down
        while True:  # Wait until last waiting thread changes the direction
            if direction != self._down:
                return
            await asyncio.sleep_ms(0) 
Example #23
Source File: aswitch.py    From micropython-samples with MIT License 5 votes vote down vote up
def killer(self):
        twait = time.ticks_diff(self.tstop, time.ticks_ms())
        while twait > 0:  # Must loop here: might be retriggered
            await asyncio.sleep_ms(twait)
            if self.tstop is None:
                break  # Return if stop() called during wait
            twait = time.ticks_diff(self.tstop, time.ticks_ms())
        if self.tstop is not None and self.func is not None:
            launch(self.func, self.args)  # Timed out: execute callback
        self.tstop = None  # Not running 
Example #24
Source File: message.py    From micropython-samples with MIT License 5 votes vote down vote up
def wait(self):  # CPython comptaibility
        while not self._flag:
            await asyncio.sleep_ms(self.delay_ms) 
Example #25
Source File: message.py    From micropython-samples with MIT License 5 votes vote down vote up
def __await__(self):
        while not self._flag:
            await asyncio.sleep_ms(self.delay_ms) 
Example #26
Source File: aswitch.py    From micropython-samples with MIT License 5 votes vote down vote up
def _run(self):
        while True:
            if self.tstop is None:  # Not running
                await asyncio.sleep_ms(0)
            else:
                await self.killer() 
Example #27
Source File: queue.py    From micropython-samples with MIT License 5 votes vote down vote up
def put(self, val):  # Usage: await queue.put(item)
        while self.qsize() >= self.maxsize and self.maxsize:
            # Queue full
            await asyncio.sleep_ms(0)
            # Task(s) waiting to get from queue, schedule first Task
        self._put(val) 
Example #28
Source File: semaphore.py    From micropython-samples with MIT License 5 votes vote down vote up
def acquire(self):
        while self._count == 0:
            await asyncio.sleep_ms(0)
        self._count -= 1 
Example #29
Source File: delay_ms.py    From micropython-samples with MIT License 5 votes vote down vote up
def _killer(self):
        twait = time.ticks_diff(self._tstop, time.ticks_ms())
        while twait > 0:  # Must loop here: might be retriggered
            await asyncio.sleep_ms(twait)
            if self._tstop is None:
                break  # Return if stop() called during wait
            twait = time.ticks_diff(self._tstop, time.ticks_ms())
        if self._running and self.func is not None:
            launch(self.func, self.args)  # Timed out: execute callback
        self._tstop = None  # killer not running
        self._running = False  # timer is stopped 
Example #30
Source File: switches.py    From micropython-samples with MIT License 5 votes vote down vote up
def killer():
    pin = Pin('X2', Pin.IN, Pin.PULL_UP)
    while pin.value():
        await asyncio.sleep_ms(50)

# Test for the Switch class passing coros