python ibmcloud-pythonmqttdevice.py
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python ibmcloud-pythonmqttdevice.py相关的知识,希望对你有一定的参考价值。
# Python sample to publish data to Aercloud
# uses mosquitto Python API
# see https://aeriscom.jira.com/wiki/display/DOCS/API+Reference#APIReference-MQTT
# Andy Piper @andypiper November 2013
import json
import mosquitto
# define callbacks
def on_connect(mosq, obj, rc):
if rc == 0:
print("Connected to Aercloud successfully.")
else:
print("Cannot connect, rc: "+str(rc))
def on_connect2(mosq, obj, rc):
if rc == 0:
mosq.subscribe("hack1/things/1/location", 0)
print("Connected to IBM cloud successfully.")
else:
print("Cannot connect, rc: "+str(rc))
def on_disconnect(mosq, obj, rc):
print("Disconnected.")
def on_publish(mosq, obj, mid):
print("Message ID "+str(mid)+" published.")
def on_subscribe(mosq, obj, mid, granted_qos):
print("Subscribed: "+str(mid)+" "+str(granted_qos))
def on_message(mosq, obj, msg):
print(msg.topic+" "+str(msg.qos)+" "+str(msg.payload))
lon,lat = str(msg.payload).split(",")
# update robot location (should really set proper timestamp too...)
pubmsg=json.dumps({
"Accuracy":"10",
"Latitude":lat,
"LocationTimeStamp":"1366361979315",
"Longitude":lon
})
print("Message data to be published: " + pubmsg)
mqttc.publish(user + "/scls/" + sclID + "/containers/" + container + "/contentInstances", pubmsg)
# define variables
broker = "mqtt.aercloud.aeris.com"
port = 1883
user = "myuserid" # Aercloud User ID
pw = "mykey" # Aercloud API Key
sclID = "robotclient" # Aercloud sclID / deviceID (must be provisioned)
container = "mycontainer" # Aercloud Container
# create MQTT client instance for Aercloud
mqttc = mosquitto.Mosquitto(sclID)
mqttc.username_pw_set(user, pw) # must be user ID + API key
# set callbacks to be triggered
mqttc.on_connect = on_connect
mqttc.on_publish = on_publish
mqttc.on_disconnect = on_disconnect
# connect to broker
# NB call loop() regularly to enable callbacks to be triggered
mqttc.connect(broker, port, 60)
mqttc.loop()
# create MQTT client for IBM cloud
mqttc2 = mosquitto.Mosquitto("robotlistener")
mqttc2.on_subscribe = on_subscribe
mqttc2.on_message = on_message
mqttc2.on_connect = on_connect2
mqttc2.connect("5.153.17.246", 1883, 60)
mqttc2.loop_forever()
以上是关于python ibmcloud-pythonmqttdevice.py的主要内容,如果未能解决你的问题,请参考以下文章
Python代写,Python作业代写,代写Python,代做Python
Python开发
Python,python,python
Python 介绍
Python学习之认识python
python初识