Hub Plug-in Structure

Introduction

The customized Hub Plug-in is a class called ‘App’. The Hub’s ‘Core Manager’ code will create an object of App at the end of the boot procedure, provided that the ‘Developer Mode’ or ‘User Plug-in’ enabled.

The block __init__() will run first.

Here is the minimum code of Hub Plug-in:

class App:
    def __init__(self, mgr, loop, pan):
        print('Hello world')

This python module must be named as __init__.py and put it in the /app folder.

This “hello-world” Plug-in only prints a line on the console. You can observe this over the WebRepl.

  • mgr: ‘Core Manager’ object

  • loop: the asyncio loop object

  • pan: local mesh network (Personal Area Network, PAN) object

Now you may wonder, can I write a blocking code inside __init__()? The answer is No. You should complete the preparing job here as fast as possible. If you need to do a recurring task, use co-routine, please. Here is an example:

import uasyncio as asyncio

class App:
    def __init__(self, mgr, loop, pan):
        self._loop = loop
        self._loop.create_task(self.myLoop('hello world'))

    async def myLoop(self, s):
        while True:
            print('myLoop')
            await self.myPrint(s)
            await asyncio.sleep(5)

    async def myPrint(self, s):
        await asyncio.sleep(1)
        print(s)

The __init__() create an async task: myLoop() which never exits. Here, the myPrint() simulated a ‘slow task’ which may take one second of processing time.

The myLoop() yields from the myPrint() and asyncio.sleep(5), letting some other co-routine tasks running first. There are many co-routine tasks in system / SDK codes. So it’s very important to yield, not block it.

Please learn the asyncio here: https://github.com/peterhinch/micropython-async/blob/master/TUTORIAL.md