初めてWatson IoT Platformを使ってみよう、というかたのためのガイドです。
Watson IoT Platformを使ってみるでIoTアプリを準備しました。
#サンプルアプリからQuickstartへpublish
- 以下のアプリを使用してQuickstartへpublishします
-
python pub.py
で実行します
pub.py
#!/usr/bin/python
# -*- coding: utf-8 -*-
import time
import paho.mqtt.client as mqtt
import random
import sys
MQTT_BROKER="quickstart.messaging.internetofthings.ibmcloud.com"
MQTT_PORT=1883
MQTT_TIMEOUT=60
MQTT_PUB_TOPIC="iot-2/evt/status/fmt/json"
latTuple = (36.065269, 36.045284, 36.058608, 36.178417, 36.305790, 36.293616, 36.238253, 36.172874, 35.976411, 35.878552, 35.987524)
longTuple = (-112.123288, -112.263364, -112.428159, -112.511929, -112.399319, -112.216672, -112.051877, -111.850003, -111.703061, -111.856870, -112.128781)
def on_connect(client, userdata, flags, rc):
print("on connect")
def on_disconnect(client, userdata, rc):
print("on disconnect")
client.unsubscribe(MQTT_SUB_TOPIC)
def on_message(client, userdata, msg):
print("on message: " + msg.topic + " " + str(msg.payload))
def mqttConnect():
print("mqttConnect")
try:
global client
client = mqtt.Client("d:quickstart:myThing:001122334455")
client.on_connect = on_connect
client.on_message = on_message
client.on_disconnect = on_disconnect
client.connect(MQTT_BROKER,MQTT_PORT,MQTT_TIMEOUT)
print("connected")
except KeyboardInterrupt, kex:
sys.exit()
except Exception, ex:
print("mqttConnect error")
def mqttPublish():
while client.loop() == 0:
for lat in latTuple:
index = latTuple.index(lat)
long =longTuple[index]
temp = random.randrange(250,450)/10.0
humid = random.randrange(500,1000)/10.0
print "#" + str(index) + ", temp = " + str(temp) + ", humid = " + str(humid) + ", lat = " + str(lat) + ", long = " + str(long)
msg = " {\"d\": {\"temperature\": " + str(temp) +",\"humidity\": " + str(humid) +", \"latitude\": " + str(lat) +", \"longitude\": " + str(long) + "} }";
client.publish(MQTT_PUB_TOPIC, msg, 0, True)
try:
print raw_input("[Enter] to send another request")
except:
sys.exit()
def mqttPublishAuto():
while client.loop() == 0:
for lat in latTuple:
try:
index = latTuple.index(lat)
long =longTuple[index]
temp = random.randrange(250,450)/10.0
humid = random.randrange(500,1000)/10.0
print "#" + str(index) + ", temp = " + str(temp) + ", humid = " + str(humid) + ", lat = " + str(lat) + ", long = " + str(long)
msg = " {\"d\": {\"Temperature\": " + str(temp) +",\"Humidity\": " + str(humid) +", \"latitude\": " + str(lat) +", \"longitude\": " + str(long) + "} }";
client.publish(MQTT_PUB_TOPIC, msg, 0, True)
time.sleep(2)
except:
sys.exit()
if __name__ == "__main__":
print("--- started ---")
mqttConnect()
mqttPublishAuto()
print("--- program ended ---")
- Node-RED側では
Device ID
に上記の001122334455
を指定して受信します。