Using MQTT on Raspberry Pi

Environment

  • Raspberry Pi 3B+
  • Raspbian GNU/Linux 9.4
  • Python 3
  • mosquitto 1.4.10
  • paho.mqtt 1.3.1

Setup

$ sudo apt install mosquitto mosquitto-clients
$ pip install paho-mqtt

Code

Pi Publisher.

#!/usr/bin/env python

import time
import paho.mqtt.client as mqtt
import FaBo9Axis_MPU9250

host = 'x.x.x.x'
port = x
keepalive = 60
topic = 'mqtt/sensor'

client = mqtt.Client()
client.connect(host, port, keepalive)

mpu9250 = FaBo9Axis_MPU9250.MPU9250()

while True:
    temp = mpu9250.readTemperature()
    accel = mpu9250.readAccel()
    gyro = mpu9250.readGyro()
    mag = mpu9250.readMagnet()

    client.publish(topic, 'temp:' + str(temp) + ',' + 
                          'accel:' + str(accel['x']) + ',' + str(accel['y']) + ',' + str(accel['z']) + ',' + 
                          'gyro:' + str(gyro['x']) + ',' + str(gyro['y']) + ',' + str(gyro['z']) + ',' +
                          'mag:' + str(mag['x']) + ',' + str(mag['y']) + ',' + str(mag['z']))
    time.sleep(1)

client.disconnect()

Host Subscriber.

#!/usr/bin/env python

import paho.mqtt.client as mqtt

host = 'x.x.x.x'
port = x
keepalive = 60
topic = 'mqtt/sensor'

def on_connect(client, userdata, flags, rc):
    print('Connected with result code ' + str(rc))
    client.subscribe(topic)

def on_message(client, userdata, msg):
    print(msg.topic + ' ' + str(msg.payload))

client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message

client.connect(host, port, keepalive)

client.loop_forever()

Result

Reference