--Programme de publication de messages: MQTTpub_test1_qiita.py
―― Ce qui suit est un programme à exécuter sur Raspberry Pi. --Publier le programme
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)
--Exemple d'exécution de programme d'abonnement --Le décalage horaire est affiché
――Lorsque j'ai exécuté Pub / Sub 30 fois, le résultat du décalage est le suivant.
――Le décalage temporel dépend de l'environnement de communication, c'est donc juste pour référence. ――Comme mentionné ci-dessus, le test de connexion a été effectué à l'aide du programme Pub / Sub.
Recommended Posts