Python uasyncio.get_event_loop() Examples

The following are 30 code examples of uasyncio.get_event_loop(). 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: asyn.py    From micropython-mqtt with MIT License 7 votes vote down vote up
def launch(func, tup_args):
    res = func(*tup_args)
    if isinstance(res, type_coro):
        loop = asyncio.get_event_loop()
        loop.create_task(res)


# To access a lockable resource a coro should issue
# async with lock_instance:
#    access the locked resource

# Alternatively:
# await lock.acquire()
# try:
#   do stuff with locked resource
# finally:
#   lock.release
# Uses normal scheduling on assumption that locks are held briefly. 
Example #2
Source File: __init__.py    From micropython-samples with MIT License 6 votes vote down vote up
def run(self, host="127.0.0.1", port=8081, debug=False, lazy_init=False, log=None):
        if log is None and debug >= 0:
            import ulogging
            log = ulogging.getLogger("picoweb")
            if debug > 0:
                log.setLevel(ulogging.DEBUG)
        self.log = log
        gc.collect()
        self.debug = int(debug)
        self.init()
        if not lazy_init:
            for app in self.mounts:
                app.init()
        loop = asyncio.get_event_loop()
        if debug > 0:
            print("* Running on http://%s:%s/" % (host, port))
        loop.create_task(asyncio.start_server(self._handle, host, port))
        loop.run_forever()
        loop.close() 
Example #3
Source File: rfpump.py    From pysmartnode with MIT License 6 votes vote down vote up
def changeMode(self, topic, msg, retain):
        print("changeMode", topic, msg, retain, self._repeating_mode)
        if msg not in _mqtt.payload_on and msg not in _mqtt.payload_off:
            raise ValueError("unsupported payload {!r}".format(msg))
        if msg in _mqtt.payload_on:
            if self._repeating_mode is True:
                # already on
                return True
            elif self._repeating_mode is False:
                await super().on_message(self._topic, "OFF", retain)
                self._off_coro = self._repeating()
                asyncio.get_event_loop().create_task(self._off_coro)
        elif msg in _mqtt.payload_off:
            if self._off_coro is not None:
                asyncio.cancel(self._off_coro)  # will shut down pump
                self._off_coro = None
            if self._repeating_mode is True:
                return True
            elif self._repeating_mode is False:
                await super().on_message(self._topic, "OFF", retain)
                return True
        return True 
Example #4
Source File: phSensor.py    From pysmartnode with MIT License 6 votes vote down vote up
def __init__(self, adc, adc_multi, voltage_calibration_0, pH_calibration_value_0,
                 voltage_calibration_1, pH_calibration_value_1,
                 precision=2, interval=None, mqtt_topic=None,
                 friendly_name=None, discover=True):
        # This makes it possible to use multiple instances of MySensor
        global _unit_index
        _unit_index += 1
        super().__init__(COMPONENT_NAME, __version__, _unit_index, discover)
        self._interval = interval or config.INTERVAL_SENSOR_PUBLISH
        self._topic = mqtt_topic
        self._frn = friendly_name
        self._adc = ADC(adc)
        self._adc_multi = adc_multi

        self.__ph = None

        self._prec = int(precision)

        self._v0 = voltage_calibration_0
        self._v1 = voltage_calibration_1
        self._ph0 = pH_calibration_value_0
        self._ph1 = pH_calibration_value_1
        gc.collect()
        if self._interval > 0:  # if interval==-1 no loop will be started
            asyncio.get_event_loop().create_task(self._loop()) 
Example #5
Source File: switches.py    From micropython-samples with MIT License 6 votes vote down vote up
def test_btncb():
    s = '''
press toggles red
release toggles green
double click toggles yellow
long press toggles blue
'''
    print('Test of pushbutton executing callbacks.')
    print(helptext)
    print(s)
    pin = Pin('X1', Pin.IN, Pin.PULL_UP)
    red = LED(1)
    green = LED(2)
    yellow = LED(3)
    blue = LED(4)
    pb = Pushbutton(pin)
    pb.press_func(toggle, (red,))
    pb.release_func(toggle, (green,))
    pb.double_func(toggle, (yellow,))
    pb.long_func(toggle, (blue,))
    loop = asyncio.get_event_loop()
    loop.run_until_complete(killer()) 
Example #6
Source File: mqtt.py    From pysmartnode with MIT License 6 votes vote down vote up
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")
                # resubscribe topics because clean session is used
                if self._sub_coro is not None:
                    asyncio.cancel(self._sub_coro)
                self._sub_coro = self._subscribeTopics()
                asyncio.get_event_loop().create_task(self._sub_coro)
            for cb in self._reconnected_subs:
                res = cb(client)
                if type(res) == type_gen:
                    await res
            self._connected_coro = None
        except asyncio.CancelledError:
            if self._sub_coro is not None:
                asyncio.cancel(self._sub_coro) 
