设为首页 收藏本站
查看: 952|回复: 0

[经验分享] mqtt client python example

[复制链接]

尚未签到

发表于 2017-7-1 17:05:10 | 显示全部楼层 |阅读模式
  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)

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-390064-1-1.html 上篇帖子: 译:微软发布.NET应用架构指南草案 下篇帖子: Ubuntu 下安装Mongodb
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表