|
| 1 | +#include <Arduino.h> |
| 2 | + |
| 3 | +#include "secrets.h" |
| 4 | +#include <WiFiClientSecure.h> |
| 5 | +#include <PubSubClient.h> |
| 6 | +#include <ArduinoJson.h> |
| 7 | +#include "WiFi.h" |
| 8 | + |
| 9 | +// The MQTT topics that this device should publish/subscribe |
| 10 | +#define AWS_IOT_PUBLISH_TOPIC "esp32/pub" |
| 11 | +#define AWS_IOT_SUBSCRIBE_TOPIC "esp32/sub" |
| 12 | + |
| 13 | +WiFiClientSecure net = WiFiClientSecure(); |
| 14 | +PubSubClient client(net); |
| 15 | + |
| 16 | +void messageHandler(char* topic, byte* payload, unsigned int length) |
| 17 | +{ |
| 18 | + Serial.print("incoming: "); |
| 19 | + Serial.println(topic); |
| 20 | + |
| 21 | + StaticJsonDocument<200> doc; |
| 22 | + deserializeJson(doc, payload); |
| 23 | + const char* message = doc["message"]; |
| 24 | + Serial.println(message); |
| 25 | +} |
| 26 | + |
| 27 | +void connectAWS() |
| 28 | +{ |
| 29 | + WiFi.mode(WIFI_STA); |
| 30 | + WiFi.begin(WIFI_SSID, WIFI_PASSWORD); |
| 31 | + |
| 32 | + Serial.println("Connecting to Wi-Fi"); |
| 33 | + |
| 34 | + while (WiFi.status() != WL_CONNECTED){ |
| 35 | + delay(500); |
| 36 | + Serial.print("."); |
| 37 | + } |
| 38 | + |
| 39 | + Serial.println("Connecting AWS"); |
| 40 | + // Configure WiFiClientSecure to use the AWS IoT device credentials |
| 41 | + net.setCACert(AWS_CERT_CA); |
| 42 | + net.setCertificate(AWS_CERT_CRT); |
| 43 | + net.setPrivateKey(AWS_CERT_PRIVATE); |
| 44 | + |
| 45 | + Serial.println("Connecting to Endpoint"); |
| 46 | + // Connect to the MQTT broker on the AWS endpoint we defined earlier |
| 47 | + client.setServer(AWS_IOT_ENDPOINT, 8883); |
| 48 | + |
| 49 | + // Create a message handler |
| 50 | + client.setCallback(messageHandler); |
| 51 | + |
| 52 | + Serial.print("Connecting to AWS IOT"); |
| 53 | + |
| 54 | + while (!client.connect(THINGNAME)) { |
| 55 | + Serial.print("."); |
| 56 | + delay(100); |
| 57 | + } |
| 58 | + |
| 59 | + if(!client.connected()){ |
| 60 | + Serial.println("AWS IoT Timeout!"); |
| 61 | + return; |
| 62 | + } |
| 63 | + |
| 64 | + Serial.print("Subscribing to the topic"); |
| 65 | + // Subscribe to a topic |
| 66 | + client.subscribe(AWS_IOT_SUBSCRIBE_TOPIC); |
| 67 | + |
| 68 | + Serial.println("AWS IoT Connected!"); |
| 69 | +} |
| 70 | + |
| 71 | +void publishMessage() |
| 72 | +{ |
| 73 | + StaticJsonDocument<200> doc; |
| 74 | + doc["time"] = millis(); |
| 75 | + doc["sensor_a0"] = analogRead(0); |
| 76 | + char jsonBuffer[512]; |
| 77 | + serializeJson(doc, jsonBuffer); // print to client |
| 78 | + |
| 79 | + client.publish(AWS_IOT_PUBLISH_TOPIC, jsonBuffer); |
| 80 | + Serial.println("published"); |
| 81 | +} |
| 82 | + |
| 83 | +void setup() { |
| 84 | + Serial.begin(115200); |
| 85 | + connectAWS(); |
| 86 | +} |
| 87 | + |
| 88 | +void loop() { |
| 89 | + publishMessage(); |
| 90 | + client.loop(); |
| 91 | + delay(3000); |
| 92 | +} |
0 commit comments