This is a simple example showing how to use the [Paho MQTT Python client](https://eclipse.org/paho/clients/python/) to send 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/python

import paho.mqtt.publish as publish
import paho.mqtt.client as mqtt
import ssl auth = {
'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 will subscribe on topic f and republish on topic f2

import paho.mqtt.client as mqtt
message = 'ON'
def on_connect(mosq, obj, rc):
mqttc.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); def on_publish(mosq, obj, 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 callbacks
mqttc.on_message = on_message
mqttc.on_connect = on_connect
mqttc.on_publish = on_publish
mqttc.on_subscribe = on_subscribe
# Connect
mqttc.connect("localhost", 1883,60) # Continue the network loop
mqttc.loop_forever()

  用戶端程式偶爾需要發佈訊息,不須與 mqtt broker 保持連線的情形,可用 single() 或 multiple() 方法。這種作法比較省電

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)

  當用戶端程式,例如感應器服務程式,經常或短週期地持續發佈訊息時,則應用連線式設計。

# coding: utf-8
import sys, os, time
reload(sys)
sys.setdefaultencoding('utf-8') import paho.mqtt.client as mqtt # If broker asks 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 = "你好 mqtt" for i in xrange(10):
client.publish(topic, "%s - %d" % (payload, i))
time.sleep(0.01)
# 當 qos = 0, 若訊息間隔太短,就可能會漏發訊息。這是正常現象。

  實作時,可先用 mosquitto_sub 訂閱主題,以監看訊息是否送出。

訂閱主題

本節實作一個類似 mosquitto_sub 的程式,訂閱主題 “tw/rocksaying/#” 。它也是一個服務程式的基礎骨架。

# coding: utf-8
import sys, os, time, signal
reload(sys)
sys.setdefaultencoding('utf-8')
import paho.mqtt.client as mqtt client = None
mqtt_looping = False TOPIC_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.qos def 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_message = 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.loop() 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(*args):
global mqtt_looping
mqtt_looping = False if __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)

  

用戶端服務

大部份 MQTT 用戶端服務程式需要同時監看與發佈訊息。例如一個感應器服務程式,它一邊得監看主題以接收來自其他程式的動作請求;另一邊得讀取感應器狀態後發佈到主題上。

Paho 提供的範例程式使用 loop_start() 方法進入內建的待命執行緒,再讓設計者於主執行緒中讀取感應器狀態與發佈訊息。如下所示:

mqttc.loop_start()  # enter a looping thread.

# main thread
while True:
temperature = sensor.blocking_read()
mqttc.publish("paho/temperature", temperature)

  

mqtt client python example的更多相关文章

  1. python mqtt client publish操作

    使用Python库paho.mqtt.client 模拟mqtt client 连接broker,publish topic. #-*-coding:utf-8-*- import paho.mqtt ...

  2. M2Mqtt is a MQTT client available for all .Net platform

    Introduction M2Mqtt is a MQTT client available for all .Net platform (.Net Framework, .Net Compact F ...

  3. go ---MQTT client

    Paho GO Client   语言 GO 协议 EPL AND EDL 官网地址 http://www.eclipse.org/paho/ API类型 Asynchronous  描述 Paho ...

  4. mqtt client api: 阻塞API

    fusesource版本:mqtt-client-1.11.jar下载地址:https://github.com/fusesource/mqtt-client fusesource提供三种mqtt c ...

  5. Redis client Python usage

    http://www.yiibai.com/redis/redis_sorted_sets.html mport redis r_server = redis.Redis('localhost') # ...

  6. MQTT Client library for C (MQTT客户端C语言库-paho)

    原文:http://www.eclipse.org/paho/files/mqttdoc/MQTTClient/html/index.html 来自我的CSDN博客   最近在使用Paho的MQTT客 ...

  7. MQTT Server搭建(apache-apollo)和MQtt Client搭建

    目标 本文就MQTT server和client搭建做以下总结,方便测试及开发使用,能基于MQTT软件发送和接收消息. 介绍 MQTT是基于tcp的消息发送,目前JAVA方面有两种实现,分别是mqtt ...

  8. php mqtt client

    <?php /* phpMQTT */ class phpMQTT { private $socket; /* holds the socket */ private $msgid = 1; / ...

  9. Asynchronous MQTT client library for C (MQTT异步客户端C语言库-paho)

    原文:http://www.eclipse.org/paho/files/mqttdoc/MQTTAsync/html/index.html MQTT异步客户端C语言库   用于C的异步 MQTT 客 ...

随机推荐

  1. [译]如何在迭代字典的过程中删除其中的某些item(Python)

    最好不要在迭代的过程中删除.你可以使用解析式和filter过滤. 比方说: {key:my_dict[key] for key in my_dict if key !="deleted&qu ...

  2. DS博客作业-05--树

    1.本周学习总结  1.1思维导图  1.2学习体会 1.课堂上的知识也很难听懂,打代码就更难听懂了,真的需要不断练习代码. 2.在学习本章的内容中,一开始只是理解了概念,在真正做题中,一点思路都没有 ...

  3. Spring整合Junit进行单元测试

    I. 加入依赖包 Spring Test (如spring-test-2.5.4.jar) JUnit 4 Spring 其他相关包 II.新建Junit Test Case III.读取配置文件 @ ...

  4. 【Luogu】P3313旅行(树链剖分)

    题目链接 动态开点的树链剖分qwq. 跟小奇的花园一模一样,不做过多讲解. #include<cstdio> #include<cstring> #include<cct ...

  5. Python tldextract模块准确获取域名和后缀

    Python tldextract 模块 - 功能说明 tldextract准确地从URL的域名和子域名分离通用顶级域名或国家顶级域名. 例如,http://www.google.com,你只想取出连 ...

  6. bzoj 4009 接水果 整体二分

    Description 先给出一些盘子, 用路径x-y表示, 有权值 再有Q个询问, 表示水果, 用路径x-y表示 如果盘子是水果的子路径, 可以接住 对于每个水果, 输出可以接住它的盘子的第k小权 ...

  7. xsy 1790 - 不回头的旅行

    from NOIP2016模拟题28 Description 一辆车,开始没油,可以选择一个点(加油站)出发 经过一个点i可加g[i]的油,走一条边减少len的油 没油的时候车就跪了 特别的,跪在加油 ...

  8. Mondriaan's Dream(poj 2411)

    题意:在n*m的方格里铺1*2的骨牌,有多少种方案 /* 第一次做插头DP,感觉和状压差不多. 这道题是利用上一行的状态来更新下一行的状态. 1代表上一行这个位置填了一个竖的(即本行可以填): 0代表 ...

  9. Pόlya定理-学习笔记

    gi为一个为一个置换 c(g),为c(g)的轮换的数量 (循环的数量) 太监了

  10. Android4.2.2 动态显示隐藏屏幕底部的导航栏(对系统源码进行修改)

    需求如题. 在Android4.2.2中,导航栏(也就是屏幕底部的三个按钮,home,back,recentapp)是系统应用SystemUi.apk的一部分,简言之,我们的需求就是让我们的app来控 ...