Docker MQTT installation and use tutorial

Docker MQTT installation and use tutorial

Introduction to MQTT

MQTT (Message Queuing Telemetry Transport) is an instant messaging protocol developed by IBM that has the potential to become an important part of the Internet of Things. The protocol supports all platforms and can connect almost all connected objects to the outside world. It is used as a communication protocol for sensors and actuators (such as connecting houses to the Internet via Twitter).

Docker installs RabbitMQ and configures MQTT

Use RabbitMQ as the MQTT server and Eclipse Paho as the client. The host system is Ubuntu 16.04

Docker download image

docker pull daocloud.io/library/rabbitmq:3.7.4

Start RabbitMQ

docker run -d --hostname my-rabbit --name some-rabbit -p 15672:15672 -p 5672:5672 -p 1883:1883 -p 15675:15675 daocloud.io/library/rabbitmq:3.7.4

Note the mapping container port

  • 15672 is the default access port of the RabbitMQ management interface
  • 5672 is the default port for amqp
  • 1883 is the default port of MQTT TCP protocol
  • 15675 is the default port for web_mqtt websocket protocol

Enable plugin

After the default installation, we need to manually enable the rabbitmq_management plugin, rabbitmq_mqtt plugin and rabbitmq_web_mqtt plugin.

Execute the following three commands

docker exec <container ID> rabbitmq-plugins enable rabbitmq_management
docker exec <container ID> rabbitmq-plugins enable rabbitmq_mqtt
docker exec <container ID> rabbitmq-plugins enable rabbitmq_web_mqtt

Of course, you can also write a script start.sh and copy it to the container

/usr/sbin/rabbitmq-plugins enable rabbitmq_management
/usr/sbin/rabbitmq-plugins enable rabbitmq_mqtt
/usr/sbin/rabbitmq-plugins enable rabbitmq_web_mqtt

Enter the container and execute this script.

sh start.sh

Open host ports

firewall-cmd --zone=public --add-port=15672/tcp --permanent
firewall-cmd --zone=public --add-port=5672/tcp --permanent
firewall-cmd --zone=public --add-port=1883/tcp --permanent
firewall-cmd --zone=public --add-port=15675/tcp --permanent
firewall-cmd --reload

Python MQTT client implementation

Install Python Packages

pip install paho-mqtt

Send data demo (consumer)

# Before use, you need to start hbase and thrift server. # Start hbase in cd /usr/local/hbase bin/start-hbase.sh The default port is 60000
# Start the thrift server cd /usr/local/hbase/bin execute ./hbase-daemon.sh start thrift The default port is 9090
import sys
import os
dir_common = os.path.split(os.path.realpath(__file__))[0] + '/../'
sys.path.append(dir_common) # Add the root directory to the system directory to reference the common folder normally import argparse #
import logging
import time,datetime
from common.py_log import init_logger,init_console_logger
from common.config import *
from common.py_hbase import PyHbase
import time,json
from common.py_rabbit import Rabbit_Consumer
import paho.mqtt.client as mqtt
import time
HOST = "192.168.2.46"
PORT = 1883
def client_loop():
  client_id = time.strftime('%Y%m%d%H%M%S',time.localtime(time.time()))
  client = mqtt.Client(client_id) # ClientId cannot be repeated, so use the current time client.username_pw_set("guest", "guest") # Must be set, otherwise it will return "Connected with result code 4"
  client.on_connect = on_connect
  client.on_message = on_message
  client.connect(HOST, PORT, 60)
  client.loop_forever()
def on_connect(client, userdata, flags, rc):
  print("Connected with result code "+str(rc))
  client.subscribe("test")
def on_message(client, userdata, msg):
  print(msg.topic+" "+msg.payload.decode("utf-8"))
if __name__ == '__main__':
  client_loop()

Receiving data demo (producer)

import sys
import os
dir_common = os.path.split(os.path.realpath(__file__))[0] + '/../'
sys.path.append(dir_common) # Add the root directory to the system directory to reference the common folder normally import paho.mqtt.client as mqtt
import time
HOST = "192.168.2.46"
PORT = 1883
def client_loop():
  client_id = time.strftime('%Y%m%d%H%M%S',time.localtime(time.time()))
  client = mqtt.Client(client_id) # ClientId cannot be repeated, so use the current time client.username_pw_set("guest", "guest") # Must be set, otherwise it will return "Connected with result code 4"
  client.on_connect = on_connect
  client.on_message = on_message
  client.connect(HOST, PORT, 60)
  client.loop_forever()
def on_connect(client, userdata, flags, rc):
  print("Connected with result code "+str(rc))
  client.subscribe("test")
def on_message(client, userdata, msg):
  print(msg.topic+" "+msg.payload.decode("utf-8"))
if __name__ == '__main__':
  client_loop()

Producer demo

# import paho.mqtt.client as mqtt
import paho.mqtt.publish as publish
import time
HOST = "192.168.2.46"
PORT = 1883
def on_connect(client, userdata, flags, rc):
  print("Connected with result code "+str(rc))
  client.subscribe("test")
def on_message(client, userdata, msg):
  print(msg.topic+" "+msg.payload.decode("utf-8"))
if __name__ == '__main__':
  client_id = time.strftime('%Y%m%d%H%M%S',time.localtime(time.time()))
  # client = mqtt.Client(client_id) # ClientId cannot be repeated, so use the current time# client.username_pw_set("guest", "guest") # Must be set, otherwise it will return "Connected with result code 4"
  # client.on_connect = on_connect
  # client.on_message = on_message
  # client.connect(HOST, PORT, 60)
  # client.publish("test", "Hello MQTT", qos=0, retain=False) # Publish message publish.single("test", "Hello MQTT", qos = 1, hostname=HOST, port=PORT, client_id=client

Official documentation:
mqtt http://www.rabbitmq.com/mqtt.html

Summarize

The above is the full content of this article. I hope that the content of this article will have certain reference learning value for your study or work. Thank you for your support of 123WORDPRESS.COM. If you want to learn more about this, please check out the following links

You may also be interested in:
  • WeChat applet connects to the server to display MQTT data information
  • Detailed explanation of the process of building an MQTT server using Docker

<<:  Mysql GTID Mha configuration method

>>:  JavaScript to achieve a simple message board case

Recommend

IDEA uses the Docker plug-in (novice tutorial)

Table of contents illustrate 1. Enable Docker rem...

Advanced and summary of commonly used sql statements in MySQL database

This article uses examples to describe the common...

What command is better for fuzzy searching files in Linux?

1. Introduction This article mainly explains how ...

How to display web pages properly in various resolutions and browsers

The key codes are as follows: Copy code The code i...

Detailed explanation of the configuration method of Vue request interceptor

Follow the steps below 1. request.js content: htt...

A brief introduction to Linux environment variable files

In the Linux system, environment variables can be...

js tag syntax usage details

Table of contents 1. Introduction to label statem...

Installation and configuration method of vue-route routing management

introduce Vue Router is the official routing mana...

vue+rem custom carousel effect

The implementation of custom carousel chart using...

Detailed explanation of three solutions to the website footer sinking effect

Background Many website designs generally consist...

Summary of Linux ps and pstree command knowledge points

The ps command in Linux is the abbreviation of Pr...

Example of using UserMap in IMG

usemap is an attribute of the <img> tag, use...

How to capture exceptions gracefully in React

Table of contents Preface ErrorBoundary Beyond Er...