MQTT Client Python Example

Source: Internet
Author: User
Tags mqtt broker

This was a simple example showing how to use the [Paho MQTT Python Client] (https://eclipse.org/paho/clients/python/) to Sen D data to Azure IoT hub. You need to assemble the rights credentials and configure TLS and the MQTT protocol version appropriately.

send_iot-hub_paho_mqtt.py

#!/usr/bin/pythonimport Paho.mqtt.publish as Publishimport paho.mqtt.client as Mqttimport Sslauth = {  ' username ': " Ciscohackhub.azure-devices.net/lora1 ",  ' password ':" Sharedaccesssignature sr=ciscohackhub.azure-devices.net% 2fdevices%2flora1&sig=xxxx&se=1463048772 "}tls = {  ' ca_certs ':"/etc/ssl/certs/ca-certificates.crt ",  ' tls_version ': SSL. Protocol_tlsv1}publish.single ("devices/lora1/messages/events/",  payload= "Hello World",  hostname= " Ciscohackhub.azure-devices.net ",  client_id=" Lora1 ",  Auth=auth,  tls=tls,  port=8883,  Protocol=mqtt. MQTTv311)

 

The following code would subscribe on topic F and republish on topic F2

import paho.mqtt.client as Mqttmessage = ' on ' def on_connect (mosq, obj, RC): MQTT  C.subscribe ("F", 0) print ("RC:" + str (RC)) def on_message (mosq, obj, msg): Global message print (Msg.topic + "" + STR (MSG.QOS) + "" + str (msg.payload)) message = Msg.payload mqttc.publish ("F2", msg.payload);d EF on_publish (MOSQ, O BJ, Mid): Print ("Mid:" + str (mid)) def on_subscribe (Mosq, obj, Mid, Granted_qos): Print ("subscribed:" + str (MID) + "+ str (granted_qos)) def on_log (mosq, obj, Level, string): Print (string) MQTTC = Mqtt. Client () # Assign Event Callbacksmqttc.on_message = On_messagemqttc.on_connect = On_connectmqttc.on_publish = On_ Publishmqttc.on_subscribe = on_subscribe# connectmqttc.connect ("localhost", 1883,60) # Continue the network Loopmqttc.loop_forever () 

The user program is required to send messages, not to maintain a connection with the MQTT broker, available single() or multiple() method. This is a better way to save electricity.

Import Paho.mqtt.publish as publish# publish a message then Disconnect.host = "localhost" topic = "tw/rocksaying" payload = "Hello Mqtt" # If broker asks User/password.auth = {' username ': "", ' Password ': ""}# If broker asks client id.client_id = " "Publish.single (topic, Payload, Qos=1, Hostname=host) #publish. Single (topic, payload, Qos=1, host=host,#    auth= Auth, client_id=client_id)

When you use a user program, such as a sensor service, you should use a connector design for regular or short-term continuous messaging.

# coding:utf-8import sys, OS, timereload (SYS) sys.setdefaultencoding (' utf-8 ') import paho.mqtt.client as mqtt# If broker A SKS Client id.client_id = "" Client = Mqtt. Client (client_id=client_id) # If broker asks user/password.user = "" Password = "" Client.username_pw_set (user, password) Client.connect ("localhost") topic = "tw/rocksaying" payload = "Hello Mqtt" for i in Xrange:    client.publish (topic, "%s" -%d "% (payload, i))    time.sleep (0.01)    # When QoS = 0, if the message is too short, messages may be missed. This is a normal phenomenon.

In real time, you can use Mosquitto_sub to subscribe to the topic, to see if the message is sent.

Subscribe to the main topic

This is actually a mosquitto_sub-like program to subscribe to the topic "tw/rocksaying/#". It is also a basic skeleton of a service program.

# coding:utf-8import sys, OS, time, Signalreload (SYS) sys.setdefaultencoding (' utf-8 ') import paho.mqtt.client as Mqttclient = nonemqtt_looping = Falsetopic_root = "Tw/rocksaying" def on_connect (MQ, UserData, RC, _): # Subscribe when    Connected. Mq.subscribe (topic_root + '/# ') def on_message (MQ, UserData, msg): Print "TOPIC:%s"% msg.topic print "payload:%s" % msg.payload print "QoS:%d"% msg.qosdef mqtt_client_thread (): Global client, mqtt_looping client_id = "" # If    Broker asks client ID. Client = Mqtt.    Client (client_id=client_id) # If broker asks User/password. user = "" Password = "" Client.username_pw_set (user, password) client.on_connect = On_connect Client.on_messag E = on_message try:client.connect ("localhost") except:print "MQTT Broker is not online.    Connect later. " mqtt_looping = True print "Looping ..." #mqtt_loop. Loop_forever () cnt = 0 while Mqtt_looping:client.loo P () cnt + = 1 if CNT > 20:try:client.reconnect () # to avoid ' broken pipe ' error. Except:time.sleep (1) CNT = 0 print "Quit Mqtt thread" Client.disconnect () def stop_all (*ar GS): Global mqtt_looping mqtt_looping = falseif __name__ = = ' __main__ ': signal.signal (signal. SIGTERM, Stop_all) signal.signal (signal. Sigquit, Stop_all) signal.signal (signal. SIGINT, Stop_all) # ctrl-c Mqtt_client_thread () print "Exit program" Sys.exit (0)

  

Client Service

Most MQTT User services need to be monitored and posted at the same time. For example, a sensor service program, which has to watch the subject in order to receive the action from the other program requests, and the other side to read the sensor state and posted to the topic.

Paho provides examples of how you can use the loop_start() method to enter an on-call script, which allows the designer to read the sensor state and the message in the main operation. As shown below:

Mqttc.loop_start ()  # Enter a looping thread.# main threadwhile True:    temperature = Sensor.blocking_read ()    Mqttc.publish ("Paho/temperature", temperature)

  

MQTT Client Python Example

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.