|
| 1 | +/* |
| 2 | + AWS IoT WiFi |
| 3 | +
|
| 4 | + This sketch securely connects to an AWS IoT using MQTT over WiFi. |
| 5 | + It uses a a WiFiSSLClient configured with a private key and |
| 6 | + a public certificate for SSL/TLS authetication. |
| 7 | +
|
| 8 | + Use openssl to generate a compatible prive key (prime256v1) and |
| 9 | + a CSR to upload to AWS IoT core |
| 10 | +
|
| 11 | + # openssl ecparam -name prime256v1 -genkey -noout -out private-key.pem |
| 12 | + # openssl req -new -key private-key.pem -out csr.csr -days 3650 |
| 13 | +
|
| 14 | + It publishes a message every 5 seconds to arduino/outgoing |
| 15 | + topic and subscribes to messages on the arduino/incoming |
| 16 | + topic. |
| 17 | +
|
| 18 | + This example code is in the public domain. |
| 19 | +*/ |
| 20 | + |
| 21 | +#include <ArduinoMqttClient.h> |
| 22 | +#include <Arduino_ConnectionHandler.h> |
| 23 | +#include <Arduino_JSON.h> |
| 24 | +#include <NTPClient.h> |
| 25 | +#include <WiFi.h> |
| 26 | +#include <WiFiUdp.h> |
| 27 | + |
| 28 | +#include "arduino_secrets.h" |
| 29 | + |
| 30 | +// Enter your sensitive data in arduino_secrets.h |
| 31 | +constexpr char broker[] { SECRET_BROKER }; |
| 32 | +constexpr unsigned port { SECRET_PORT }; |
| 33 | +const char* certificate { SECRET_CERTIFICATE }; |
| 34 | +const char* privateKey { PRIVATE_KEY }; |
| 35 | +constexpr char ssid[] { SECRET_SSID }; |
| 36 | +constexpr char pass[] { SECRET_PASS }; |
| 37 | + |
| 38 | +WiFiConnectionHandler conMan(SECRET_SSID, SECRET_PASS); |
| 39 | +WiFiUDP NTPUdp; |
| 40 | +NTPClient timeClient(NTPUdp); |
| 41 | +WiFiSSLClient sslClient; |
| 42 | +MqttClient mqttClient(sslClient); |
| 43 | + |
| 44 | +unsigned long lastMillis { 0 }; |
| 45 | + |
| 46 | +void setup() |
| 47 | +{ |
| 48 | + Serial.begin(115200); |
| 49 | + |
| 50 | + // Wait for Serial Monitor or start after 2.5s |
| 51 | + for (const auto startNow = millis() + 2500; !Serial && millis() < startNow; delay(250)); |
| 52 | + |
| 53 | + // Set the callbacks for connectivity management |
| 54 | + conMan.addCallback(NetworkConnectionEvent::CONNECTED, onNetworkConnect); |
| 55 | + conMan.addCallback(NetworkConnectionEvent::DISCONNECTED, onNetworkDisconnect); |
| 56 | + conMan.addCallback(NetworkConnectionEvent::ERROR, onNetworkError); |
| 57 | + |
| 58 | + // Configure TLS key/certificate pair |
| 59 | + sslClient.setCertificate(certificate); |
| 60 | + sslClient.setPrivateKey(privateKey); |
| 61 | + // mqttClient.setId("Your Thing ID"); |
| 62 | + mqttClient.onMessage(onMessageReceived); |
| 63 | + |
| 64 | + timeClient.begin(); |
| 65 | +} |
| 66 | + |
| 67 | +void loop() |
| 68 | +{ |
| 69 | + // Automatically manage connectivity |
| 70 | + const auto conStatus = conMan.check(); |
| 71 | + |
| 72 | + if (conStatus != NetworkConnectionState::CONNECTED) |
| 73 | + return; |
| 74 | + |
| 75 | + if (!mqttClient.connected()) { |
| 76 | + // MQTT client is disconnected, connect |
| 77 | + connectMQTT(); |
| 78 | + } |
| 79 | + |
| 80 | + // poll for new MQTT messages and send keep alives |
| 81 | + mqttClient.poll(); |
| 82 | + |
| 83 | + // publish a message roughly every 5 seconds. |
| 84 | + if (millis() - lastMillis > 5000) { |
| 85 | + lastMillis = millis(); |
| 86 | + |
| 87 | + publishMessage(); |
| 88 | + } |
| 89 | +} |
| 90 | + |
| 91 | +void setNtpTime() |
| 92 | +{ |
| 93 | + timeClient.forceUpdate(); |
| 94 | + const auto epoch = timeClient.getEpochTime(); |
| 95 | + set_time(epoch); |
| 96 | +} |
| 97 | + |
| 98 | +unsigned long getTime() |
| 99 | +{ |
| 100 | + const auto now = time(NULL); |
| 101 | + return now; |
| 102 | +} |
| 103 | + |
| 104 | +void connectMQTT() |
| 105 | +{ |
| 106 | + Serial.print("Attempting to MQTT broker: "); |
| 107 | + Serial.print(broker); |
| 108 | + Serial.print(":"); |
| 109 | + Serial.print(port); |
| 110 | + Serial.println(); |
| 111 | + |
| 112 | + int status; |
| 113 | + while ((status = mqttClient.connect(broker, port)) == 0) { |
| 114 | + // failed, retry |
| 115 | + Serial.println(status); |
| 116 | + delay(1000); |
| 117 | + } |
| 118 | + Serial.println(); |
| 119 | + |
| 120 | + Serial.println("You're connected to the MQTT broker"); |
| 121 | + Serial.println(); |
| 122 | + |
| 123 | + // subscribe to a topic with QoS 1 |
| 124 | + constexpr char incomingTopic[] { "arduino/incoming" }; |
| 125 | + constexpr int incomingQoS { 1 }; |
| 126 | + Serial.print("Subscribing to topic: "); |
| 127 | + Serial.print(incomingTopic); |
| 128 | + Serial.print(" with QoS "); |
| 129 | + Serial.println(incomingQoS); |
| 130 | + mqttClient.subscribe(incomingTopic, incomingQoS); |
| 131 | +} |
| 132 | + |
| 133 | +void publishMessage() |
| 134 | +{ |
| 135 | + Serial.println("Publishing message"); |
| 136 | + |
| 137 | + JSONVar payload; |
| 138 | + String msg = "Hello, World! "; |
| 139 | + msg += millis(); |
| 140 | + payload["message"] = msg; |
| 141 | + payload["rssi"] = WiFi.RSSI(); |
| 142 | + |
| 143 | + JSONVar message; |
| 144 | + message["ts"] = static_cast<unsigned long>(time(nullptr)); |
| 145 | + message["payload"] = payload; |
| 146 | + |
| 147 | + String messageString = JSON.stringify(message); |
| 148 | + Serial.println(messageString); |
| 149 | + |
| 150 | + // send message, the Print interface can be used to set the message contents |
| 151 | + constexpr char outgoingTopic[] { "arduino/outgoing" }; |
| 152 | + |
| 153 | + mqttClient.beginMessage(outgoingTopic); |
| 154 | + mqttClient.print(messageString); |
| 155 | + mqttClient.endMessage(); |
| 156 | +} |
| 157 | + |
| 158 | +void onMessageReceived(int messageSize) |
| 159 | +{ |
| 160 | + // we received a message, print out the topic and contents |
| 161 | + Serial.println(); |
| 162 | + Serial.print("Received a message with topic '"); |
| 163 | + Serial.print(mqttClient.messageTopic()); |
| 164 | + Serial.print("', length "); |
| 165 | + Serial.print(messageSize); |
| 166 | + Serial.println(" bytes:"); |
| 167 | + |
| 168 | + /* |
| 169 | + // Message from AWS MQTT Test Client |
| 170 | + { |
| 171 | + "message": "Hello from AWS IoT console" |
| 172 | + } |
| 173 | + */ |
| 174 | + |
| 175 | + char bytes[messageSize] {}; |
| 176 | + for (int i = 0; i < messageSize; i++) |
| 177 | + bytes[i] = mqttClient.read(); |
| 178 | + |
| 179 | + JSONVar jsonMessage = JSON.parse(bytes); |
| 180 | + auto text = jsonMessage["message"]; |
| 181 | + |
| 182 | + Serial.print("["); |
| 183 | + Serial.print(time(nullptr)); |
| 184 | + Serial.print("] "); |
| 185 | + Serial.print("Message: "); |
| 186 | + Serial.println(text); |
| 187 | + |
| 188 | + Serial.println(); |
| 189 | +} |
| 190 | + |
| 191 | +void onNetworkConnect() |
| 192 | +{ |
| 193 | + Serial.println(">>>> CONNECTED to network"); |
| 194 | + |
| 195 | + printWifiStatus(); |
| 196 | + setNtpTime(); |
| 197 | + connectMQTT(); |
| 198 | +} |
| 199 | + |
| 200 | +void onNetworkDisconnect() |
| 201 | +{ |
| 202 | + Serial.println(">>>> DISCONNECTED from network"); |
| 203 | +} |
| 204 | + |
| 205 | +void onNetworkError() |
| 206 | +{ |
| 207 | + Serial.println(">>>> ERROR"); |
| 208 | +} |
| 209 | + |
| 210 | +void printWifiStatus() |
| 211 | +{ |
| 212 | + // print the SSID of the network you're attached to: |
| 213 | + Serial.print("SSID: "); |
| 214 | + Serial.println(WiFi.SSID()); |
| 215 | + |
| 216 | + // print the received signal strength: |
| 217 | + Serial.print("signal strength (RSSI):"); |
| 218 | + Serial.print(WiFi.RSSI()); |
| 219 | + Serial.println(" dBm"); |
| 220 | + Serial.println(); |
| 221 | + |
| 222 | + // print your board's IP address: |
| 223 | + Serial.print("Local IP: "); |
| 224 | + Serial.println(WiFi.localIP()); |
| 225 | + Serial.print("Local GW: "); |
| 226 | + Serial.println(WiFi.gatewayIP()); |
| 227 | + Serial.println(); |
| 228 | +} |
0 commit comments