1, first of all we need to first install the client mosquitto in the Raspberry Pi
mosquitto introduced:
a message push to achieve the agreement MQTT v3.1 open source message broker software, provide lightweight, supports publish / subscribe message may push mode, the device for short message communications between devices becomes simple, such as the now widely used low-power sensors, mobile phones, embedded computers, micro-controllers and other mobile devices. A typical application case is Andy Stanford-ClarkMosquitto (one of the founders MQTT protocol) remote monitoring and home automation to achieve. And on the lecture OggCamp of MQTT protocol in detail.
Open a terminal raspberry pie, enter
sudo apt-get install mosquitto mosquitto-clients
Press Y to confirm
Use two terminals respectively using the following code to check whether the installation was successful mosquitto
mosquitto_sub -t m -d
mosquitto_pub -t m -m "This is a message from pi."
Subscribe to the terminal will be the words "This is my first message from pi" of
Details regarding the use of mosquitto: https://blog.csdn.net/xyblog/article/details/50113883
2, the installation paho.mqtt library
If raspberries come in multiple versions of python when you need to specify the type of installation:
python3
sudo python3 -m pip install paho-mqtt
python2
sudo python2 -m pip install paho-mqtt
2.1 Introduction to use the library on paho.mqtt
Jane thought finishing in the book, the author: EMQ Details Come: https://www.jianshu.com/p/b76dbc675141
-
Connection Broker to use connect () / connect_async ()
call loop () remains connected to the Broker network
using loop_start () call to a loop () process
using loop_forever () keeping loop () calls
using the subscribe () subscribe to a topic and receive messages
using the publish ( ) announced
using disconnect () disconnect from Broker -
on_connect (client, userdata, flags, rc)
when Broker in response we call request, "flags" is a comprising Broker in response dictionary parameters: flags [ 'session present'] - This flag only for a clean session is set to 0, if provided session = 0, for a client to reconnect to the Broker before the session before the information is still saved, if set 1, there has been a session. "Rc" value used to determine whether the connection is successful -
on_disconnect (client, userdata, rc)
Called when the client is disconnected Broker -
on_message (client, userdata, message)
is called when a message is received on the client subscribed threads, "message" variable is a MQTT message describing the features of all messages -
on_publish (client, userdata, mid)
when using publish () message is sent to the transfer agent has completed call. For QoS level messages 1 and 2, which means that the proper handshake has been completed. For QoS 0, it just means the message has left the client. "Mid" variable is () call returns publish from the corresponding intermediate variable. This callback is very important, because even publish () call returns successfully, it does not always mean the message has been sent -
on_subscribe (client, userdata, mid, granted_qos)
when Broker in response to a subscription request to call, "mid" variable is () call returns from the respective subscribe intermediate variable, "granted_qos" variable is the list each time a subscription request to send different Qos level -
on_unsubscribe (client, userdata, mid)
when Broker in response to an unsubscribe request call, "mid" variable is invoked with unsubscribe from the corresponding () Returns the intermediate variables -
on_log (client, userdata, level, buf)
when the client has to call log information, definitions allow debugging, "level" variable is the message level contain MQTT_LOG_INFO, MQTT_LOG_NOTICE, MQTT_LOG_WARNING, MQTT_LOG_ERR, MQTT_LOG_DEBUG, the message itself is buf.
Application Example 1 (message):
PUB:
import paho.mqtt.client as mqtt
def on_connect(client, userdata, flags, rc):
print("Connected with result code "+str(rc))
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("127.0.0.1", 1883, 600)
client.publish('emqtt',payload='Hello,EMQ!',qos=0)
client.loop_start()
SUB:
import paho.mqtt.client as mqtt
def on_connect(client, userdata, flags, rc):
print("Connected with result code "+str(rc))
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("127.0.0.1", 1883, 600)
client.subscribe('emqtt',qos=0)
client.loop_start()
Use Example 2 (using the remote control MQTT GPIO):
Raspberry Pi idea of finishing in the laboratory Details Come: http://shumeipai.nxez.com/2018/09/16/install-mosquitto-on-the-raspberry-pi-to-implement-mqtt.html
Content of the message as JSON packet, the packet format is { "index": 17, "value": 0}, index representative of Raspberry Pi GPIO number, value on behalf of open or closed state.
# -*- coding: utf-8 -*-
import paho.mqtt.client as mqtt
import RPi.GPIO as GPIO
import json
# BCM GPIO编号
pins = [17,18,27,22,23,24,25,4]
def gpio_setup():
# 采用BCM编号
GPIO.setmode(GPIO.BCM)
# 设置所有GPIO为输出状态,且输出低电平
for pin in pins:
GPIO.setup(pin, GPIO.OUT)
GPIO.output(pin, GPIO.LOW)
def gpio_destroy():
for pin in pins:
GPIO.output(pin, GPIO.LOW)
GPIO.setup(pin, GPIO.IN)
# 连接成功回调函数
def on_connect(client, userdata, flags, rc):
print("Connected with result code " + str(rc))
# 连接完成之后订阅xxxx主题
client.subscribe("xxxx")
# 消息推送回调函数
def on_message(client, userdata, msg):
print(msg.topic+" "+str(msg.payload))
# 获得负载中的pin 和 value
gpio = json.loads(str(msg.payload))
if gpio['pin'] in pins:
if gpio['value'] == 0:
GPIO.output(gpio['pin'], GPIO.LOW)
else:
GPIO.output(gpio['pin'], GPIO.HIGH)
if __name__ == '__main__':
client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
gpio_setup()
try:
# 请根据实际情况改变MQTT代理服务器的IP地址
client.connect("xxxxxxxx", 1883, 60) #此处的xxxxxx为ip地址
client.loop_forever()
except KeyboardInterrupt:
client.disconnect()
gpio_destroy()
3, the code programming raspberry pie even things work on Baidu sky
Code and ideas here finishing in CSDN author: Luo Xiaolong Details Come: https://blog.csdn.net/Tavox/article/details/74996150
import paho.mqtt.client as mqtt
import sys
import uuid
#import Collect
import time
broker = change0' #百度云天工物联网平台的域名地址
port = 1883
username = 'change1'# 实例用户名
password = 'change2'# 密钥
clientid = 'xxxx' + str(uuid.uuid4()) #为随机生成的id
topic = 'xxxx' #xxxx为树莓派发布的主题名字
def on_connect(client, userdata, rc):
print('Connected. Client id is: ' + clientid)
def on_message(client, userdata, msg):
msg = str(msg.payload, 'utf-8')
print('MQTT message received: ' + msg)
if msg == 'exit':
sys.exit()
client = mqtt.Client(clientid)
# client.will_set('temperature', 'last will', 0, False)
client.on_connect = on_connect
client.on_message = on_message
client.username_pw_set(username, password)
print('Connecting to broker: ' + broker)
client.connect(broker, port)
client.loop_start()
time.sleep(3)
# client.loop_forever()
client.publish(topic,payload=xxxx,qos=0) #xxxx为你想发布的数据
#while True: #没搞懂Collect是啥操作,具体看作者博客
# rTHdata = test1.Collect.collect()
# client.publish(topic, "temperture :" + str(rTHdata[0]) + " *C " + "humidity :" + str(rTHdata[1]) + " %")
# 设置发布间隔时间
# time.sleep(3)
4, using the results of experimental code window side
If there are not Raspberry Pi test, you can use the server to test mosquitto window installation
method to install and test from CSDN author: PotoYoung
https://blog.csdn.net/qq_21842575/article/details/82760335
Test verification:
procedures substantially as described above, the addition of a cycle, every transmission 3s "hello_world a" sky Baidu to work things server MQTT
Results:
receiving hello_world 0
received hello_world 1
received hello_world 2
At this point it's done, the same operation Raspberry Pi can connect Baidu sky work things server
Past articles:
Use Raspberry Pi build a smart home of their own (a) use -DHT11 temperature and humidity sensors: https://blog.csdn.net/qq_41744697/article/details/103907582
Raspberry Pi build -MQTT using a protocol of their own smart home (b) the use of
https://blog.csdn.net/qq_41744697/article/details/103908028