예제 #1
0
async def demo_async():
    wifi = Wifi('ybb-home')
    print(wifi.check_wifi_config())
    print(await wifi.async_connect())
    await asyncio.sleep(1)
    print(wifi.get_info())
    asyncio.create_task(wifi.monitor())
    for i in range(0, 50):
        print(i)
        if i == 15:
            print("test disconnection")
            wifi.disconnect()
        await asyncio.sleep(1)
예제 #2
0
async def main():
    tasks = [asyncio.create_task(bar(70))]
    tasks.append(barking(21))  #Add to the end of the tasks array
    tasks.append(asyncio.wait_for(foo(10), 7))
    asyncio.create_task(do_cancel(tasks[0]))
    res = None
    try:
        res = await asyncio.gather(*tasks, return_exceptions=True)
    except asyncio.TimeoutError:  # These only happen if return_exceptions is False
        print('Timeout')  # With the default times, cancellation occurs first
    except asyncio.CancelledError:
        print('Cancelled')
    print('Result: ', res)
예제 #3
0
 def __sub_callback(self, topic, pay): 
     s = pay.decode("utf-8")
     log.info('Received %s: %s' , topic.decode("utf-8"), s)
     try:
         json = loads(s)
         if ENCRYPTED_INPUT: # 处理加密
             st = Sec()
             json = st.dec_payload(json)
         create_task(self.__opc.op_request(json))
     except BaseException as e:
         m = "Process message failed: %r" % e
         log.error(m)
         self.publish_op_log(None, None, result(500, m))
예제 #4
0
async def main():
    t1 = asyncio.create_task(task(1, 4, 100))
    t2 = asyncio.create_task(task(2, 2, 250))

    micropython.heap_lock()

    print("start")
    await asyncio.sleep_ms(5)
    print("sleep")
    await asyncio.sleep_ms(350)
    print("finish")

    micropython.heap_unlock()
예제 #5
0
async def bart():
    barrier = Barrier(4, my_coro, ('my_coro running', ))
    for x in range(3):
        asyncio.create_task(report1(barrier, x))
    await asyncio.sleep(4)
    assert barrier.busy()
    await barrier
    await asyncio.sleep(0)
    assert not barrier.busy()
    # Must yield before reading result(). Here we wait long enough for
    await asyncio.sleep_ms(1500)  # coro to print
    barrier.result().cancel()
    await asyncio.sleep(2)
예제 #6
0
 def __init__(self, pin, suppress=False, sense=None):
     self.pin = pin  # Initialise for input
     self._supp = suppress
     self._dblpend = False  # Doubleclick waiting for 2nd click
     self._dblran = False  # Doubleclick executed user function
     self._tf = False
     self._ff = False
     self._df = False
     self._ld = False  # Delay_ms instance for long press
     self._dd = False  # Ditto for doubleclick
     self.sense = pin.value(
     ) if sense is None else sense  # Convert from electrical to logical value
     self.state = self.rawstate()  # Initial state
     asyncio.create_task(self.buttoncheck())  # Thread runs forever
예제 #7
0
async def test_async():
    relay = Relay(2)
    relay.on()
    print("on")
    asyncio.sleep(1)
    relay.off()
    print("off")
    asyncio.sleep(1)
    asyncio.create_task(relay.async_blink())
    for i in range(0,10):
        print(i)
        if i == 5:
            relay.stop_async_blink()
        await asyncio.sleep(1)
예제 #8
0
async def queue_go():
    q = Queue(10)
    asyncio.create_task(foo(q))
    asyncio.create_task(bar(q))
    await asyncio.sleep(3)
    for n in range(4):
        asyncio.create_task(q_put(n, q))
    await asyncio.sleep(1)
    assert q.qsize() == 10
    await q.get()
    await asyncio.sleep(0.1)
    assert q.qsize() == 10
    while not q.empty():
        await q.get()
        await asyncio.sleep(0.1)
    assert q.empty()
    print('Competing put tasks test complete')

    for n in range(4):
        asyncio.create_task(q_get(n, q))
    await asyncio.sleep(1)
    x = 0
    while not q.full():
        await q.put(x)
        await asyncio.sleep(0.3)
        x += 1
    assert q.qsize() == 10
    print('Competing get tasks test complete')
    await asyncio.gather(putter(q), getter(q))
    print('Queue tests complete')
    print("I've seen starships burn off the shoulder of Orion...")
    print("Time to die...")