Example #7
Source File: switches.py    From micropython-samples with MIT License 6 votes vote down vote up
def test_sw():
    s = '''
close pulses green
open pulses red
'''
    print('Test of switch scheduling coroutines.')
    print(helptext)
    print(s)
    pin = Pin('X1', Pin.IN, Pin.PULL_UP)
    red = LED(1)
    green = LED(2)
    sw = Switch(pin)
    # Register coros to launch on contact close and open
    sw.close_func(pulse, (green, 1000))
    sw.open_func(pulse, (red, 1000))
    loop = asyncio.get_event_loop()
    loop.run_until_complete(killer())

# Test for the switch class with a callback 
Example #8
Source File: logging_full.py    From pysmartnode with MIT License 6 votes vote down vote up
def log(name, level, *message, local_only=False, return_only=False, timeout=None):
    if level == "debug" and not config.DEBUG:  # ignore debug messages if debug is disabled
        return
    if hasattr(config, "RTC_SYNC_ACTIVE") and config.RTC_SYNC_ACTIVE:
        if hasattr(time, "strftime"):
            print("[{}]".format(time.strftime("%Y-%m-%d %H:%M:%S")), "[{}]".format(name),
                  "[{}]".format(level), *message)
        else:
            t = time.localtime()
            print("[{}-{:02d}-{:02d} {:02d}:{:02d}:{:02d}]".format(*t), "[{}]".format(name),
                  "[{}]".format(level), *message)
    else:
        print("[{!s}] [{!s}]".format(name, level), *message)
    if return_only:
        return
    if not local_only:
        asyncio.get_event_loop().create_task(asyncLog(name, level, *message, timeout=timeout,
                                                      await_connection=True)) 
Example #9
Source File: prim_test.py    From micropython-samples with MIT License 6 votes vote down vote up
def event_test():
    printexp('''Test Lock class
Test Event class
waiting for event
run_lock 1 waiting for lock
run_lock 1 acquired lock
run_lock 2 waiting for lock
run_lock 3 waiting for lock
Waiting 5 secs before setting event
run_lock 1 released lock
run_lock 2 acquired lock
run_lock 2 released lock
run_lock 3 acquired lock
run_lock 3 released lock
event was set
got event
Event status OK
Tasks complete
''', 5)
    asyncio.get_event_loop().run_until_complete(run_event_test())

# ************ Barrier test ************ 
Example #10
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 #11
Source File: __init__.py    From pysmartnode with MIT License 6 votes vote down vote up
def __init__(self, component_name, version, unit_index: int, discover=True):
        self._next_component = None  # needed to keep a list of registered components
        global _components
        if _components is None:
            _components = self
        else:
            c = _components
            while c is not None:
                if c._next_component is None:
                    c._next_component = self
                    break
                c = c._next_component
        # Workaround to prevent every component object from creating a new asyncio task for
        # network oriented initialization as this would lead to an asyncio queue overflow.
        global _init_queue_start
        if _init_queue_start is None:
            _init_queue_start = self
            asyncio.get_event_loop().create_task(self.__initNetworkProcess())
        self.COMPONENT_NAME = component_name
        self.VERSION = version
        self._count = unit_index
        self.__discover = discover 
Example #12
Source File: logging_light.py    From pysmartnode with MIT License 5 votes vote down vote up
def _log(self, level, *message, local_only=False, timeout=None):
        print("[{!s}]".format(level), *message)
        if timeout == 0:
            return
        if config.getMQTT() and not local_only:
            message = (b"{} " * len(message)).format(*message)
            asyncio.get_event_loop().create_task(
                config.getMQTT().publish(self.base_topic.format(level), message, qos=1,
                                         timeout=timeout, await_connection=True))
            # format message as bytes so there's no need to encode it later. 
Example #13
Source File: aswitch.py    From pysmartnode with MIT License 5 votes vote down vote up
def launch(func, tup_args):
    res = func(*tup_args)
    if isinstance(res, type_gen):
        loop = asyncio.get_event_loop()
        loop.create_task(res) 
Example #14
Source File: mqtt.py    From pysmartnode with MIT License 5 votes vote down vote up
def schedulePublish(self, topic, msg, retain=False, qos=0, timeout=None,
                        await_connection=True):
        asyncio.get_event_loop().create_task(
            self.publish(topic, msg, retain, qos, timeout, await_connection))

    # Await broker connection. Subclassed to reduce canceling time from 1s to 50ms 
Example #15
Source File: switch.py    From pysmartnode with MIT License 5 votes vote down vote up
def on(self):
        """Turn switch on. Can be used by other components to control this component"""
        if self.lock.locked() is True and self._wfl is False:
            return False
        async with self.lock:
            res = await self._on()  # if _on() returns True the value should be published
            if res is True:
                self._setState(True)
                if self._pub_task:
                    asyncio.cancel(self._pub_task)
                    self._pub_task = None
                self._pub_task = asyncio.get_event_loop().create_task(self.__publish("ON"))            
            return res 
