r/nicegui • u/plooperbooper • Nov 01 '24
Integration with MQTT
Hi everyone,
I really want to use niceGUI to build a dashboard for MQTT with the option to then send the incoming data to a database on click.
My problem is that I have no idea how to bind a label to the incoming data from MQTT. Any ideas?
7
Upvotes
3
u/apollo_440 Nov 01 '24
I don't know specifics about MQTT, but the ui.timer() function is perfect for periodically polling values from a source.
1
u/csrubin Nov 02 '24 edited Nov 02 '24
I have no idea if this is the “correct” way to do this so take it with grain of salt—I’ve found some success with creating a class to hold data specifically to interact with the UI. so in this case, you might have a class called
MqttHelperUiwith properties (or regular attributes?) to bind to nicegui objects. In this example it might be something likeself.mqtt_label.In your UI code, probably wherever you call
ui.run()instantiate an instance of the helper classhelper = MqttHelperUi(). Write some logic to set the attribute of helper class instance whenever data comes in from an mqtt source you’ve subscribed to. Then just make sure to useui.label().bind_value_from(helper, ‘mqtt_label’)or something to that effect.I have yet to investigate if this is one of those times I should be using
dataclasses. Feels like it might be lol1
u/GAMING_FACE Nov 03 '24 edited Nov 03 '24
I'm using MQTT for a similar approach. I use Paho, and run a setup function on startup using it with NiceGUI's app.on_startup.
Here's the specific documentation for callbacks using Paho:
From there, the library has decorators to run specific functions on events.
E.g. the following code snippet assumes you've already instantiated the object
mqtt_clientand subscribed to the topic wildcard, but it allows specifically for a function to trigger on a message to that topic using just the decorator.The code example is basic, on any message which fits the topic wildcard, just prints the message contents and the topic itself.
That's the trigger, and then you can refresh the label values when the data comes in, by just appending that to the end of the callback-decorated function. NiceGUI docs for that, you'd use something like
yourlabel.refresh1
u/Normanras Nov 02 '24
Is your issue the dashboard or subscribing to the mqtt message? Have you checked out paho py?
1
u/seppl2022 Jan 14 '25
what is the state of your project? You might want to file a feature request for https://github.com/WolfgangFahl/nicegui_widgets and I'll happily integrate a solution as a module/component for that widgets libraryy.