예제 #9
0
 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 coro
         tft = Screen.get_tft()
         if tft.text_font is None:
             raise UguiException(
                 'The lcd set_font method has not been called')
         asyncio.create_task(self._touchtest())  # One coro only
         asyncio.create_task(self._garbage_collect())
     Screen.current_screen = self
     self.parent = None
예제 #10
0
async def default(scale, lbl):
    asyncio.create_task(ssd.do_refresh(4))
    cv = -1.0  # Current
    val = 1.0
    while True:
        v1, v2 = val, cv
        steps = 400
        delta = (val - cv) / steps
        for _ in range(steps):
            cv += delta
            scale.value(cv)
            lbl.value('{:4.3f}'.format(cv))
            await asyncio.sleep_ms(250)
        val, cv = v2, v1
예제 #11
0
 def trigger(self, duration=0):  # Update end time
     self._running = True
     if duration <= 0:
         duration = self.duration
     tn = time.ticks_add(time.ticks_ms(), duration)  # new end time
     self.verbose and self._tstop is not None and self._tstop > tn \
         and print("Warning: can't reduce Delay_ms time.")
     # Start killer if can allocate and killer is not running
     sk = self.can_alloc and self._tstop is None
     # The following indicates ._killer is running: it will be
     # started either here or in ._run
     self._tstop = tn
     if sk:  # ._killer stops the delay when its period has elapsed
         asyncio.create_task(self._killer())
예제 #12
0
async def run_sema_test(bounded):
    num_coros = 5
    barrier = Barrier(num_coros + 1)
    if bounded:
        semaphore = BoundedSemaphore(3)
    else:
        semaphore = Semaphore(3)
    for n in range(num_coros):
        asyncio.create_task(run_sema(n, semaphore, barrier))
    await barrier  # Quit when all coros complete
    try:
        semaphore.release()
    except ValueError:
        print('Bounded semaphore exception test OK')
예제 #13
0
def test_async():
    relay = Dimmer(2)
    asyncio.create_task(relay.async_blink())
    for i in range(0,10):
        print(i)
        if i == 4:
            relay.stop_async_blink()
        await asyncio.sleep(1)
    asyncio.create_task(relay.async_fading(10, 1000))
    for i in range(0,30):
        print(i)
        if i == 20:
            relay.stop_async_fading()
        await asyncio.sleep(1)
async def main():
    waiting_task = asyncio.create_task(
        wait_task(asyncio.create_task(sleep_task())))

    print("main sleep")
    await asyncio.sleep(0)
    print("main sleep")
    await asyncio.sleep(0)

    waiting_task.cancel()
    print("main wait")
    try:
        await waiting_task
    except asyncio.CancelledError as er:
        print(repr(er))
예제 #15
0
 async def bounce():
     while (True):
         print('bounce forward')
         asyncio.create_task(s1.move(1, 300))
         print('wait')
         await asyncio.sleep(10)
         print('bounce stop')
         s1.stop()
         await asyncio.sleep(1)
         print('bounce backwards')
         asyncio.create_task(s1.move(-1, 300))
         await asyncio.sleep(10)
         print('bounce stop')
         s1.stop()
         await asyncio.sleep(1)
예제 #16
0
async def do_drift(minutes):
    global gps
    print('Setting up GPS.')
    gps = await setup()
    print('Waiting for time data.')
    await gps.ready()
    print('Setting RTC.')
    await gps.set_rtc()
    print('Measuring drift.')
    terminate = Event()
    asyncio.create_task(killer(terminate, minutes))
    change = await drift_test(terminate, gps)
    ush = int(60 * change / minutes)
    spa = int(ush * 365 * 24 / 1000000)
    print('Rate of change {}μs/hr {}secs/year'.format(ush, spa))
예제 #17
0
 async def writer(self):
     self.verbose and print('Started writer')
     while True:
         for _ in range(4):
             gc.collect()
             data = [
                 self.tx_msg_id, self.cl.connects,
                 gc.mem_free(), self.cm.dupe, self.cm.miss
             ]
             self.tx_msg_id += 1
             await self.cl  # Only launch write if link is up
             print('Sent', data, 'to server app\n')
             dstr = ujson.dumps(data)
             asyncio.create_task(self.cl.write(dstr, wait=False))
         await asyncio.sleep(5)
