[PYTHON] Raspberry Pi and AWS IoT connection program example

Premise

--In this article, Raspberry Pi and AWS IoT are already connectable. --For the connection method, refer to This Qiita article. --Write a Pub / Sub Python program using the MQTT protocol.

environment

Program structure

--Program to publish messages: MQTTpub_test1_qiita.py --Store the time stamp in a message and send it. --For the time stamp, use the UNIX time (epoch seconds) that can be obtained with the time () function. --Program to subscribe to messages: MQTTsub_test1_qiita.py --See the difference between the time stamp stored in the message and the time stamp when it was received. Measure the time lag.

PubSub Figure 1.png

program

――The following is a program to be executed on Raspberry Pi. --Publish program

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)

--Subscribe program

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)

Execution example

--Subscribe program execution example --Time lag is displayed

Output example_Figure 2.png

--Program considerations --In the Publish program, the message to be sent used the json format. --The json format received by the Subscribe program is returned to the dictionary type. --Please match XXX to the usage environment.

Comparison

--Tested with two connection methods. (The program is the same)

  1. Test connecting to AWS IoT message prober via WiFi
  2. Test connecting to AWS IoT message broker via iPhone tethering (4G)

――When I ran Pub / Sub 30 times, the result of the time lag was as follows. 比較_図3.png

――The time lag depends on the communication environment, so it is just for reference. ――As mentioned above, the connection test was completed using the Pub / Sub program.

Recommended Posts

Raspberry Pi and AWS IoT connection program example
Easy connection between Raspberry Pi and AWS IoT
Send data from Raspberry Pi using AWS IOT
Easy IoT to start with Raspberry Pi and MESH
Run AWS IoT Device SDK for Python on Raspberry Pi
MQTT on Raspberry Pi and Mac
Create your own IoT platform using raspberry pi and ESP32 (Part 1)
[Raspberry Pi] Add a thermometer and a hygrometer
AWS IoT device life and death monitoring
IPsec gateway VPN construction with CentOS 8 and openSUSE (Raspberry Pi) --2 StrongSwan VPN connection confirmation
Raspberry Pi 3 x Julius (reading file and grammar file)
MQTT RC car with Arduino and Raspberry Pi
Get temperature and humidity with DHT11 and Raspberry Pi
Edit and debug the code in the Raspberry Pi with VS Code's SSH connection feature
Simple VPN construction of IPsec gateway with Ubuntu 20.04 and Raspberry Pi --2 StrongSwan VPN connection confirmation
Create your own IoT platform using raspberry pi and ESP32 (Part 2) ~ ESP32 setting L Chika
Record temperature and humidity with systemd on Raspberry Pi
Machine learning with Raspberry Pi 4 and Coral USB Accelerator
Create a color sensor using a Raspberry Pi and a camera
Monitor temperature using Raspberry Pi + Alibaba cloud IoT platform
Detect mask wearing status with OpenCV and Raspberry Pi
Measure temperature and humidity with Raspberry Pi3 and visualize with Ambient
Ubuntu 20.04 on raspberry pi 4 with OpenCV and use with python
Installation of Docker on Raspberry Pi and L Chika
Install pyenv on Raspberry Pi and version control Python
Getting Started with Yocto Project with Raspberry Pi 4 and WSL2
Troubleshoot with installing OpenCV on Raspberry Pi and capturing
Use raspberry Pi and Julius (speech recognition). ③ Dictionary creation
Create your own IoT platform using raspberry pi and ESP32 (Part 3) ~ ESP32 settings Analog temperature sensor
Raspberry Pi + python + IoT device, environment construction procedure to start image processing and machine learning