peterhinch / micropython-mqtt

A 'resilient' asynchronous MQTT driver. Recovers from WiFi and broker outages.
MIT License
549 stars 116 forks source link

Question : Callback to function outside of own class #55

Closed kloknibor closed 3 years ago

kloknibor commented 3 years ago

I'm not sure if this question should be asked here but I have the following situation.

I have 2 async tasks running from the main loop :

these are both living in their own file. So the main loop looks like this:

from .UartHelper import UartConnection
from .MqttComp import MqttClass, config
import uasyncio as asyncio

class Main():
    def __init__(self):
        self.uart_interface = UartConnection()
        self.mqtt = MqttClass()

    async def loop(self):
        await self.mqtt.start_connection()
        # get UART data
        while True:
            uart_connection_task = asyncio.create_task(self.uart_interface.check_uart())
            current_uart_state = await uart_connection_task
            asyncio.create_task(self.mqtt.publish_states(states=current_uart_state))

            await asyncio.sleep(1)

i am able to use self.config['subs_cb'] in self.mqtt for setting a callback function but this function seems to only work if it is inside the MqttClass. What I basically want is the following :

Mqtt launches the callback function -> MqttClass asks main class to run function from UartConnection class (Send Uart command)

how would I achieve this? Since I also want to add a web page control for this I prefer to not use the MQTT class as main class.

peterhinch commented 3 years ago

i am able to use self.config['subs_cb'] in self.mqtt for setting a callback function but this function seems to only work if it is inside the MqttClass.

I am unclear what you mean by this. If you mean that the function must be a class member then I'm baffled: take a look at the demo scripts (e.g. range.py) for callbacks that are simple functions. It should be possible to use any Python callable (e.g. a function, a method of a subclass, or method of another class) as a callback.