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.