モチベーション
前回のRaspberryからAWS IoT にsubscribeするの逆のpublishをしたい。
環境
- RaspberryPi3B+
- Raspbian 9.8
参考文献
こちらを参考に
https://github.com/aws/aws-iot-device-sdk-python/blob/master/samples/basicPubSub/basicPubSub.py
ソースコード
コマンドラインから様々な変数を変更できるようにしていますが、前回のコードと同じように、pythonコードの中に定義する形にして、一度subscribeし、1秒毎に無限回publishするようにしたコードが以下。
mqttsubpub.py
# coding: utf-8
from AWSIoTPythonSDK.MQTTLib import AWSIoTMQTTClient
import logging
import time
import argparse
import json
CLIENT_ID = "test_client_id"
ENDPOINT = "a1zpik1blw3qlv-ats.iot.us-east-1.amazonaws.com"
PORT = 8883
ROOT_CA = "./cert/AmazonRootCA1.pem"
PRIVATE_KEY = "./cert/786b47188a-private.pem.key"
CERTIFICATE = "./cert/786b47188a-certificate.pem.crt"
TOPIC = "RasPi3B/sample"
def main():
client = AWSIoTMQTTClient(CLIENT_ID)
client.configureEndpoint(ENDPOINT, PORT)
client.configureCredentials(ROOT_CA, PRIVATE_KEY, CERTIFICATE)
# AWSIoTMQTTClient connection configuration
client.configureAutoReconnectBackoffTime(1, 32, 20)
client.configureOfflinePublishQueueing(-1) # Infinite offline Publish queueing
client.configureDrainingFrequency(2) # Draining: 2 Hz
client.configureConnectDisconnectTimeout(10) # 10 sec
client.configureMQTTOperationTimeout(5) # 5 sec
# Connect and subscribe to AWS IoT
client.connect()
# TOPICが起動したら呼ばれる関数を登録する
client.subscribe(TOPIC, 1, mycallback)
time.sleep(2)
# Publish to the same topic in a loop forever
loopCount = 0
while True:
message = {}
message['message'] = 'Hellow AWS IoT'
message['sequence'] = loopCount
messageJson = json.dumps(message)
# publish(topic, payload, QoS)
client.publish(TOPIC, messageJson, 1)
loopCount += 1
time.sleep(1)
# Custom MQTT message callback
def mycallback(client, userdata, message):
print("Received a new message: ")
print(message.payload)
print("from topic: ")
print(message.topic)
print("--------------\n\n")
if __name__ == "__main__":
main()
実行結果も載せておきます。
5回pub/subした後に、Ctrl-zで中止しました。
pi@raspberrypi:~ $ python mqttsubpub.py
Received a new message:
{"message": "Hellow AWS IoT", "sequence": 0}
from topic:
RasPi3B/sample
--------------
Received a new message:
{"message": "Hellow AWS IoT", "sequence": 1}
from topic:
RasPi3B/sample
--------------
Received a new message:
{"message": "Hellow AWS IoT", "sequence": 2}
from topic:
RasPi3B/sample
--------------
Received a new message:
{"message": "Hellow AWS IoT", "sequence": 3}
from topic:
RasPi3B/sample
--------------
Received a new message:
{"message": "Hellow AWS IoT", "sequence": 4}
from topic:
RasPi3B/sample
--------------
Received a new message:
{"message": "Hellow AWS IoT", "sequence": 5}
from topic:
RasPi3B/sample
--------------
^Z
[3]+ 停止 python mqttsubpub.py
pi@raspberrypi:
APIリファレンス
https://s3.amazonaws.com/aws-iot-device-sdk-python-docs/sphinx/html/index.html#