Example #16
Source File: aswitch.py    From pysmartnode with MIT License 5 votes vote down vote up
def __init__(self, pin):
        self.pin = pin  # Should be initialised for input with pullup
        self._open_func = False
        self._close_func = False
        self.switchstate = self.pin.value()  # Get initial state
        loop = asyncio.get_event_loop()
        loop.create_task(self.switchcheck())  # Thread runs forever 
Example #17
Source File: mqtt_iot.py    From pysmartnode with MIT License 5 votes vote down vote up
def scheduleSubscribe(self, topic, callback_coro, qos=0):
        asyncio.get_event_loop().create_task(self.subscribe(topic, callback_coro, qos)) 
Example #18
Source File: mock_asyncio.py    From microdot with MIT License 5 votes vote down vote up
def get_event_loop():
    _calls.append(('get_event_loop',))
    return loop 
Example #19
Source File: abutton.py    From pysmartnode with MIT License 5 votes vote down vote up
def launch(func, tup_args):
    res = func(*tup_args)
    if isinstance(res, type_gen):
        loop = asyncio.get_event_loop()
        loop.create_task(res) 
Example #20
Source File: mock_asyncio.py    From microdot with MIT License 5 votes vote down vote up
def run_forever(self):
        _calls.append(('run_forever',))

        async def rf():
            s = mock_socket.socket()
            while True:
                fd, addr = s.accept()
                fd = mock_socket.FakeStreamAsync(fd)
                await self.coro(fd, fd)

        asyncio.get_event_loop().run_until_complete(rf()) 
Example #21
Source File: test_request_asyncio.py    From microdot with MIT License 5 votes vote down vote up
def _run(coro):
    return asyncio.get_event_loop().run_until_complete(coro) 
Example #22
Source File: test_response_asyncio.py    From microdot with MIT License 5 votes vote down vote up
def _run(coro):
    return asyncio.get_event_loop().run_until_complete(coro) 
Example #23
Source File: microdot_asyncio.py    From microdot with MIT License 5 votes vote down vote up
def run(self, host='0.0.0.0', port=5000, debug=False):
        self.debug = debug

        async def serve(reader, writer):
            if not hasattr(writer, 'awrite'):  # pragma: no cover
                # CPython provides the awrite and aclose methods in 3.8+
                async def awrite(self, data):
                    self.write(data)
                    await self.drain()

                async def aclose(self):
                    self.close()
                    await self.wait_closed()

                from types import MethodType
                writer.awrite = MethodType(awrite, writer)
                writer.aclose = MethodType(aclose, writer)

            await self.dispatch_request(reader, writer)

        if self.debug:  # pragma: no cover
            print('Starting async server on {host}:{port}...'.format(
                host=host, port=port))
        loop = asyncio.get_event_loop()
        loop.run_until_complete(asyncio.start_server(serve, host, port))
        loop.run_forever()
        loop.close()  # pragma: no cover 
Example #24
Source File: task.py    From esp8266 with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def register(self) :
        loop = uasyncio.get_event_loop()
        loop.create_task(self.loop())
        self.state = TaskBase.RUNNING
        return self 
Example #25
Source File: cmd.py    From esp8266 with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def run_event_loop():
    import uasyncio
    print("Running event loop... (^C to exit)")
    uasyncio.get_event_loop().run_forever() 
Example #26
Source File: controller.py    From esp8266 with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def reboot(self, delay_ms=1342) :
        loop = uasyncio.get_event_loop()
        logging.info("Going down for reboot in {}ms ...", delay_ms)
        loop.call_later_ms(delay_ms, core.util.reboot) 
Example #27
Source File: __init__.py    From esp8266 with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def resume() :
    uasyncio.get_event_loop().run_forever() 
Example #28
Source File: __init__.py    From esp8266 with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def run(self, debug=False):
        if debug:
            import logging
            logging.basicConfig(level=logging.DEBUG)

        loop = asyncio.get_event_loop()
        this = self

        @asyncio.coroutine
        def serve(reader, writer):
            yield from this.serve(reader, writer)

        loop.call_soon(asyncio.start_server(
            client_coro=serve,
            host=self._bind_addr,
            port=self._port,
            backlog=self._backlog
        ))
        loop.run_forever()
        loop.close()


#class EchoHandler:
#    def __init__(self):
#        pass
#
#    def handle_request(self, reader, writer, tcp_request):
#        data = yield from reader.readline()
#        return False, data



#def test():
#    server = TCPServer(port=80, handler=EchoHandler())
#   server.run() 
Example #29
Source File: fusiontest_as6.py    From micropython-fusion with MIT License 5 votes vote down vote up
def test_task():
    await fuse.start()  # Start the update task
    loop = asyncio.get_event_loop()
    await display() 
Example #30
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())