Python uasyncio.create_task() Examples

The following are 30 code examples of uasyncio.create_task(). 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: asyntest.py    From micropython-async 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 #2
Source File: esp_link.py    From micropython-iot with MIT License 6 votes vote down vote up
def start(self):
        await self.chan.ready()  # Wait for sync
        self.verbose and print('awaiting config')
        line = await self.sreader.readline()
        config = ujson.loads(line)

        self.verbose and print('Setting client config', config)
        self.cl = LinkClient(config, self.swriter, self.verbose)
        self.verbose and print('App awaiting connection.')
        await self.cl
        asyncio.create_task(self.to_server())
        asyncio.create_task(self.from_server())
        t_rep = config[_REPORT]  # Reporting interval (s)
        if t_rep:
            asyncio.create_task(self.report(t_rep))
        await self.crashdet() 
Example #3
Source File: mqtt_as_timeout.py    From micropython-mqtt with MIT License 6 votes vote down vote up
def publish(self, topic, msg, retain=False, qos=0, timeout=None):
        task = None
        start = time.ticks_ms()
        while timeout is None or time.ticks_diff(time.ticks_ms(), start) < timeout:
            # Can't use wait_for because cancelling a wait_for would cancel _publishTimeout
            # Also a timeout in wait_for would cancel _publishTimeout without waiting for
            # the socket lock to be available, breaking mqtt protocol.
            if self._pub_task is None and task is None:
                task = asyncio.create_task(self._publishTimeout(topic, msg, retain, qos))
                self._pub_task = task
            elif task is not None:
                if self._pub_task != task:
                    return  # published
            await asyncio.sleep_ms(20)
        if task is not None:
            async with self.lock:
                task.cancel()
                return 
Example #4
Source File: asnano_sync.py    From micropython-nano-gui with MIT License 6 votes vote down vote up
def main():
    print('Press Pyboard usr button to stop test.')
    # Asynchronously flash Pyboard LED's. Because we can.
    leds = [asyncio.create_task(flash(1, 200)), asyncio.create_task(flash(2, 233))]
    # Task for each meter and GUI LED
    mtasks =[MyMeter(2, 'left').task, MyMeter(50, 'right').task, MyMeter(98, 'bass').task]
    k = Killer()
    while True:
        if await k.wait(800):  # Switch was pressed
            break
        refresh(ssd)
    for task in mtasks + leds:
        task.cancel()
    await asyncio.sleep_ms(0)
    ssd.fill(0)  # Clear display at end.
    refresh(ssd) 
Example #5
Source File: asi2c_i.py    From micropython-iot with MIT License 6 votes vote down vote up
def __init__(self, i2c, pin, pinack, reset=None, verbose=True,
                 cr_go=False, go_args=(), cr_fail=False, f_args=()):
        super().__init__(i2c, pin, pinack, verbose, self.rxbufsize)
        self.reset = reset
        self.cr_go = cr_go
        self.go_args = go_args
        self.cr_fail = cr_fail
        self.f_args = f_args
        if reset is not None:
            reset[0].init(mode=machine.Pin.OUT, value=not (reset[1]))
        # Self measurement
        self.nboots = 0  # No. of reboots of Responder
        self.block_max = 0  # Blocking times: max
        self.block_sum = 0  # Total
        self.block_cnt = 0  # Count
        asyncio.create_task(self._run()) 
Example #6
Source File: app_base.py    From micropython-iot with MIT License 6 votes vote down vote up
def await_msg(self):
        while True:
            line = await self.sreader.readline()
            h, p = chr(line[0]), line[1:]  # Header char, payload
            if h == 'n':  # Normal message
                self.rxmsg.set(p)
            elif h == 'b':
                asyncio.create_task(self.bad_wifi())
            elif h == 's':
                asyncio.create_task(self.bad_server())
            elif h == 'r':
                asyncio.create_task(self.report(ujson.loads(p)))
            elif h == 'k':
                self.tim_boot.trigger(4000)  # hold off reboot (4s)
            elif h in ('u', 'd'):
                up = h == 'u'
                self._status = up
                asyncio.create_task(self.server_ok(up))
            else:
                raise ValueError('Unknown header:', h) 
Example #7
Source File: asyntest.py    From micropython-samples with MIT License 6 votes vote down vote up
def run_ack():
    message = Message()
    ack1 = Message()
    ack2 = Message()
    count = 0
    while True:
        asyncio.create_task(message_wait(message, ack1, 1))
        asyncio.create_task(message_wait(message, ack2, 2))
        message.set(count)
        count += 1
        print('message was set')
        await ack1
        ack1.clear()
        print('Cleared ack1')
        await ack2
        ack2.clear()
        print('Cleared ack2')
        message.clear()
        print('Cleared message')
        await asyncio.sleep(1) 
