Hub は、iot-aa
Device は pansy
と設定されている Azure IoT Hub に paho で subscribe するサンプルです。
azure_subscribe.py
#! /usr/bin/python
# -*- coding: utf-8 -*-
#
# azure_subscribe.py
#
# Feb/05/2018
#
# ------------------------------------------------------------------
import sys
import ssl
from time import sleep
import paho.mqtt.client as mqtt
from generate_sas_token import generate_sas_token
# ------------------------------------------------------------------
sys.stderr.write("*** 開始 ***\n")
uri = "iot-aa.azure-devices.net/devices/pansy"
key = "2eQ2wF5OjZLP7tq6PG123456789RTfAnMJbZ8wtJPu4="
policy_name = None
iexpire = 3600
sas_token = generate_sas_token(uri, key, policy_name, iexpire)
#
path_to_root_cert = "/etc/ssl/certs/ca-certificates.crt"
host = 'iot-aa.azure-devices.net'
port = 8883
topic = 'devices/pansy/messages/devicebound/#'
# ------------------------------------------------------------------
def on_connect(client, userdata, flags, respons_code):
sys.stderr.write("***on_connect ***\n")
print('status {0}'.format(respons_code))
client.subscribe(topic)
# ------------------------------------------------------------------
def on_message(client, userdata, msg):
sys.stderr.write("***on_message ***\n")
print(msg.topic + ' ' + str(msg.payload,'utf-8'))
# ------------------------------------------------------------------
client = mqtt.Client(client_id="pansy",protocol=mqtt.MQTTv311)
client.username_pw_set(username="iot-aa.azure-devices.net/pansy", password=sas_token)
client.tls_set(ca_certs=path_to_root_cert, certfile=None,
keyfile=None, cert_reqs=ssl.CERT_REQUIRED,
tls_version=ssl.PROTOCOL_TLSv1_2, ciphers=None)
client.tls_insecure_set(False)
client.on_connect = on_connect
client.on_message = on_message
try:
client.connect(host, port=port, keepalive=60)
client.loop_forever()
except Exception as ee:
sys.stderr.write("*** error *** in client.connect ***\n")
sys.stderr.write(str(ee) + "\n")
sys.stderr.write("*** 終了 ***\n")
# ------------------------------------------------------------------
generate_sas_token.py はこちらです。
Azure IoT Hub に paho で publish