MojoScale Forum
Login Sign up

How can different parts of my ESP32 app communicate without calling each other directly?

Asked 3 weeks, 6 days ago in Firmware by Mojo Scale
Ask Question
1 Answers
34 Views
0 Comments

I have different parts of my program handling sensors, MQTT, and device state. I don't want everything tightly coupled together with direct function calls.

Is there a way to fire an event like "temperature_high" and have another part of the program respond to it?

Answered updated 3 weeks, 6 days ago
Log in to comment.
1 Answer
OK Accepted

Yes. You can use system.subscribe() and system.emit() to create simple events inside your application.

For example:

import system

def temperature_warning(temp):
    print("Temperature is too high:", temp)

system.subscribe("temperature_high", temperature_warning)

Now anywhere else in your program you can emit that event:

temp = 92

if temp > 90:
    system.emit("temperature_high", temp)

When the event is emitted, the subscribed callback receives the values you passed with it. In this case, that effectively results in:

temperature_warning(92)

This becomes useful once your application starts doing several things at once. Your sensor code doesn't need to know what should happen when the temperature gets too high — it just reports the event:

system.emit("temperature_high", temp)

Another part of the application decides how to react:

def handle_warning(temp):
    print("WARNING:", temp)

system.subscribe("temperature_high", handle_warning)

You can also pass multiple values:

def device_alarm(sensor, value, limit):
    print(sensor, value, limit)

system.subscribe("alarm", device_alarm)

system.emit("alarm", "temperature", 92, 90)

which passes those values to the subscriber as:

device_alarm("temperature", 92, 90)

This is particularly handy for keeping larger applications separated into pieces — sensor code can emit events while MQTT, logging, displays, or other application logic can respond to them.

So instead of building everything as:

read_sensor()
send_mqtt()
update_display()
handle_alarm()

you can have the sensor side simply announce what happened and let the appropriate part of the application respond.

answered by Mojo Scale 3 weeks, 6 days ago edited 3 weeks, 6 days ago
Your Answer
Log in to answer this question.