Example #8
Source File: prim_test.py    From micropython-samples with MIT License 6 votes vote down vote up
def cond_go():
    cond = asyncio.Condition()
    ntasks = 7
    barrier = Barrier(ntasks + 1)
    t1 = asyncio.create_task(cond01_new(cond))
    t3 = asyncio.create_task(cond03_new())
    for n in range(ntasks):
        asyncio.create_task(cond02(n, cond, barrier))
    await barrier  # All instances of cond02 have completed
    # Test wait_for
    barrier = Barrier(2)
    asyncio.create_task(cond04(99, cond, barrier))
    await barrier
    # cancel continuously running coros.
    t1.cancel()
    t3.cancel()
    await asyncio.sleep(0)
    print('Done.') 
Example #9
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 #10
Source File: asi2c_i.py    From micropython-async with MIT License 6 votes vote down vote up
def __init__(self, i2c, pin, pinack, reset=None, verbose=True,
                 cr_go=False, go_args=(), cr_fail=False, f_args=()):
        super().__init__(i2c, pin, pinack, verbose, self.rxbufsize)
        self.reset = reset
        self.cr_go = cr_go
        self.go_args = go_args
        self.cr_fail = cr_fail
        self.f_args = f_args
        if reset is not None:
            reset[0].init(mode=machine.Pin.OUT, value=not (reset[1]))
        # Self measurement
        self.nboots = 0  # No. of reboots of Responder
        self.block_max = 0  # Blocking times: max
        self.block_sum = 0  # Total
        self.block_cnt = 0  # Count
        asyncio.create_task(self._run()) 
Example #11
Source File: ast_pbrw.py    From micropython-async with MIT License 6 votes vote down vote up
def gps_test():
    global gps, uart  # For shutdown
    print('Initialising')
    # Adapt UART instantiation for other MicroPython hardware
    uart = pyb.UART(4, 9600, read_buf_len=200)
    # read_buf_len is precautionary: code runs reliably without it.
    sreader = asyncio.StreamReader(uart)
    swriter = asyncio.StreamWriter(uart, {})
    timer = Delay_ms(cb_timeout)
    sentence_count = 0
    gps = GPS(sreader, swriter, local_offset=1, fix_cb=callback,
                       fix_cb_args=(timer,),  msg_cb = message_cb)
    await asyncio.sleep(2)
    await gps.command(DEFAULT_SENTENCES)
    print('Set sentence frequencies to default')
    #await gps.command(FULL_COLD_START)
    #print('Performed FULL_COLD_START')
    print('awaiting first fix')
    asyncio.create_task(sat_test(gps))
    asyncio.create_task(stats(gps))
    asyncio.create_task(navigation(gps))
    asyncio.create_task(course(gps))
    asyncio.create_task(date(gps))
    await gps.data_received(True, True, True, True)  # all messages
    await change_status(gps, uart) 
Example #12
Source File: asyntest.py    From micropython-async with MIT License 6 votes vote down vote up
def run_ack():
    message = Message()
    ack1 = Message()
    ack2 = Message()
    count = 0
    while True:
        asyncio.create_task(message_wait(message, ack1, 1))
        asyncio.create_task(message_wait(message, ack2, 2))
        message.set(count)
        count += 1
        print('message was set')
        await ack1
        ack1.clear()
        print('Cleared ack1')
        await ack2
        ack2.clear()
        print('Cleared ack2')
        message.clear()
        print('Cleared message')
        await asyncio.sleep(1) 
Example #13
Source File: asyntest.py    From micropython-async with MIT License 6 votes vote down vote up
def ack_test():
    printexp('''message was set
message_wait 1 got message with value 0
message_wait 2 got message with value 0
Cleared ack1
Cleared ack2
Cleared message
message was set
message_wait 1 got message with value 1
message_wait 2 got message with value 1

... text omitted ...

message_wait 1 got message with value 5
message_wait 2 got message with value 5
Cleared ack1
Cleared ack2
Cleared message
I've seen attack ships burn on the shoulder of Orion...
Time to die...
''', 10)
    asyncio.create_task(run_ack())
    asyncio.run(ack_coro(6))

# ************ Test Lock and Message classes ************ 
Example #14
Source File: prim_test.py    From micropython-samples with MIT License 6 votes vote down vote up
def run_ack():
    message = Message()
    ack1 = asyncio.Event()
    ack2 = asyncio.Event()
    count = 0
    while True:
        asyncio.create_task(event_wait(message, ack1, 1))
        asyncio.create_task(event_wait(message, ack2, 2))
        message.set(count)
        count += 1
        print('message was set')
        await ack1.wait()
        ack1.clear()
        print('Cleared ack1')
        await ack2.wait()
        ack2.clear()
        print('Cleared ack2')
        message.clear()
        print('Cleared message')
        await asyncio.sleep(1) 
