def start(mqtt, config): period = config.get( "period", 1000) # get period from config with a default of 1000ms log.info("start called, period=%d", period) bl = Blinker(mqtt.client, config["topic"], period, config["b_topic"]) loop.create_task(bl.blinker(mqtt.client)) mqtt.on_init(bl.hook_it_up(mqtt))
async def _mqtt_handler(cls, connected): fail_led(not connected) if connected: log.info("MQTT connected (->%d)", len(cls._mqtt_cb)) else: log.info("MQTT disconnected (->%d)", len(cls._mqtt_cb)) for cb in cls._mqtt_cb: loop.create_task(cb(connected))
def run(self): if self.is_sdl: while True: pass else: from uasyncio import Loop from async_utils import lv_async lva = lv_async() try: Loop.run_forever() except KeyboardInterrupt: print("User interrupt")
async def connected(cls, mqtt, config): topic = config["topic"] getLogger("main").info("Logging to %s", topic) # flush what we'd need cut due to resize maxsize = config.get("loop_sz", 1400) getLogger("main").info("Log buf: %d/%d bytes", cls._qlen, cls._qmax) while cls._qlen > maxsize*3//4: await cls.push(mqtt.client, topic) # re-init including resize MQTTLog.init( minlevel=config.get("loop_level", WARNING), maxsize=maxsize, ) getLogger("main").info("Log buf: %d/%d bytes", cls._qlen, cls._qmax) # launch regular flusher loop.create_task(MQTTLog.run(mqtt.client, topic))
def main(): # function keeps global namespace clean if not safemode and hasattr(board, "syspath"): sys.path[100:] = board.syspath # sys.path += board.syspath if hasattr(board, "modules") and board.modules: from mqtt import MQTT from uasyncio import Loop as loop # global default asyncio exception handler def def_exception_handler(loop, context): log.error(context["message"]) log.exc( context["exception"], "coro: %s; future: %s", context["future"].coro, context["future"], ) def lm(): log.info("MEM free=%d", gc.mem_free()) loop.set_exception_handler(def_exception_handler) lm() for name in board.modules: try: log.info("Loading %s" % name) mod = __import__(name) fun = getattr(mod, "start", None) if fun: config = getattr(board, name, {}) log.info(" config: [%s]", ", ".join(iter(config))) lvl = config.pop("log", None) if lvl: log.info(" log level: [%d]", lvl) logging.getLogger(name).setLevel(lvl) fun(MQTT, config) except ImportError as e: log.error(str(e)) except Exception as e: log.exc(e, "Cannot start %s: ", name) lm() # micropython.mem_info() # log.warning("Starting asyncio loop") loop.run_forever()
async def sender(self, pub): Loop.create_task(self._ticker()) while True: try: # publish what we've got if self.tx_len > 0: tx = self.tx_buf[:self.tx_len] self.tx_len = 0 if len(self.tx_buf) > PKTLEN: self.tx_buf = bytearray(PKTLEN) await pub(tx) #else: # await pub(b"Nothing...\n") # wait for event so we send more await self.ev.wait() self.ev.clear() except Exception: await asyncio.sleep(200)
def main(): # function keeps global namespace clean if not safemode and hasattr(board, "syspath"): sys.path[100:] = board.syspath # sys.path += board.syspath if hasattr(board, "modules") and board.modules: from mqtt import MQTT from uasyncio import sleep_ms, Loop as loop from esp32 import idf_heap_info, HEAP_DATA # global default asyncio exception handler def def_exception_handler(loop, context): log.error("Task exception: %s", context["message"]) log.exc( context["exception"], "coro: %s; future: %s", context["future"].coro.coro, context["future"], ) def lm(): log.info("MEM free=%d contig=%d", gc.mem_free(), gc.mem_maxfree()) log.info("IDF %s", [h[2] for h in idf_heap_info(HEAP_DATA) if h[2] > 0]) loop.set_exception_handler(def_exception_handler) lm() # the loader task iterates through the modules (typ from board_config) and starts each one async def loader(): for name in board.modules: try: log.info("Loading %s" % name) mod = __import__(name) # load the module by name await sleep_ms(0) fun = getattr(mod, "start", None) # check whether the module has a start() if fun: config = getattr(board, name, {}) # check whether we got a config for this log.info(" config: [%s]", ", ".join(iter(config))) lvl = config.pop("log", None) if lvl: logging.getLogger(name).setLevel(lvl) fun(MQTT, config) # call the module's start() function await sleep_ms(0) except ImportError as e: log.error(str(e)) except Exception as e: log.exc(e, "Cannot start %s: ", name) lm() loop.create_task(loader()) log.warning("Starting asyncio loop") loop.run_forever()
msg_box.set_pos(getrandbits(7), 50 + getrandbits(7)) # Countdown for i in range(10, 0, -1): msg_box.set_text(str(i)) await sleep(1) # Close the msg box msg_box.close_msg_box() ################################################################################################## # Create objects and screen ################################################################################################## scr = lv.scr_act() btn = lv.btn(scr) btn.align(lv.ALIGN.TOP_MID, 0, 10) btn.add_event_cb(lambda e: create_task(btn_event_task()), lv.EVENT.CLICKED, None) label = lv.label(btn) label.set_text('Click Me Again!') ################################################################################################## # Start event loop ################################################################################################## Loop.run_forever()
def _msg_cb(self, topic, msg, retained, qos, dup): topic = str(topic, "utf-8") # log.info("MQTT: %s", topic) lt = len(TOPIC) if topic.startswith(TOPIC) and topic[lt:lt + 4] == "cmd/" and len(msg) >= 2: if dup and not self._ndup: return # skip inital dup msgs else: self._ndup = True # expect topic: TOPIC/cmd/<cmd>/<id>[/<filename>] topic = topic[lt + 4:].split("/", 2) if len(topic) < 2: return cmd, ident, *name = topic # *name allows for it to be missing name = name[0] if len(name) else None rtopic = TOPIC + "reply/out/" + ident errtopic = TOPIC + "reply/err/" + ident # check cmd fn = "_do_" + cmd if not hasattr(self, fn): loop.create_task( self.mqclient.publish(errtopic, "Command '" + cmd + "' not supported", qos=1)) return # parse message header (first two bytes) seq = ((msg[0] & 0x7F) << 8) | msg[1] last = (msg[0] & 0x80) != 0 msg = memoryview(msg)[2:] # dispatch to command function # logging: if something is being streamed to us and we try to send a log message back # for each inbound message we end up loosing log messages because we can't get them out # as fast as new ones arrive. This always happens during OTA. Hence we stop logging # every message... if seq < 4 or last or seq & 0xF == 0: log.info( "Dispatch %s, msglen=%d seq=%d last=%s id=%s dup=%s", cmd, len(msg), seq, last, ident, dup, ) try: t0 = time.ticks_ms() resp = getattr(self, fn)(name, msg, seq, last) log.debug("took %dms", time.ticks_diff(time.ticks_ms(), t0)) # send response back, which may require reading a stream if resp is None: pass elif callable(getattr(resp, "read", None)): loop.create_task(self._send_stream(rtopic, resp)) else: log.debug("pub {} -> {}".format(len(resp), rtopic)) loop.create_task( self.mqclient.publish(rtopic, b"\xff\xff" + resp, qos=1)) except ValueError as e: buf = "MQRepl protocol error {}: {}".format(cmd, e.args[0]) loop.create_task(self.mqclient.publish(errtopic, buf, qos=1)) except Exception as e: log.warning("Exception in %s: %s", cmd, e) # sys.print_exception(e) # if this is a memory error just return, logging more runs out of memory again... if isinstance(e, MemoryError): return # lw = LogWriter(log.log, logging.WARNING) # sys.print_exception(e, lw) errbuf = io.BytesIO(PKTLEN) sys.print_exception(e, errbuf) errbuf = errbuf.getvalue() loop.create_task(self.mqclient.publish(errtopic, errbuf, qos=1))
if hr_meas: hrm_q = hr_meas.subscribe() print("Subscribed to HR measurements") else: print("HR sensor measurements unavailable") hr_sensor.terminate() await sleep_ms(5000) continue # try our luck yet again? while True: val = await hrm_q() print(val) if val[0] & 1: hr = struct.unpack("<H", val[1:3])[0] else: hr = struct.unpack("<B", val[1:2])[0] print("HR measurement: %dbpm (0x%02x)" % (hr, val[0])) except OSError as e: print("Sensor connection failed:", e, "- reconnecting...") hr_sensor.terminate() sleep_ms(500) # Dummy task needed to keep the asyncio loop going in v1.13!? async def ticker(): while True: await sleep_ms(100000) Loop.create_task(ticker()) Loop.run_until_complete(demo())
def _msg_handler(cls, topic, msg, retained, qos, dup): log.debug("RX %s (->%d): %s", topic, len(cls._msg_cb), msg) loop.create_task(cls._pulse_act()) for cb in cls._msg_cb: cb(topic, msg, retained, qos, dup)