Skip to content

Instantly share code, notes, and snippets.

@yoshidaken1
Last active October 14, 2016 02:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yoshidaken1/80c51dc1b9ef297b91ebe8caf25b95ff to your computer and use it in GitHub Desktop.
Save yoshidaken1/80c51dc1b9ef297b91ebe8caf25b95ff to your computer and use it in GitHub Desktop.
##coding: utf-8
import paho.mqtt.client as mqtt
import time
host = 'beam.soracom.io'
port = 1883
topic = 'nic/52/2f/5226/led/01'
# インスタンス作成時に protocol v3.1.1 を指定します
client = mqtt.Client(protocol=mqtt.MQTTv311)
client.connect(host, port=port, keepalive=60)
#例外を検出する
try:
flag = 1
#無限ループ
while 1:
client.publish(topic, str(flag))
print("pub:" + topic + ' ' + str(flag))
if flag == 0:
flag = 1
else:
flag = 0
time.sleep(1)
#キーボード例外を検出
except KeyboardInterrupt:
#何もしない
pass
#クライアント切断
client.disconnect()
##coding: utf-8
import paho.mqtt.client as mqtt
# GPIOライブラリのインポート
import RPi.GPIO as GPIO
#ピン番号の割り当て:コネクタのピン番号
GPIO.setmode(GPIO.BOARD)
#使用するピン番号
LED = 11
#使用するピンを出力ピンに設定し初期出力をローレベルに
GPIO.setup(LED, GPIO.OUT, initial = GPIO.LOW)
###### 接続先情報
host = 'beam.soracom.io'
port = 1883
###### MQTTトピック(pub/sub側で一致している必要がある)
topic = 'nic/52/2f/5226/led/01'
# MQTT接続時のイベントリスナ
def on_connect(client, userdata, flags, respons_code):
print('status {0}'.format(respons_code))
client.subscribe(topic)
# MQTTメッセージ受信時のイベントリスナ
def on_message(client, userdata, msg):
print(msg.topic + ' ' + str(msg.payload))
if str(msg.payload) == '1':
GPIO.output(LED, GPIO.HIGH)
else:
GPIO.output(LED, GPIO.LOW)
# Publisherと同様に v3.1.1を利用
client = mqtt.Client(protocol=mqtt.MQTTv311)
client.on_connect = on_connect
client.on_message = on_message
client.connect(host, port=port, keepalive=60)
# 待ち受け状態にする
client.loop_forever()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment