This repository has been archived by the owner on Jan 29, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathTeensy_WiFiNINA_MQTT.ino
382 lines (313 loc) · 10.2 KB
/
Teensy_WiFiNINA_MQTT.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
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
/****************************************************************************************************************************
Teensy40_WiFiNINA_MQTT.ino
For Teensy boards using WiFiNINA Modules/Shields, using much less code to support boards with smaller memory
WiFiManager_NINA_WM_Lite is a library for the Mega, Teensy, SAM DUE, SAMD and STM32 boards
(https://github.com/khoih-prog/WiFiManager_NINA_Lite) to enable store Credentials in EEPROM/LittleFS for easy
configuration/reconfiguration and autoconnect/autoreconnect of WiFi and other services without Hardcoding.
Built by Khoi Hoang https://github.com/khoih-prog/WiFiManager_NINA_Lite
Licensed under MIT license
**********************************************************************************************************************************/
/****************************************************************************************************************************
You have to modify file ./libraries/Adafruit_MQTT_Library/Adafruit_MQTT.cpp as follows to avoid dtostrf error, if exists
#ifdef __cplusplus
extern "C" {
#endif
extern char* itoa(int value, char *string, int radix);
extern char* ltoa(long value, char *string, int radix);
extern char* utoa(unsigned value, char *string, int radix);
extern char* ultoa(unsigned long value, char *string, int radix);
#ifdef __cplusplus
} // extern "C"
#endif
//#if defined(ARDUINO_SAMD_ZERO) || defined(ARDUINO_SAMD_MKR1000) || defined(ARDUINO_ARCH_SAMD)
#if !( ESP32 || ESP8266 || defined(CORE_TEENSY) || defined(STM32F1) || defined(STM32F2) || defined(STM32F3) || defined(STM32F4) || defined(STM32F7) || \
( defined(ARDUINO_ARCH_RP2040) && !defined(ARDUINO_ARCH_MBED) ) || ARDUINO_ARCH_SEEED_SAMD || ( defined(SEEED_WIO_TERMINAL) || defined(SEEED_XIAO_M0) || \
defined(SEEED_FEMTO_M0) || defined(Wio_Lite_MG126) || defined(WIO_GPS_BOARD) || defined(SEEEDUINO_ZERO) || defined(SEEEDUINO_LORAWAN) || defined(WIO_LTE_CAT) || \
defined(SEEED_GROVE_UI_WIRELESS) ) )
static char *dtostrf(double val, signed char width, unsigned char prec, char *sout)
{
char fmt[20];
sprintf(fmt, "%%%d.%df", width, prec);
sprintf(sout, fmt, val);
return sout;
}
#endif
*****************************************************************************************************************************/
#include "defines.h"
#include "Credentials.h"
#include "dynamicParams.h"
#define LOCAL_DEBUG true //false
#include "Adafruit_MQTT.h" //https://github.com/adafruit/Adafruit_MQTT_Library
#include "Adafruit_MQTT_Client.h" //https://github.com/adafruit/Adafruit_MQTT_Library
// Create a WiFiClient class to connect to the MQTT server
WiFiClient *client = NULL;
Adafruit_MQTT_Client *mqtt = NULL;
Adafruit_MQTT_Publish *Temperature = NULL;
Adafruit_MQTT_Subscribe *LED_Control = NULL;
// You have to get from a sensor. Here is just an example
uint32_t measuredTemp = 5;
WiFiManager_NINA_Lite* WiFiManager_NINA;
void heartBeatPrint(void)
{
static int num = 1;
if (WiFi.status() == WL_CONNECTED)
Serial.print("H"); // H means connected to WiFi
else
{
if (WiFiManager_NINA->isConfigMode())
Serial.print("C"); // C means in Config Mode
else
Serial.print("F"); // F means not connected to WiFi
}
if (num == 40)
{
Serial.println();
num = 1;
}
else if (num++ % 5 == 0)
{
Serial.print(" ");
}
}
void publishMQTT(void)
{
MQTT_connect();
if (Temperature->publish(measuredTemp))
{
//Serial.println(F("Failed to send value to Temperature feed!"));
Serial.print("T"); // T means publishing OK
}
else
{
//Serial.println(F("Value to Temperature feed sucessfully sent!"));
Serial.print("F"); // F means publishing failure
}
}
void subscribeMQTT(void)
{
Adafruit_MQTT_Subscribe *subscription;
MQTT_connect();
while ((subscription = mqtt->readSubscription(5000)))
{
if (subscription == LED_Control)
{
Serial.print(F("\nGot: "));
Serial.println((char *)LED_Control->lastread);
if (!strcmp((char*) LED_Control->lastread, "ON"))
{
digitalWrite(LED_PIN, HIGH);
}
else
{
digitalWrite(LED_PIN, LOW);
}
}
}
}
void check_status()
{
static unsigned long checkstatus_timeout = 0;
//KH
#define HEARTBEAT_INTERVAL 5000L
// Print WiFi hearbeat, Publish MQTT Topic every HEARTBEAT_INTERVAL (5) seconds.
if ((millis() > checkstatus_timeout) || (checkstatus_timeout == 0))
{
if (WiFi.status() == WL_CONNECTED)
{
// MQTT related jobs
publishMQTT();
subscribeMQTT();
}
heartBeatPrint();
checkstatus_timeout = millis() + HEARTBEAT_INTERVAL;
}
}
void deleteOldInstances(void)
{
// Delete previous instances
if (mqtt)
{
delete mqtt;
mqtt = NULL;
Serial.println("Deleting old MQTT object");
}
if (Temperature)
{
delete Temperature;
Temperature = NULL;
Serial.println("Deleting old Temperature object");
}
}
#define USE_GLOBAL_TOPIC true
#if USE_GLOBAL_TOPIC
String completePubTopic;
String completeSubTopic;
#endif
void createNewInstances(void)
{
if (!client)
{
client = new WiFiClient;
if (client)
{
Serial.println("\nCreating new WiFi client object OK");
}
else
Serial.println("\nCreating new WiFi client object failed");
}
// Create new instances from new data
if (!mqtt)
{
// Setup the MQTT client class by passing in the WiFi client and MQTT server and login details.
mqtt = new Adafruit_MQTT_Client(client, AIO_SERVER, atoi(AIO_SERVERPORT), AIO_USERNAME, AIO_KEY);
if (mqtt)
{
Serial.println("Creating new MQTT object OK");
Serial.println(String("AIO_SERVER = ") + AIO_SERVER + ", AIO_SERVERPORT = " + AIO_SERVERPORT);
Serial.println(String("AIO_USERNAME = ") + AIO_USERNAME + ", AIO_KEY = " + AIO_KEY);
}
else
Serial.println("Creating new MQTT object failed");
}
if (!Temperature)
{
#if USE_GLOBAL_TOPIC
completePubTopic = String(AIO_USERNAME) + String(AIO_PUB_TOPIC);
#else
// Must be static or global
static String completePubTopic = String(AIO_USERNAME) + String(AIO_PUB_TOPIC);
#endif
Temperature = new Adafruit_MQTT_Publish(mqtt, completePubTopic.c_str());
Serial.println(String("Creating new MQTT_Pub_Topic, Temperature = ") + completePubTopic);
if (Temperature)
{
Serial.println("Creating new Temperature object OK");
Serial.println(String("Temperature MQTT_Pub_Topic = ") + completePubTopic);
}
else
Serial.println("Creating new Temperature object failed");
}
if (!LED_Control)
{
#if USE_GLOBAL_TOPIC
completeSubTopic = String(AIO_USERNAME) + String(AIO_SUB_TOPIC);
#else
// Must be static or global
static String completeSubTopic = String(AIO_USERNAME) + String(AIO_SUB_TOPIC);
#endif
LED_Control = new Adafruit_MQTT_Subscribe(mqtt, completeSubTopic.c_str());
Serial.println(String("Creating new AIO_SUB_TOPIC, LED_Control = ") + completeSubTopic);
if (LED_Control)
{
Serial.println("Creating new LED_Control object OK");
Serial.println(String("LED_Control AIO_SUB_TOPIC = ") + completeSubTopic);
mqtt->subscribe(LED_Control);
}
else
Serial.println("Creating new LED_Control object failed");
}
}
void MQTT_connect()
{
int8_t ret;
createNewInstances();
// Return if already connected
if (mqtt->connected())
{
return;
}
#if LOCAL_DEBUG
Serial.println("\nConnecting to WiFi MQTT (3 attempts)...");
#endif
uint8_t attempt = 3;
while ( (ret = mqtt->connect()) )
{
// connect will return 0 for connected
Serial.println(mqtt->connectErrorString(ret));
#if LOCAL_DEBUG
Serial.println("Another attemtpt to connect to MQTT in 5 seconds...");
#endif
mqtt->disconnect();
delay(5000); // wait 5 seconds
attempt--;
if (attempt == 0)
{
Serial.println("WiFi MQTT connection failed. Continuing with program...");
return;
}
}
#if LOCAL_DEBUG
Serial.println("WiFi MQTT connection successful!");
#endif
}
#if USING_CUSTOMS_STYLE
const char NewCustomsStyle[] /*PROGMEM*/ = "<style>div,input{padding:5px;font-size:1em;}input{width:95%;}body{text-align: center;}\
button{background-color:blue;color:white;line-height:2.4rem;font-size:1.2rem;width:100%;}fieldset{border-radius:0.3rem;margin:0px;}</style>";
#endif
void setup()
{
// Debug console
Serial.begin(115200);
while (!Serial && millis() < 5000);
pinMode(LED_PIN, OUTPUT);
delay(200);
Serial.print(F("\nStarting Teensy_WiFiNINA_MQTT on ")); Serial.println(BOARD_TYPE);
Serial.println(WIFIMULTI_GENERIC_VERSION);
Serial.println(WIFIMANAGER_NINA_LITE_VERSION);
WiFiManager_NINA = new WiFiManager_NINA_Lite();
// Optional to change default AP IP(192.168.4.1) and channel(10)
//WiFiManager_NINA->setConfigPortalIP(IPAddress(192, 168, 120, 1));
WiFiManager_NINA->setConfigPortalChannel(0);
#if USING_CUSTOMS_STYLE
WiFiManager_NINA->setCustomsStyle(NewCustomsStyle);
#endif
#if USING_CUSTOMS_HEAD_ELEMENT
WiFiManager_NINA->setCustomsHeadElement("<style>html{filter: invert(10%);}</style>");
#endif
#if USING_CORS_FEATURE
WiFiManager_NINA->setCORSHeader("Your Access-Control-Allow-Origin");
#endif
// Set customized DHCP HostName
WiFiManager_NINA->begin(HOST_NAME);
//Or use default Hostname "SAMD-WiFiNINA-XXXXXX"
//WiFiManager_NINA->begin();
}
#if USE_DYNAMIC_PARAMETERS
void displayCredentials()
{
Serial.println(F("\nYour stored Credentials :"));
for (uint16_t i = 0; i < NUM_MENU_ITEMS; i++)
{
Serial.print(myMenuItems[i].displayName);
Serial.print(F(" = "));
Serial.println(myMenuItems[i].pdata);
}
}
void displayCredentialsInLoop()
{
static bool displayedCredentials = false;
if (!displayedCredentials)
{
for (int i = 0; i < NUM_MENU_ITEMS; i++)
{
if (!strlen(myMenuItems[i].pdata))
{
break;
}
if ( i == (NUM_MENU_ITEMS - 1) )
{
displayedCredentials = true;
displayCredentials();
}
}
}
}
#endif
void loop()
{
WiFiManager_NINA->run();
check_status();
#if USE_DYNAMIC_PARAMETERS
displayCredentialsInLoop();
#endif
}