Http to mqtt bridge

I am working on a home automation project that will control various aspects of my house from heating and lighting to music playing and security. The backend of this consists of a server running on a Raspberry Pi. It is my intention for this server to be a hub to broker messages between the various different methods of communication and the protcols that sit on top of them. For example, I may wish to turn my heating up from an app on my mobile phone. This is a breakdown of the steps required to make that happen

  1. The mobile phone app sends an http request to the server
  2. The server receives the http request and translates it into an mqtt message on the request temperature change channel
  3. A programme concerned with heating control is subscribed to the request temperature change channel and receives the message.
  4. The heating control programme is also subscribed to the current temperature channel which is being pushed out by sensors in each room.
  5. A calculation is made by the programme and a message sent out on the set temperature channel.
  6. A programme to translate mqtt messages into a protocol suitable for rf communication intercepts the message and sends it out over a 433mhz network.
  7. The radiator thermostat receives the rf communication and sets the temperature accordingly.

It is the third step that I will describe in this post. Very simply this is a small Python programme using the Flask library that sits in its own process listening for particular http requests. When it gets one it strips out the relevent information and publishes it over an MQTT channel using the paho. A more detailed description can be found under the code below.

We first import the required libraries for Flask and mqtt. Then define the ip address and port for the mqtt server. In this case it is just running on the localhost. We then start the Flask app and define a route which will call the function get_id when we visit the web address at /mqtt. We pull out the topic and message from the http request, set up an mqtt client and then publish the message.

We can test it all works using the mosquitto broker and its command line tools

First install it by following these instructions

Now start the mosquitto mqtt server


Subscribe to a the channel 'test'

mosquitto_sub -h localhost -t mqtt_test

Send an http request by typing this into a web browser

The message 'hello_world' should appear in the terminal