――Das Folgende ist ein Programm, das auf Raspberry Pi ausgeführt werden soll.
MQTTpub_test1_qiita.py
from AWSIoTPythonSDK.MQTTLib import AWSIoTMQTTClient
import os
import json
import time
CLIENT_ID = "mqtt_pub1"
IOT_ENDPOINT_URL = "XXX-XXX.XXX.ap-northeast-1.amazonaws.com"
IOT_ENDPOINT_PORT = 8883
PATH = os.getcwd()
ROOT_CA_PATH = PATH + "/XXX-CA1.pem"
PRIVATE_KEY_PATH = PATH + "/XXX-private.pem.key"
CERTIFICATE_PATH = PATH + "/XXX-certificate.pem.crt"
KEEP_ALIVE_TIME = 60
TOPIC = "rasp3-mono/timestamp"
myMQTTClient = AWSIoTMQTTClient(CLIENT_ID)
myMQTTClient.configureEndpoint(IOT_ENDPOINT_URL, IOT_ENDPOINT_PORT)
myMQTTClient.configureCredentials(ROOT_CA_PATH, PRIVATE_KEY_PATH, CERTIFICATE_PATH)
myMQTTClient.configureOfflinePublishQueueing(-1)
myMQTTClient.configureDrainingFrequency(2)
myMQTTClient.configureConnectDisconnectTimeout(10)
myMQTTClient.configureMQTTOperationTimeout(5)
def GetTimeStamp():
return time.time()
if __name__ == '__main__':
myMQTTClient.connect(KEEP_ALIVE_TIME)
num = 0
while num < 10:
message = {}
message['num'] = num
message['time'] = GetTimeStamp()
payload = json.dumps(message)
print("payload=", payload)
myMQTTClient.publish(TOPIC, payload, 1)
num += 1
time.sleep(5)
MQTTsub_test1_qiita.py
from AWSIoTPythonSDK.MQTTLib import AWSIoTMQTTClient
import os
import json
import time
CLIENT_ID = "mqtt_sub1"
IOT_ENDPOINT_URL = "XXX-XXX.XXX.ap-northeast-1.amazonaws.com"
IOT_ENDPOINT_PORT = 8883
PATH = os.getcwd()
ROOT_CA_PATH = PATH + "/XXX-CA1.pem"
PRIVATE_KEY_PATH = PATH + "/XXX-private.pem.key"
CERTIFICATE_PATH = PATH + "/XXX-certificate.pem.crt"
KEEP_ALIVE_TIME = 60
TOPIC = "rasp3-mono/timestamp"
myMQTTClient = AWSIoTMQTTClient(CLIENT_ID)
myMQTTClient.configureEndpoint(IOT_ENDPOINT_URL, IOT_ENDPOINT_PORT)
myMQTTClient.configureCredentials(ROOT_CA_PATH, PRIVATE_KEY_PATH, CERTIFICATE_PATH)
myMQTTClient.configureOfflinePublishQueueing(-1)
myMQTTClient.configureDrainingFrequency(2)
myMQTTClient.configureConnectDisconnectTimeout(10)
myMQTTClient.configureMQTTOperationTimeout(5)
def customCallback(client, userdata, message):
dict_message = json.loads(message.payload)
print("num = {}, Time Difference = {}".format(dict_message['num'], time.time() - dict_message['time']))
if __name__ == '__main__':
myMQTTClient.connect(KEEP_ALIVE_TIME)
num = 0
while num < 12:
myMQTTClient.subscribe(TOPIC, 1, customCallback)
num += 1
time.sleep(5)
――Wenn ich 30 Mal Pub / Sub ausgeführt habe, war das Ergebnis der Zeitverzögerung wie folgt.
――Die Zeitverzögerung hängt von der Kommunikationsumgebung ab und dient nur als Referenz. ―― Wie oben erwähnt, wurde der Verbindungstest mit dem Pub / Sub-Programm abgeschlossen.
Recommended Posts