예제 #18
0
    def __init__(self, host = 'pool.ntp.org', poll = MAX_POLL,
                 max_startup_delta = 1, debug = False):
        self.host = host
        self.sock = None
        self.addr = None
        self.rstr = None
        self.wstr = None
        self.req_poll = poll
        self.poll = MIN_POLL
        self.max_startup_delta = int(max_startup_delta * 1000000)
        self.rtc = RTC()
        self.debug = debug

        asyncio.create_task(self._poll_task())
        asyncio.create_task(self._adj_task())
예제 #19
0
def delayed_task(sec, func, tup_args, is_coro=False):
    from uasyncio import sleep_ms, create_task

    async def __task(sec, func, tup_args):
        await sleep_ms(sec)
        func(tup_args)

    async def __coro_task(sec, func, tup_args):
        await sleep_ms(sec)
        await func(tup_args)

    if is_coro:
        create_task(__coro_task(sec, func, tup_args))
    else:
        create_task(__task(sec, func, tup_args))
예제 #20
0
 def _execute_sync(self, topic, msg, retained):
     _log.debug("mqtt received:", topic, msg, retained, local_only=True)
     # optional safety feature if memory allocation fails on receive of messages.
     # Should actually never happen in a user controlled environment.
     # mqtt_as must support it for code having any effect.
     """ # Not enabled in mqtt_as as typically not needed
     if topic is None or msg is None:
         self.__dropped += 1
         _log.error("Received message that didn't fit into RAM on topic {!s}".format(topic),
                    local_only=True)
         return
     """
     topic = topic.decode()
     msg = msg.decode()
     try:
         msg = ujson.loads(msg)
     except ValueError:
         pass  # maybe not a json string, no way of knowing
     if self._isDeviceSubscription(topic):
         topic = self._convertToDeviceTopic(topic)
     found = False
     for sub in self._subs:
         if self.matchesSubscription(topic,
                                     sub[0],
                                     ignore_command=len(sub) == 4):
             if config.MQTT_MAX_CONCURRENT_EXECUTIONS != -1:
                 dr = self.__active_cbs >= config.MQTT_MAX_CONCURRENT_EXECUTIONS
             else:
                 dr = 0
             if dr:
                 self.__dropped += 1
                 _log.error("dropping message of topic",
                            topic,
                            "component",
                            sub[2],
                            "too many active cbss:",
                            "{!s}".format(self.__active_cbs),
                            local_only=True)
             else:
                 self.__active_cbs += 1
                 asyncio.create_task(
                     self._execute_callback(sub, topic, msg, retained))
             found = True
     if found is False:
         _log.warn("Subscribed topic",
                   topic,
                   "not found, should solve itself. not yet unsubscribed",
                   local_only=True)
async def main():
    usb = pyb.USB_VCP()
    pyb.Pin("EN_3V3").on() #Aktivation der Spannungsquelle 
    

    task_ =  uasyncio.create_task(start_measurment("X3",usb,15, 10)) #Daten des ersten Pins
    task__ = uasyncio.create_task(start_measurment("Y7",usb,5, 5))   #Daten des zweiten Pins 
    befehl = uasyncio.create_task(empfanger(usb)) #Kommunikation zwischen Pyboard und Komputer

    print("Starten Haupt Threads")
    await task_
    await task__
    await befehl
    
    empfanger(usb)
    print("Ende des Programm")
예제 #22
0
    def restore_handler(self, topic, payload, retained):
        """ Gets called when the property should be restored from mqtt """
        # Retained messages are not allowed on /set topics
        if topic.endswith(T_SET):
            return

        # Unsubscribe from topic and remove the callback handler
        asyncio.create_task(self.node.device.unsubscribe(topic))
        del self.node.device.callback_topics[topic]

        if payload_is_valid(self, payload):
            if payload != self._value:
                if self.on_message:
                    self.on_message(topic, payload, retained)

                self._value = payload
예제 #23
0
async def do_time(minutes):
    fstr = '{}ms Time: {:02d}:{:02d}:{:02d}:{:06d}'
    print('Setting up GPS.')
    gps = await setup()
    print('Waiting for time data.')
    await gps.ready()
    print('Setting RTC.')
    await gps.set_rtc()
    terminate = asyncio.Event()
    asyncio.create_task(killer(terminate, minutes))
    while not terminate.is_set():
        await asyncio.sleep(1)
        # In a precision app, get the time list without allocation:
        t = gps.get_t_split()
        print(fstr.format(gps.get_ms(), t[0], t[1], t[2], t[3]))
    gps.close()
