MQTT sample code

I was looking for a way to have the UI update based on events on the server or uplink code. Although Anvil uses websockets, they can be not be used for server to client communication unfortunately.
In my application I want to quickly update the UI, so polling (with a Timer) is not very convenient. With very frequent checks it would hammer the server.

So that’s why I checked the possibilities of integrating MQTT. The idea would be to have have the UI subscribe to changes published by the server or uplink code. Only then would the UI query the server for the changes. Or the changes could be published directly.

In the sample code I have implemented an MQTT listener on the Anvil UI by integrating the Paho Mqtt javascript library. Quite easy with the nice Anvil JS support.
Publishing is done with the python Paho MQTT library. In the sample code there is some sample code. Since the Anvil server code does not stay running, the code is not very suited as Anvil server code. You can use the publishing part of the code, or you could just copy it as uplink code (or as a separate process).

The sample code can run as is because it uses a public MQTT Broker.

Anyway HTH somebody.

https://anvil.works/build#clone:GPVVZ7JC5ZJD5AQA=J4YBXOIITHPLY6QR4SCKUPNI

Caveat on MQTT brokers

The eagle eyed will have noticed that the JS and the python code uses different ports. Usually different ports are used for no TLS or TLS and for MQTT transport and MQTT over WebSockets transport.

The javascript library needs to have the broker have websockets transport enabled, otherwise you’ll get a weird error (Failed to connect: AMQJS0007E Socket error:undefined with Mosquitto Broker).
See: Failed to connect: AMQJS0007E Socket error:undefined with Mosquitto Broker · Issue #99 · eclipse/paho.mqtt.javascript · GitHub and:
Using MQTT Over WebSockets with Mosquitto
The python library can use either transport.

The public HiveMQ broker does not have websockets enabled. The free broker at Free Public MQTT 5 Broker Server | EMQ works nicely and clearly documents its port use.

9 Likes

Hi @mjmare I would like to thank you for sharing this brilliant solution with the community.

Finally I was able to build a web app with anvil without the need for pooling the data from server side using the timer.

Client is just subscribed to the MQTT broker and is listening on one topic.
Based on the value read from the subscription I can trigger UI update.

1 Like

Glad it was helpful!

1 Like