Tutorial: Using MQTT with the WeatherRack2

Tutorial: Using MQTT with the WeatherRack2MQTT

Editors Note:   Thank you Guest Blogger Jason Chalmers!  This is a great tutorial on how to connect up MQTT to the WeatherRack2.

Introduction

The KickStarter kit for the WeatherRack2 couldn’t get to me fast enough! While waiting for my kit to arrive, I had identified how and where I would mount the rack, tested the installation of the software-defined radio, and reviewed the SwitchDoc Labs Github repository that contains the Python code that reads the rack. The Python script for reading the rack is simple which makes it a greenfield for however you want to process the data from the WeatherRack2. As a huge fan of MQTT, I knew exactly how I was going to process the readings from the WeatherRack2.

MQTT – Message Queuing Telemetry Transport

MQTT

You’ve likely used MQTT before, however, you may not have realized you were doing so. A lot of the smart devices that have become so prevalent in our life, and our homes, rely upon MQTT to communicate. The big words the acronym represents makes MQTT sound fancier than it really is. In a nutshell, MQTT is a publish/subscribe(pub/sub) model that allows publishers to publish messages to a topic and allows subscribers to subscribe to those topics to receive messages. The messages, topics, and subscriptions are managed in a tool called a broker. The broker sits between publishers and subscribers and allows for the flow of messages between the two.

SwitchDoc has also published another article about getting MQTT to work with the Raspberry Pi for further edification.

Eclipse Mosquitto

A very popular open source MQTT broker that is available for the Raspberry Pi is Eclipse Mosquitto. The broker is very lightweight and runs really well on a Raspberry Pi. If you feel intimidated by the idea of becoming a server administrator, please know that the administration of any broker is as simple or as complicated as you make it. If you want to run a broker on the same Raspberry Pi that you run the software-defined radio that reads your WeatherRack2, and you have no intention of exposing the Raspberry Pi to the Internet, administration is very simple. All that is needed is to install the broker using the default settings provided with the installer package, enable the Linux service, and you are done. The installation and enabling of the Linux service can be accomplished on a Raspberry Pi terminal window using the following two commands:

sudo apt install mosquitto mosquitto-clients -y

sudo systemctl enable mosquitto

Python and MQTT

Because MQTT is a protocol, most, if not all, modern programming languages have supporting libraries that will enable MQTT communications. In the case of Python, the Eclipse Paho MQTT library is a great option because it has the added benefit of being maintained by the Eclipse Foundation which just so happens to also maintain the Eclipse Mosquitto broker. Installation of the library on a Raspberry Pi can be accomplished using the following command:

sudo pip3 install paho.mqtt

WeatherRack2

In order to read data from the rack, it is necessary to install the software-defined radio (SDR) provided by SwitchDoc Labs. The following link will take you to instructions on how to accomplish installing the SDR and testing the installation:

https://github.com/switchdoclabs/rtl_433

With the SDR setup, the Github repository for the WeatherRack2 can be cloned to your Raspberry Pi in a terminal window using the following command:

git clone https://github.com/switchdoclabs/SDL_Pi_WeatherRack2

There is only one script in the repository: readWeatherSensors.py. The script is responsible for starting the software-defined radio and listening to the radio in order to receive telemetry data from the WeatherRack2. A definite greenfield!

Enabling MQTT

As with any Python module, it is necessary to import the MQTT module. In this case, I’m only going to use the publish class provided in the module:

from paho.mqtt import publish

The publish class includes the function single. The function handles connecting to the broker, publishing a single message to a single topic, and disconnecting from the broker. The following function definition was added to readWeatherSensors.py:

 

def mqtt_publish_single(message):

	topic = '{0}{1}'.format(config['station']['name'], config['mqtt']['topic_suffix'])

	try:
		publish.single(
			topic=topic,
			payload=message,
			hostname=config['mqtt']['host'],
			port=config['mqtt']['port'],
			qos=config['mqtt']['qos']
		)
	except ConnectionError as ce:
		print('Mosquitto not available')



 

The wrapper function, mqtt_publish_single, relies upon a Python dictionary named config. You can easily replace references to config with hard-coded values. The suggested replacements that follow assume you are running the broker on the same machine as the software-defined radio.

  • topic – topic name of your choice to which you would like to publish sensor data
  • hostname – ‘localhost’
  • port – 1883
  • qos – 0

The resulting wrapper function should look as follows:

 

def mqtt_publish_single(message):

	topic = 'YOUR-TOPIC-NAME'

	try:
		publish.single(
			topic=topic,
			payload=message,
			hostname= ‘localhost',
			port=1883,
			qos=0
		)
	except ConnectionError as ce:
		print('Mosquitto not available')

Should you choose to keep the config Python dictionary, you’ll need an additional import:

import json

You will also need to add a file named config.json to the same folder in which readWeatherSensors.py is stored with the following contents:

{	
	"station": {
		"name": "YOUR-STATION-NAME"
	},
	"mqtt": {
		"host": "localhost",
		"port": 1883,
		"topic_suffix": "YOUR-TOPIC-SUFFIX",
		"qos": 0
	}
}


 

Finally, locate the following snippet in the main processing loop:

if (( sLine.find('F007TH') != -1) or ( sLine.find('F016TH') != -1)):
            sys.stdout.write('WeatherSense Indoor T/H F016TH Found' + '\n')
            sys.stdout.write('This is the raw data: ' + sLine + '\n')
        if (( sLine.find('FT0300') != -1) or ( sLine.find('FT020T') != -1)):
            sys.stdout.write('WeatherSense WeatherRack2 FT020T found' + '\n')
            sys.stdout.write('This is the raw data: ' + sLine + '\n')
<\pre>
 

Add calls to the function mqtt_publish_single so that the above snippet is as follows:
if (( sLine.find('F007TH') != -1) or ( sLine.find('F016TH') != -1)):
            sys.stdout.write('WeatherSense Indoor T/H F016TH Found' + '\n')
            sys.stdout.write('This is the raw data: ' + sLine + '\n')
            mqtt_publish_single(sLine)
        if (( sLine.find('FT0300') != -1) or ( sLine.find('FT020T') != -1)):
            sys.stdout.write('WeatherSense WeatherRack2 FT020T found' + '\n')
            sys.stdout.write('This is the raw data: ' + sLine + '\n')
            mqtt_publish_single(sLine)

<\pre>

Conclusion

With the changes in place, run readWeatherSensors.py in a terminal window on your Raspberry Pi using the following command:

sudo python3 readWeatherSensors.py

Open a second terminal window on your Raspberry Pi and run the following command:

mosquitto_sub -t YOUR-TOPIC-NAME

Placing the two terminals windows side-by-side, you should see values being read from the weather rack and the readings being read from the MQTT broker.
MQTT and JSON
With the telemetry data available through MQTT, it is now possible to manage processing of the sensor data any way you choose.

 

1 Comment

  1. I bit of code is missing if you want to use config.json. Within the readWeatherSensors.py script, add the following snippet:

    with open(‘config.json’, ‘r’) as config_file:
    config = json.load(config_file)

Comments are closed.