예제 #24
0
    async def Run(self, aSleep: int = 5):
        await self.SetPower(True)

        asyncio.create_task(self.Reader())

        while True:
            await self.AT('') # ToDo. readline hangs without it !

            await self.AT("+CGMI") # manufacturer
            #await self.AT("+CGMM") # Module name

            await self.AT('+CGNSPWR=1') # Power on and wait 2s
            await self.AT('+CGNSINF')
            #await self.AT('+CGNSPWR=0', 3) # Power off

            await asyncio.sleep(aSleep)
예제 #25
0
    async def run(self, data_interval=1, battery_data_interval=300):
        """
        Start running the wireless module. Connects to MQTT and starts the data and battery loops.
        :param data_interval: Integer representing number of seconds to wait before sending data.
        :param battery_interval: Integer representing number of seconds to wait before sending battery voltage data
        """
        # Start publishing battery data straight away
        asyncio.create_task(self.start_battery_loop(battery_data_interval))

        # Attempt to connect to MQTT (will block until successful)
        self.status_led.set_state(WmState.ConnectingToMqtt)
        sub_topics = [self.sub_start_topic, self.sub_stop_topic]
        await self.mqtt.connect_and_subscribe(sub_topics, self.sub_cb)

        # Start the main publishing loop
        asyncio.create_task(self.start_data_loop(data_interval))
예제 #26
0
    def __init__(self,
                 url,
                 headers={},
                 method="GET",
                 name="HTTP request",
                 interval=60):
        super().__init__(id="http", name=name, type="http")
        self.url = url
        self.headers = headers
        self.method = method
        self.interval = interval

        self.p_response = HomieProperty(id="response", name="HTTP response")
        self.add_property(self.p_response)

        asyncio.create_task(self.update_data())
예제 #27
0
 async def _connected_handler(self, client):
     try:
         await self.publish(self.getDeviceTopic(
             config.MQTT_AVAILABILITY_SUBTOPIC),
                            "online",
                            qos=1,
                            retain=True)
         # if it hangs here because connection is lost, it will get canceled when reconnected.
         if self.__first_connect is True:
             # only log on first connection, not on reconnect as nothing has changed here
             await _log.asyncLog(
                 "info",
                 str(os.name if platform == "linux" else os.uname()))
             await _log.asyncLog(
                 "info", "Client version: {!s}".format(config.VERSION))
             self.__first_connect = False
         elif self.__first_connect is False:
             await _log.asyncLog("debug", "Reconnected")
         # subscribe topics because clean session is used. Some components might be added
         # before connection has been made so subscribe on first connect too.
         if self._sub_task is not None:
             self._sub_task.cancel()
         self._sub_task = asyncio.create_task(self._subscribeTopics())
         # TODO: change to asyncio.gather() as soon as cancelling gather works.
         for cb in self._reconnected_subs:
             res = cb(client)
             if type(res) == type_gen:
                 await res
         self._connected_task = None
     except asyncio.CancelledError:
         if self._sub_task is not None:
             self._sub_task.cancel()
async def main():
    # Call function directly via an await
    print(await foo())

    # Create a task and await on it
    task = asyncio.create_task(foo())
    print(await task)
예제 #29
0
 async def _preprocessor(self,
                         coroutine,
                         *args,
                         timeout=None,
                         await_connection=True):
     task = None
     start = time.ticks_ms()
     i = 0 if len(args) == 4 else 1  # 0: publish, 1:(un)sub
     try:
         while timeout is None or time.ticks_diff(time.ticks_ms(),
                                                  start) < timeout * 1000:
             if not await_connection and not self._isconnected:
                 return False
             if self._ops_tasks[i] is task is None:
                 task = asyncio.create_task(
                     self._operationTimeout(coroutine, *args, i=i))
                 self._ops_tasks[i] = task
             elif task:
                 if self._ops_tasks[i] is not task:
                     return True  # published
             await asyncio.sleep_ms(20)
         self.dprint("timeout on", "(un)sub" if i else "publish", args)
         raise asyncio.TimeoutError
     except asyncio.CancelledError:
         raise  # the caller should be cancelled too
     finally:
         if task and self._ops_tasks[i] is task:
             async with self.lock:
                 task.cancel()
예제 #30
0
파일: o.py 프로젝트: uraich/mpy_ucad
 def measure(self,sreader,swriter):
     print("measure task")
     trace_task = asyncio.create_task(self.trace.read_trace())
     await trace_task
     print("read trace ready")
     swriter.write(self.trace.traceBuf)
     await swriter.drain()