Every Halloween my kids and I build some kind of decoration to scare everyone. The past few years we have been evolving a pneumatic wolf head that pops up and scares you. Then, it takes a picture of you looking silly. It was based on a RaspberryPi and AWS IoT. This year I wanted to move to Arduino, but I could not find instructions for connecting to AWS IoT from the Arduino.
AWS had an SDK for Arduino but it has not been maintained and does not appear to work with the ESP32 that I am using. There is also a recent blog post for the ESP32 but I could not find the MQTT library they use from the Arduino IDE. I would like to use the ArduinoMqttClient because it is actively maintained by Arduino and there are a lot of examples available for this library. However, there were no examples of using ArduinoMqttClient with AWS.
AWS IoT Core supports MQTT using TLS Mutual Authentication with X.509 certificates for authentication. Most ArduinoMqttClient examples use basic auth with a username and password. I was able to build a solution by combining the above blog posts.
First, we need a couple of libraries. The WiFi libraries should already be installed. You will need to add ArduinoMqttClient, but it is readily available from Tools > Manage Libraries menu.
voidsetup(){// initialize the serial port
Serial.begin(115200);// Connect to Wi-Fi network with SSID and password
Serial.print("Connecting to ");Serial.println(WIFI_SSID);WiFi.begin(WIFI_SSID,WIFI_PASSWORD);while(WiFi.status()!=WL_CONNECTED){delay(500);Serial.print(".");}// Print local IP address
Serial.println("");Serial.println("WiFi connected.");Serial.println("IP address: ");Serial.println(WiFi.localIP());// Connect to AWS IoT
wifiClient.setCACert(AWS_CERT_CA);wifiClient.setCertificate(AWS_CERT_CRT);wifiClient.setPrivateKey(AWS_CERT_PRIVATE);if(mqttClient.connect(AWS_IOT_ENDPOINT,8883)){Serial.println("You're connected to the MQTT broker!");Serial.println();}else{Serial.print("MQTT connection failed! Error code = ");Serial.println(mqttClient.connectError());}// Subscribe to MQTT and register a callback
mqttClient.onMessage(messageHandler);mqttClient.subscribe(MQTT_TOPIC);}
My message subscribe handler prints the message to the serial console.
1
2
3
4
5
6
7
8
9
10
11
12
voidmessageHandler(intmessageSize){// we received a message, print out the topic and contents
Serial.print("Received a message with topic '");Serial.print(mqttClient.messageTopic());// use the Stream interface to print the contents
while(mqttClient.available()){Serial.print((char)mqttClient.read());}Serial.println("");}