Example #15
Source File: __init__.py    From micropython-async with MIT License 5 votes vote down vote up
def launch(func, tup_args):
    res = func(*tup_args)
    if isinstance(res, type_coro):
        res = asyncio.create_task(res)
    return res 
Example #16
Source File: asi2c_i.py    From micropython-async with MIT License 5 votes vote down vote up
def _run(self):
        while True:
            # If hardware link exists reboot Responder
            await self.reboot()
            self.txbyt = b''
            self.rxbyt = b''
            await self._sync()
            await asyncio.sleep(1)  # Ensure Responder is ready
            if self.cr_go:
                self.loop.create_task(self.cr_go(*self.go_args))
            while True:
                gc.collect()
                try:
                    tstart = utime.ticks_us()
                    self._sendrx()
                    t = utime.ticks_diff(utime.ticks_us(), tstart)
                except OSError:  # Reboot remote.
                    break
                await asyncio.sleep_ms(Initiator.t_poll)
                self.block_max = max(self.block_max, t)  # self measurement
                self.block_cnt += 1
                self.block_sum += t
            self.nboots += 1
            if self.cr_fail:
                await self.cr_fail(*self.f_args)
            if self.reset is None:  # No means of recovery
                raise OSError('Responder fail.') 
Example #17
Source File: pb_client.py    From micropython-iot with MIT License 5 votes vote down vote up
def start(self):  # Apps must implement a synchronous start method
        asyncio.create_task(self.receiver())
        asyncio.create_task(self.sender())

    # If server is running s_app_cp.py it sends
    # [approx app uptime in secs/5, echoed count, echoed 99] 
Example #18
Source File: i2c_init.py    From micropython-async with MIT License 5 votes vote down vote up
def test():
    asyncio.create_task(receiver())
    asyncio.create_task(sender())
    while True:
        await chan.ready()
        await asyncio.sleep(10)
        if chan.block_cnt:
            print('Blocking time {:d}μs max. {:d}μs mean.'.format(
                chan.block_max, int(chan.block_sum/chan.block_cnt)))
        print('Reboots: ', chan.nboots) 
Example #19
Source File: aremote.py    From micropython-async with MIT License 5 votes vote down vote up
def __init__(self, pin, callback, extended, *args):  # Optional args for callback
        self._ev_start = Message()
        self._callback = callback
        self._extended = extended
        self._addr = 0
        self.block_time = 80 if extended else 73  # Allow for some tx tolerance (?)
        self._args = args
        self._times = array('i',  (0 for _ in range(_EDGECOUNT + 1)))  # +1 for overrun
        if platform == 'pyboard':
            ExtInt(pin, ExtInt.IRQ_RISING_FALLING, Pin.PULL_NONE, self._cb_pin)
        else:  # PR5962 ESP8266 hard IRQ's not supported
            pin.irq(handler = self._cb_pin, trigger = (Pin.IRQ_FALLING | Pin.IRQ_RISING))
        self._edge = 0
        self._ev_start.clear()
        asyncio.create_task(self._run()) 
Example #20
Source File: icon_buttons.py    From micropython-tft-gui with MIT License 5 votes vote down vote up
def _touched(self, x, y): # Process touch
        if self.flash > 0:
            self._show(1)
            self.delay.trigger(self.flash)
        elif self.toggle:
            self.state = (self.state + 1) % self.num_icons
            self._show(self.state)
        if self.lp_callback is not None:
            asyncio.create_task(self.longpress())
        if not self.onrelease:
            self.callback(self, *self.callback_args) # Callback not a bound method so pass self 
Example #21
Source File: buttons.py    From micropython-tft-gui with MIT License 5 votes vote down vote up
def _touched(self, x, y): # Process touch
        if self.litcolor is not None:
            self.fgcolor = self.litcolor
            self.show() # must be on current screen
            self.delay.trigger(Button.lit_time)
        if self.lp_callback is not None:
            asyncio.create_task(self.longpress())
        if not self.onrelease:
            self.callback(self, *self.callback_args) # Callback not a bound method so pass self 
Example #22
Source File: touch_bytecode.py    From micropython-tft-gui with MIT License 5 votes vote down vote up
def __init__(self, controller = "XPT2046", asyn = False, *, confidence = 5, margin = 50, delay = 10, calibration = None):
        if PCB_VERSION == 1:
            self.pin_clock = pyb.Pin("Y8", pyb.Pin.OUT_PP)
            self.pin_clock.value(0)
            self.pin_d_out = pyb.Pin("Y7", pyb.Pin.OUT_PP)
            self.pin_d_in  = pyb.Pin("Y6", pyb.Pin.IN)
            self.pin_irq   = pyb.Pin("Y5", pyb.Pin.IN)
        else:
            self.pin_clock = pyb.Pin("X11", pyb.Pin.OUT_PP)
            self.pin_clock.value(0)
            self.pin_d_out = pyb.Pin("X12", pyb.Pin.OUT_PP)
            self.pin_d_in  = pyb.Pin("Y1", pyb.Pin.IN)
            self.pin_irq   = pyb.Pin("Y2", pyb.Pin.IN)
