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):
        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):
        asyncio.create_task(self.loopTask('hello world'))

    async def loopTask(self, s):
        while True:
            print(s)
            await asyncio.sleep(10)

The __init__() creates an async task: loopTask() which never exits. It prints ‘hellow world’ every 10s (simulated a ‘slow task’).

The loopTask() yields from the asyncio.sleep(), 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://docs.micropython.org/en/latest/library/uasyncio.html