-
Notifications
You must be signed in to change notification settings - Fork 0
/
MQTTClient_aws_iot.ino
320 lines (238 loc) · 8.28 KB
/
MQTTClient_aws_iot.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
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
/****************************************************************************************************************************
MQTTClient_aws_iot.ino - Dead simple aws iot client for Ethernet shields
For Ethernet shields using WT32_ETH01 (ESP32 + LAN8720)
WebServer_WT32_ETH01 is a library for the Ethernet LAN8720 in WT32_ETH01 to run WebServer
Based on and modified from ESP8266 https://github.com/esp8266/Arduino/releases
Built by Khoi Hoang https://github.com/khoih-prog/WebServer_WT32_ETH01
Licensed under MIT license
*****************************************************************************************************************************/
/*
Basic MQTT example (for aws iot!)
This sketch demonstrates the basic capabilities of the library.
It connects to an aws iot server then:
- publishes {Hello from MQTTClient_aws_iot on WT32-ETH01 to the topic [TOPIC]
- subscribes to the topic [MQTT_Sub], printing out any messages
it receives. NB - it assumes the received payloads are strings not binary
It will reconnect to the server if the connection is lost using a blocking
reconnect function. See the 'mqtt_reconnect_nonblocking' example for how to
achieve the same result without blocking the main loop.
*/
#define DEBUG_ETHERNET_WEBSERVER_PORT Serial
// Debug Level from 0 to 4
#define _ETHERNET_WEBSERVER_LOGLEVEL_ 3
#include <WebServer_WT32_ETH01.h>
#include <WiFiClientSecure.h>
// Select the IP address according to your local network
IPAddress myIP(192, 168, 1, 232);
IPAddress myGW(192, 168, 1, 1);
IPAddress mySN(255, 255, 255, 0);
// Google DNS Server IP
IPAddress myDNS(8, 8, 8, 8);
#include "secrets.h"
#include <PubSubClient.h>
const char *ID = "MQTTClient_aws_iot-Client"; // Name of our device, must be unique
const char *TOPIC = "$aws/things/Thing03/shadow/update"; // Topic to publish to
const char *subTopic = "MQTT_Sub"; // Topic to subcribe to
unsigned long lastMsg = 0;
// Initialize the SSL client library
// Arguments: EthernetClient, our trust anchors
void callback(char* topic, byte* payload, unsigned int length)
{
Serial.print("Message arrived [");
Serial.print(topic);
Serial.print("] ");
for (unsigned int i = 0; i < length; i++)
{
Serial.print((char)payload[i]);
}
Serial.println();
}
#define USE_PTR true
#if USE_PTR
WiFiClientSecure* ethClientSSL;
PubSubClient* client;
#else
WiFiClientSecure ethClientSSL;
PubSubClient client(AWS_IOT_ENDPOINT, 8883, callback, ethClientSSL);
#endif
#if USE_PTR
void reconnect()
{
// Loop until we're reconnected
while (!client->connected())
{
Serial.print("Attempting MQTTS connection to ");
Serial.print(AWS_IOT_ENDPOINT);
// Attempt to connect
if (client->connect(ID))
{
Serial.println("...connected");
// Once connected, publish an announcement...
String data = "Hello from MQTTClient_aws_iot on " + String(BOARD_NAME);
client->publish(TOPIC, data.c_str());
//Serial.println("Published connection message successfully!");
//Serial.print("Subcribed to: ");
//Serial.println(subTopic);
// ... and resubscribe
client->subscribe(subTopic);
// for loopback testing
client->subscribe(TOPIC);
}
else
{
Serial.print("failed, rc=");
Serial.print(client->state());
Serial.println(" try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
}
}
}
#else
void reconnect()
{
// Loop until we're reconnected
while (!client.connected())
{
Serial.print("Attempting MQTT connection to ");
Serial.print(AWS_IOT_ENDPOINT);
// Attempt to connect
if (client.connect(ID))
{
Serial.println("...connected");
// Once connected, publish an announcement...
String data = "Hello from MQTTClient_aws_iot on " + String(BOARD_NAME);
client.publish(TOPIC, data.c_str());
//Serial.println("Published connection message successfully!");
//Serial.print("Subcribed to: ");
//Serial.println(subTopic);
// ... and resubscribe
client.subscribe(subTopic);
// for loopback testing
client.subscribe(TOPIC);
}
else
{
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
}
}
}
#endif
// Not sure if WiFiClientSecure checks the validity date of the certificate.
// Setting clock just to be sure...
void setClock()
{
configTime(0, 0, "pool.ntp.org");
Serial.print(F("Waiting for NTP time sync: "));
time_t nowSecs = time(nullptr);
while (nowSecs < 8 * 3600 * 2)
{
delay(500);
Serial.print(F("."));
yield();
nowSecs = time(nullptr);
}
Serial.println();
struct tm timeinfo;
gmtime_r(&nowSecs, &timeinfo);
Serial.print(F("Current time: "));
Serial.print(asctime(&timeinfo));
}
void setup()
{
// Open serial communications and wait for port to open:
Serial.begin(115200);
while (!Serial);
// Using this if Serial debugging is not necessary or not using Serial port
//while (!Serial && (millis() < 3000));
Serial.print("\nStarting MQTTClient_aws_iot on " + String(ARDUINO_BOARD));
Serial.println(" with " + String(SHIELD_TYPE));
Serial.println(WEBSERVER_WT32_ETH01_VERSION);
// To be called before ETH.begin()
WT32_ETH01_onEvent();
//bool begin(uint8_t phy_addr=ETH_PHY_ADDR, int power=ETH_PHY_POWER, int mdc=ETH_PHY_MDC, int mdio=ETH_PHY_MDIO,
// eth_phy_type_t type=ETH_PHY_TYPE, eth_clock_mode_t clk_mode=ETH_CLK_MODE);
//ETH.begin(ETH_PHY_ADDR, ETH_PHY_POWER, ETH_PHY_MDC, ETH_PHY_MDIO, ETH_PHY_TYPE, ETH_CLK_MODE);
ETH.begin(ETH_PHY_ADDR, ETH_PHY_POWER);
// Static IP, leave without this line to get IP via DHCP
//bool config(IPAddress local_ip, IPAddress gateway, IPAddress subnet, IPAddress dns1 = 0, IPAddress dns2 = 0);
ETH.config(myIP, myGW, mySN, myDNS);
WT32_ETH01_waitForConnect();
setClock();
#if USE_PTR
ethClientSSL = new WiFiClientSecure;
if (ethClientSSL)
{
//ethClientSSL->setCACert(rootCACertificate);
ethClientSSL->setCACert(AWS_CERT_CA);
ethClientSSL->setCertificate(AWS_CERT_CRT);
ethClientSSL->setPrivateKey(AWS_CERT_PRIVATE);
}
client = new PubSubClient(AWS_IOT_ENDPOINT, 8883, callback, *ethClientSSL);
// Note - the default maximum packet size is 256 bytes. If the
// combined length of clientId, username and password exceed this use the
// following to increase the buffer size:
client->setBufferSize(2048);
#else
//ethClientSSL.setCACert(rootCACertificate);
ethClientSSL.setCACert(AWS_CERT_CA);
ethClientSSL.setCertificate(AWS_CERT_CRT);
ethClientSSL.setPrivateKey(AWS_CERT_PRIVATE);
// Note - the default maximum packet size is 256 bytes. If the
// combined length of clientId, username and password exceed this use the
// following to increase the buffer size:
client.setBufferSize(2048);
#endif
}
#define MQTT_PUBLISH_INTERVAL_MS 20000L
String data = "Hello from MQTTClient_aws_iot on " + String(BOARD_NAME);
const char *pubData = data.c_str();
#if USE_PTR
void loop()
{
static unsigned long now;
if (!client->connected())
{
reconnect();
}
// Sending Data
now = millis();
if (now - lastMsg > MQTT_PUBLISH_INTERVAL_MS)
{
lastMsg = now;
if (!client->publish(TOPIC, pubData))
{
Serial.println("Message failed to send.");
}
Serial.print("Message Send : " + String(TOPIC) + " => ");
Serial.println(data);
}
client->loop();
}
#else
void loop()
{
static unsigned long now;
if (!client.connected())
{
reconnect();
}
// Sending Data
now = millis();
if (now - lastMsg > MQTT_PUBLISH_INTERVAL_MS)
{
lastMsg = now;
if (!client.publish(TOPIC, pubData))
{
Serial.println("Message failed to send.");
}
Serial.print("Message Send : " + String(TOPIC) + " => ");
Serial.println(data);
}
client.loop();
}
#endif