# set default values
        self.ready = False
        self.touched = False
        self.x = 0
        self.y = 0
        self.buf_length = 0
        cal = TOUCH.DEFAULT_CAL if calibration is None else calibration
        self.asynchronous = False
        self.touch_parameter(confidence, margin, delay, cal)
        if asyn:
            self.asynchronous = True
            asyncio.create_task(self._main_thread())

# set parameters for get_touch()
# res: Resolution in bits of the returned values, default = 10
# confidence: confidence level - number of consecutive touches with a margin smaller than the given level
#       which the function will sample until it accepts it as a valid touch
# margin: Difference from mean centre at which touches are considered at the same position 
# delay: Delay between samples in ms.
# 
Example #23
Source File: ugui.py    From micropython-tft-gui with MIT License 5 votes vote down vote up
def __init__(self):
        self.touchlist = []
        self.displaylist = []
        self.tasklist = []  # Allow instance to register tasks for shutdown
        self.modal = False
        if Screen.current_screen is None: # Initialising class and task
            asyncio.create_task(self._touchtest()) # One task only
            asyncio.create_task(self._garbage_collect())
        Screen.current_screen = self
        self.parent = None 
Example #24
Source File: delay_ms.py    From micropython-tft-gui with MIT License 5 votes vote down vote up
def _trig(self, can):
        if can:
            self._ktask.cancel()
        self._ktask = asyncio.create_task(self._timer(can)) 
Example #25
Source File: __init__.py    From micropython-tft-gui with MIT License 5 votes vote down vote up
def launch(func, tup_args):
    res = func(*tup_args)
    if isinstance(res, type_coro):
        res = asyncio.create_task(res)
    return res 
Example #26
Source File: screentest.py    From micropython-tft-gui with MIT License 5 votes vote down vote up
def __init__(self):
        super().__init__()
        self.tasks = []  # Control cancellation explicitly
        Label((0, 0), font = font14, value = 'Green dial runs only')
        Label((0, 30), font = font14, value = 'when screen is visible')
        Label((0, 120), font = font14, value = "Yellow dial's value is")
        Label((0, 150), font = font14, value = 'computed continuously.')
        self.dial1 = Dial((350, 10), fgcolor = GREEN, border = 2, pointers = (0.9, 0.7))
        self.dial2 = Dial((350, 120), fgcolor = YELLOW, border = 2,  pointers = (0.9, 0.7))
        self.pause = False  # asyncio can't pause coros so handle at application level
        self.tasks.append(asyncio.create_task(self.mainthread(self.dial1, True)))
        self.tasks.append(asyncio.create_task(self.mainthread(self.dial2)))

        fwdbutton(0, 242, BackScreen)
        self.backbutton(390, 242) 
Example #27
Source File: pt.py    From micropython-tft-gui with MIT License 5 votes vote down vote up
def populate(self, curve):
        self.aqu_task = asyncio.create_task(self.acquire(curve))
        self.reg_task(self.aqu_task, True) 
Example #28
Source File: fusion_async.py    From micropython-fusion with MIT License 5 votes vote down vote up
def start(self, slow_platform=False):
        data = await self.read_coro()
        if len(data) == 2 or (self.expect_ts and len(data) == 3):
            asyncio.create_task(self._update_nomag(slow_platform))
        else:
            asyncio.create_task(self._update_mag(slow_platform)) 
Example #29
Source File: prim_test.py    From micropython-samples with MIT License 5 votes vote down vote up
def queue_go():
    myq = asyncio.Queue(5)
    asyncio.create_task(fillq(myq))
    await mtq(myq)
    t = asyncio.create_task(fillq(myq))
    await asyncio.sleep(1)
    print('Queue filled. Cancelling fill task. Queue should be full.')
    t.cancel()
    await mtq(myq)
    t = asyncio.create_task(myq.get())
    await asyncio.sleep(1)
    print('Cancelling attempt to get from empty queue.')
    t.cancel()
    print('Queue size:', myq.qsize()) 
Example #30
Source File: as_GPS.py    From micropython-async with MIT License 5 votes vote down vote up
def _run(self):
        while True:
            res = await self._sreader.readline()
            try:
                res = res.decode('utf8')
            except UnicodeError:  # Garbage: can happen e.g. on baudrate change
                continue
            asyncio.create_task(self._update(res))
            await asyncio.sleep(0)  # Ensure task runs and res is copied

    # Update takes a line of text