-
Notifications
You must be signed in to change notification settings - Fork 140
/
IotWebConf06MqttApp.ino
273 lines (235 loc) · 7.83 KB
/
IotWebConf06MqttApp.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
/**
* IotWebConf06MqttApp.ino -- IotWebConf is an ESP8266/ESP32
* non blocking WiFi/AP web configuration library for Arduino.
* https://github.com/prampec/IotWebConf
*
* Copyright (C) 2020 Balazs Kelemen <prampec+arduino@gmail.com>
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
/**
* Example: MQTT Demo Application
* Description:
* All IotWebConf specific aspects of this example are described in
* previous examples, so please get familiar with IotWebConf before
* starting this example. So nothing new will be explained here,
* but a complete demo application will be built.
* It is also expected from the reader to have a basic knowledge over
* MQTT to understand this code.
*
* This example starts an MQTT client with the configured
* connection settings.
* Will post the status changes of the D2 pin in channel "test/status".
* Receives messages appears in channel "test/action", and writes them to serial.
* This example also provides the firmware update option.
* (See previous examples for more details!)
*
* Software setup for this example:
* This example utilizes Joel Gaehwiler's MQTT library.
* https://github.com/256dpi/arduino-mqtt
*
* Hardware setup for this example:
* - An LED is attached to LED_BUILTIN pin with setup On=LOW.
* - [Optional] A push button is attached to pin D2, the other leg of the
* button should be attached to GND.
*/
#include <MQTT.h>
#include <IotWebConf.h>
#include <IotWebConfUsing.h> // This loads aliases for easier class names.
// -- Initial name of the Thing. Used e.g. as SSID of the own Access Point.
const char thingName[] = "testThing";
// -- Initial password to connect to the Thing, when it creates an own Access Point.
const char wifiInitialApPassword[] = "smrtTHNG8266";
#define STRING_LEN 128
// -- Configuration specific key. The value should be modified if config structure was changed.
#define CONFIG_VERSION "mqt1"
// -- When CONFIG_PIN is pulled to ground on startup, the Thing will use the initial
// password to buld an AP. (E.g. in case of lost password)
#define CONFIG_PIN D2
// -- Status indicator pin.
// First it will light up (kept LOW), on Wifi connection it will blink,
// when connected to the Wifi it will turn off (kept HIGH).
#define STATUS_PIN LED_BUILTIN
// -- Method declarations.
void handleRoot();
void mqttMessageReceived(String &topic, String &payload);
bool connectMqtt();
bool connectMqttOptions();
// -- Callback methods.
void wifiConnected();
void configSaved();
bool formValidator(iotwebconf::WebRequestWrapper* webRequestWrapper);
DNSServer dnsServer;
WebServer server(80);
WiFiClient net;
MQTTClient mqttClient;
char mqttServerValue[STRING_LEN];
char mqttUserNameValue[STRING_LEN];
char mqttUserPasswordValue[STRING_LEN];
IotWebConf iotWebConf(thingName, &dnsServer, &server, wifiInitialApPassword, CONFIG_VERSION);
// -- You can also use namespace formats e.g.: iotwebconf::ParameterGroup
IotWebConfParameterGroup mqttGroup = IotWebConfParameterGroup("mqtt", "MQTT configuration");
IotWebConfTextParameter mqttServerParam = IotWebConfTextParameter("MQTT server", "mqttServer", mqttServerValue, STRING_LEN);
IotWebConfTextParameter mqttUserNameParam = IotWebConfTextParameter("MQTT user", "mqttUser", mqttUserNameValue, STRING_LEN);
IotWebConfPasswordParameter mqttUserPasswordParam = IotWebConfPasswordParameter("MQTT password", "mqttPass", mqttUserPasswordValue, STRING_LEN);
bool needMqttConnect = false;
bool needReset = false;
int pinState = HIGH;
unsigned long lastReport = 0;
unsigned long lastMqttConnectionAttempt = 0;
void setup()
{
Serial.begin(115200);
Serial.println();
Serial.println("Starting up...");
mqttGroup.addItem(&mqttServerParam);
mqttGroup.addItem(&mqttUserNameParam);
mqttGroup.addItem(&mqttUserPasswordParam);
iotWebConf.setStatusPin(STATUS_PIN);
iotWebConf.setConfigPin(CONFIG_PIN);
iotWebConf.addParameterGroup(&mqttGroup);
iotWebConf.setConfigSavedCallback(&configSaved);
iotWebConf.setFormValidator(&formValidator);
iotWebConf.setWifiConnectionCallback(&wifiConnected);
// -- Initializing the configuration.
bool validConfig = iotWebConf.init();
if (!validConfig)
{
mqttServerValue[0] = '\0';
mqttUserNameValue[0] = '\0';
mqttUserPasswordValue[0] = '\0';
}
// -- Set up required URL handlers on the web server.
server.on("/", handleRoot);
server.on("/config", []{ iotWebConf.handleConfig(); });
server.onNotFound([](){ iotWebConf.handleNotFound(); });
mqttClient.begin(mqttServerValue, net);
mqttClient.onMessage(mqttMessageReceived);
Serial.println("Ready.");
}
void loop()
{
// -- doLoop should be called as frequently as possible.
iotWebConf.doLoop();
mqttClient.loop();
if (needMqttConnect)
{
if (connectMqtt())
{
needMqttConnect = false;
}
}
else if ((iotWebConf.getState() == iotwebconf::OnLine) && (!mqttClient .connected()))
{
Serial.println("MQTT reconnect");
connectMqtt();
}
if (needReset)
{
Serial.println("Rebooting after 1 second.");
iotWebConf.delay(1000);
ESP.restart();
}
unsigned long now = millis();
if ((500 < now - lastReport) && (pinState != digitalRead(CONFIG_PIN)))
{
pinState = 1 - pinState; // invert pin state as it is changed
lastReport = now;
Serial.print("Sending on MQTT channel 'test/status' :");
Serial.println(pinState == LOW ? "ON" : "OFF");
mqttClient.publish("test/status", pinState == LOW ? "ON" : "OFF");
}
}
/**
* Handle web requests to "/" path.
*/
void handleRoot()
{
// -- Let IotWebConf test and handle captive portal requests.
if (iotWebConf.handleCaptivePortal())
{
// -- Captive portal request were already served.
return;
}
String s = "<!DOCTYPE html><html lang=\"en\"><head><meta name=\"viewport\" content=\"width=device-width, initial-scale=1, user-scalable=no\"/>";
s += "<title>IotWebConf 06 MQTT App</title></head><body>MQTT App demo";
s += "<ul>";
s += "<li>MQTT server: ";
s += mqttServerValue;
s += "</li>";
s += "</ul>";
s += "Go to <a href='config'>configure page</a> to change values.";
s += "</body></html>\n";
server.send(200, "text/html", s);
}
void wifiConnected()
{
needMqttConnect = true;
}
void configSaved()
{
Serial.println("Configuration was updated.");
needReset = true;
}
bool formValidator(iotwebconf::WebRequestWrapper* webRequestWrapper)
{
Serial.println("Validating form.");
bool valid = true;
int l = webRequestWrapper->arg(mqttServerParam.getId()).length();
if (l < 3)
{
mqttServerParam.errorMessage = "Please provide at least 3 characters!";
valid = false;
}
return valid;
}
bool connectMqtt() {
unsigned long now = millis();
if (1000 > now - lastMqttConnectionAttempt)
{
// Do not repeat within 1 sec.
return false;
}
Serial.println("Connecting to MQTT server...");
if (!connectMqttOptions()) {
lastMqttConnectionAttempt = now;
return false;
}
Serial.println("Connected!");
mqttClient.subscribe("test/action");
return true;
}
/*
// -- This is an alternative MQTT connection method.
bool connectMqtt() {
Serial.println("Connecting to MQTT server...");
while (!connectMqttOptions()) {
iotWebConf.delay(1000);
}
Serial.println("Connected!");
mqttClient.subscribe("test/action");
return true;
}
*/
bool connectMqttOptions()
{
bool result;
if (mqttUserPasswordValue[0] != '\0')
{
result = mqttClient.connect(iotWebConf.getThingName(), mqttUserNameValue, mqttUserPasswordValue);
}
else if (mqttUserNameValue[0] != '\0')
{
result = mqttClient.connect(iotWebConf.getThingName(), mqttUserNameValue);
}
else
{
result = mqttClient.connect(iotWebConf.getThingName());
}
return result;
}
void mqttMessageReceived(String &topic, String &payload)
{
Serial.println("Incoming: " + topic + " - " + payload);
}