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