0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Watson IoT Platform - MQTT - Publish/Subscribeしてみる

Posted at

初めてWatson IoT Platformを使ってみよう、というかたのためのガイドです。
Watson IoT Platformを使ってみるでIoTアプリを準備しました。
MessageSightを動かすでMQTTブローカーとしてMessageSightを準備しました。

#Publishしてみる

  1. 下記のようなプログラムを使ってpublishします。
  2. トピック名やClientID、payload(送付するデータ)などを変化させて試してみます。
pub.py
#!/usr/bin/python
# -*- coding: utf-8 -*-

import time
import paho.mqtt.client as mqtt
import random

topic = "topic/test"
clientID = "pubTester"
broker = "172.16.xxx.xxx"

mqttc = mqtt.Client(clientID)
mqttc.connect(host=broker, port=1883, keepalive=60)
while mqttc.loop() == 0:
 
	temp = random.randrange(-10,40)
	humidity = random.randrange(20,99)
	print "temp = " + str(temp) + ", humidity = " + str(humidity)
	msg = " {\"d\": {\"temperature\": " + str(temp) +",\"humidity\": " + str(humidity) + "} }";

	mqttc.publish(topic, payload=msg, qos=0, retain=False)
	print "message published"

	time.sleep(1)

#Subscribeしてみる

  1. 下記のようなプログラムを使ってsubscribeします。
  2. トピック名やClientIDなどを変化させて試してみます。
sub.py
#!/usr/bin/python
# -*- coding: utf-8 -*-

import paho.mqtt.client as mqtt

topic = "topic/test"
clientID = "subTester"
broker = "172.16.xxx.xxx"

def on_connect(client, userdata, flags, rc):
    print("connected")
    client.subscribe(topic)

def on_message(client, userdata, msg):
    print(msg.topic+" "+str(msg.payload))

mqttc = mqtt.Client(clientID)

mqttc.on_connect = on_connect
mqttc.on_message = on_message

mqttc.connect(host=broker, port=1883, keepalive=60)

mqttc.loop_forever()
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?