Dash and MQTT

This entry is part 3 of 3 in the series dash
Hey. This page is more than 3 years old! The content here is probably outdated, so bear that in mind. If this post is part of a series, there may be a more recent post that supersedes this one. Dash is an opensource Python framework for building web-apps. Pretty good. Check it out.

One gotcha to the way Dash is structured is that it is event-driven. This means out-of-the-box your web-app only reacts to requests browser. So something needs to ‘happen’ in the browser to trigger a server-side response, and this something is typically a user event. This presents an issue when you want your app to respond to a realtime data feed…such as sensor data published to an MQTT broker-server from an ESP8266 IOT device.

dash_mqtt (source code on GitHub) is my fledgeling answer to this quandary (🎆Queue fireworks 🎆). I bit the bullet and wrote it afresh, since prior I had been trying to make a flaky hack of Flask-SocketIO, Flask-MQTT and Dash play nicely. It involved ‘clicking’ hidden buttons client-side with javascript to trigger Dash callbacks. Very messy and unreliable.

Dash MQTT shipping on PyPi now:

pip install dash_mqtt

Some instructions on the pypi project page and in github readme.

MQTT over Websockets required

Use of the component (currently) is not all plain sailing. The component essentially wraps around MQTT.js running the MQTT Client in the browser (in React component form as per typical Dash components). Subsequently (precising from here):

  1. There is no way for JavaScript running in browsers to open TCP sockets so “normal” MQTT is impossible in browser apps.
  2. To get around this limitation, MQTT.js uses MQTT over WebSockets instead when it detects it’s running in a browser.

This means that you need to set the component’s broker_port  up to point at the MQTT-over-WebSockets port of the MQTT broker you are using (not the plain MQTT one), or if you are setting up your own broker server, turn on MQTT-over-WebSockets and expose a port for it.

Series navigation

<< Why I like open-source