The Internet of things with RabbitMQ, Python, MQTT and AMQP

The Internet of things with RabbitMQ, Python, MQTT and AMQP @ www.Vasilev.link DevOps consultant
Jun 13, 2016

Hello,
In nowadays we are speaking more and more about communication between `Things` over the internet. Еlectrical appliances, computers, sensors. We can make different type of communications between them.
Here I will write down a way to exchange messages between few computers.
I have been working with IBM Websphere products, but because for sensors and small computers, we need something lightweight, we can use RabbitMQ and some script - for example Python.

Lets start with installing and configuring the MQ server/Broker part.

RabbitMQ installation and configuration:

  • create the Qmanager
rabbitmqctl add_vhost demoqm

rabbitmqctl set_cluster_name democluster


  • create the user
rabbitmqctl delete_user guest
rabbitmqctl add_user demouser demopass
rabbitmqctl set_user_tags demouser administrator
rabbitmqctl set_permissions -p demoqm demouser ".*" ".*" ".*"


rabbitmqctl set_policy DLX ".*" `{"dead-letter-exchange":"DLQ"}` --apply-to queues


  • create the queue and topic key, in which you will publish


internet of things with rabbitmq, mqtt, amqp

As you can see, we have a single queue demo.queue.local, if you click on this queue, you can see the details for queue. Under details you can see its a durable queue, and under bindings you can see its bound to the default amq.topic exchange, with a routing key demo.key.


internet of things with Rabbitmq, mqq, amqp


In this example, I am using Python MQTT libraries - Paho: Paho MQTT

Python script for publishing the message:

import paho.mqtt.client as paho
import time
 
mqtthost = "host of RabbitMQ server"  
mqttuser = "demouser"  
mqttpass = "demopass"  
mqtttopic = "demo.key"  

def on_connect(client, userdata, flags, rc):
    print("CONNACK received with code %d." % (rc))
def on_publish(client, userdata, mid):
    print("mid: "+str(mid))
 
client = paho.Client()
client.on_connect = on_connect
client.on_publish = on_publish
client.username_pw_set(mqttuser,mqttpass)
client.connect(mqtthost, 1883,60)


client.loop_start()

while True:
    message = "test data"
    (rc, mid) = client.publish(mqtttopic, str(message), qos=1)
    time.sleep(10)


Now we are ready with the script for publishing data, we have to add some more functions in it, so we can read info about disc space, temperature, CPU, MEM and whatever we want.