-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.cpp
328 lines (255 loc) · 9.71 KB
/
main.cpp
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
#include <Arduino.h>
#define DEBUG_ESP_CORE
// Used for light sleep
extern "C" {
#include "user_interface.h"
}
#include <ESP8266WiFi.h>
// MQTT
#include <PubSubClient.h>
WiFiClientSecure wifiClientSecure; // To use with mqtt and certificates
WiFiClient wifiClient; // To use with mqtt without certificates
PubSubClient mqttClient;
long connection_time = millis();
// Configuration
#include "WebConfigServer.h"
#include <ESP8266WebServer.h>
WebConfigServer config; // <- global configuration object
ESP8266WebServer server(80);
// FTP server
#include <ESP8266FtpServer.h>
#include <FS.h>
FtpServer ftpSrv;
// OTA Includes
#include "WrapperOTA.h"
// #include <display2.h>
WrapperOTA ota;
void networkRestart(void){
if(config.status() == CONFIG_LOADED){
// Config loaded correctly
if (config.network.ssid_name!=NULL && config.network.ssid_password!=NULL){
// Connect to Wi-Fi
WiFi.mode(WIFI_STA);
WiFi.begin(config.network.ssid_name, config.network.ssid_password);
Serial.print("Connecting to ");Serial.print(config.network.ssid_name);
while (WiFi.status() != WL_CONNECTED) {
delay(300);
Serial.print(".");
}
Serial.println("");
}
}
// Print Local IP Address
Serial.println(WiFi.localIP());
}
void enableServices(void){
Serial.println("--- Services: ");
if (config.services.OTA){
// ota.init(&display);
ota.init(&config);
Serial.println(" - OTA -> enabled");
} else Serial.println(" - OTA -> disabled");
if (config.services.ftp.enabled && config.services.ftp.user !=NULL && config.services.ftp.password !=NULL){
ftpSrv.begin(config.services.ftp.user,config.services.ftp.password);
Serial.println(" - FTP -> enabled");
} else Serial.println(" - FTP -> disabled");
if (config.services.deep_sleep.enabled){
// We will enable it on the loop function
// Serial.println(" - Deep sleep -> configured");
Serial.print(" - Deep sleep -> enabled for ");
Serial.print(config.services.deep_sleep.sleep_time);
Serial.print("secs after waitting ");
Serial.print(config.services.deep_sleep.sleep_delay);
Serial.println("secs. Choose sleep_time: 0 for infinite sleeping");
Serial.println(" Do not forget to connect D0 to RST pin to auto-wake up! Or I will sleep forever");
} else Serial.println(" - Deep sleep -> disabled");
if (config.services.light_sleep.enabled){
if (config.services.light_sleep.mode == "LIGHT_SLEEP_T")
wifi_set_sleep_type(LIGHT_SLEEP_T);
else if (config.services.light_sleep.mode == "NONE_SLEEP_T")
wifi_set_sleep_type(NONE_SLEEP_T);
else {
Serial.println(" - Light sleep -> mode not available");
return;
}
Serial.println(" - Light sleep -> enabled");
} else Serial.println(" - Light sleep -> disabled");
Serial.println("");
}
void callbackMQTT(char* topic, byte* payload, unsigned int length) {
Serial.print("Message arrived [");
Serial.print(topic);
Serial.print("] ");
char buff[length + 1];
for (int i = 0; i < length; i++) {
//Serial.print((char)payload[i]);
buff[i] = (char)payload[i];
}
buff[length] = '\0';
String message(buff);
Serial.print(message);
Serial.println();
/*
if (strcmp(topic, "/lamp") == 0) {
//Lamp color request:
if (message.equals("red")){
Serial.println("Turning lamp to red");
//colorWipe(strip.Color(255, 0, 0), 10);
}
else if (strcmp(buff, "blue") == 0){
Serial.println("Turning lamp to blue");
//colorWipe(strip.Color(0, 0, 255), 10);
} else if (message.equals("green")){
Serial.println("Turning lamp to green");
//colorWipe(strip.Color(0, 255, 0), 10);
}
//client.publish((char*)"/lamp",(char*)"color changed");
}
*/
Serial.print("Heap: "); Serial.println(ESP.getFreeHeap()); //Low heap can cause problems
///
}
void initMQTT(void){
if (config.mqtt.enable_certificates){
mqttClient.setClient(wifiClientSecure);
Serial.println("Configuring MQTT using certificates");
} else {
mqttClient.setClient(wifiClient);
Serial.println("Configuring MQTT without certificates");
}
mqttClient.setServer(config.mqtt.server.c_str(), config.mqtt.port);
mqttClient.setCallback(callbackMQTT);
if (config.mqtt.enable_certificates){
// Load certificate file:
// But you must convert it to .der
// openssl x509 -in ./certs/IoLed_controller/client.crt -out ./certs/IoLed_controller/cert.der -outform DER
File cert = SPIFFS.open(config.mqtt.cert_file, "r"); //replace cert.crt with your uploaded file name
if (!cert) Serial.println("Failed to open cert file ");
else Serial.println("Success to open cert file");
if (wifiClientSecure.loadCertificate(cert)) Serial.println("cert loaded");
else Serial.println("cert not loaded");
cert.close();
// Load private key:
// But you must convert it to .der
// openssl rsa -in ./certs/IoLed_controller/client.key -out ./certs/IoLed_controller/private.der -outform DER
File private_key = SPIFFS.open(config.mqtt.key_file, "r");
if (!private_key) Serial.println("Failed to open key file ");
else Serial.println("Success to open key file");
if (wifiClientSecure.loadPrivateKey(private_key)) Serial.println("key loaded");
else Serial.println("key not loaded");
private_key.close();
// Load CA file:
File ca = SPIFFS.open(config.mqtt.ca_file, "r");
if (!ca) Serial.println("Failed to open CA file ");
else Serial.println("Success to open CA file");
if (wifiClientSecure.loadCACert(ca)) Serial.println("CA loaded");
else Serial.println("CA not loaded");
ca.close();
}
}
void reconnectMQTT() {
// Loop until we're reconnected
int retries = 0;
int max_retries = 5;
bool mqtt_connected = false;
while (!mqttClient.connected() && (retries <= max_retries) ) {
Serial.print("Attempting MQTT connection...");
if (config.mqtt.enable_user_and_pass)
mqtt_connected = mqttClient.connect(config.mqtt.id_name.c_str(),
config.mqtt.user_name.c_str(),
config.mqtt.user_password.c_str());
else
mqtt_connected = mqttClient.connect(config.mqtt.id_name.c_str());
if (mqtt_connected) {
Serial.println("connected");
// Once connected, publish an announcement...
String base_topic_pub = "/" + config.mqtt.id_name + "/";
String topic_connected_pub = base_topic_pub + "connected";
// String msg_connected = config.mqtt.id_name + " connected";
String msg_connected ="true";
mqttClient.publish(topic_connected_pub.c_str(), msg_connected.c_str());
// ... and resubscribe
String base_topic_sub = base_topic_pub + "#";
mqttClient.subscribe(base_topic_sub.c_str());
long time_now = millis() - connection_time;
Serial.print("Time to setup and be connected: ");
Serial.print(time_now/1000);
Serial.println("s");
} else {
Serial.print("failed, rc=");
Serial.print(mqttClient.state());
Serial.print(" try again in 5 seconds: ");
Serial.print(retries);
Serial.print("/");
Serial.println(max_retries);
// Wait 5 seconds before retrying
delay(5000);
}
retries++;
}
}
void reconnect(void) {
//delay(1000);
Serial.print("--- Free heap: "); Serial.println(ESP.getFreeHeap());
config.begin();
networkRestart();
config.configureServer(&server);
// Enable services:
enableServices();
// Configure MQTT broker:
initMQTT();
reconnectMQTT();
}
void setup() {
Serial.begin(115200);
Serial.setDebugOutput(true);
reconnect();
// Print some info:
uint32_t realSize = ESP.getFlashChipRealSize();
uint32_t ideSize = ESP.getFlashChipSize();
FlashMode_t ideMode = ESP.getFlashChipMode();
Serial.printf("Flash real id: %08X\n", ESP.getFlashChipId());
Serial.printf("Flash real size: %u bytes\n\n", realSize);
Serial.printf("Flash ide size: %u bytes\n", ideSize);
Serial.printf("Flash ide speed: %u Hz\n", ESP.getFlashChipSpeed());
Serial.printf("Flash ide mode: %s\n", (ideMode == FM_QIO ? "QIO" : ideMode == FM_QOUT ? "QOUT" : ideMode == FM_DIO ? "DIO" : ideMode == FM_DOUT ? "DOUT" : "UNKNOWN"));
if (ideSize != realSize) {
Serial.println("Flash Chip configuration wrong!\n");
} else {
Serial.println("Flash Chip configuration ok.\n");
}
Serial.println("### Looping time\n");
}
void loop() {
// if (WiFi.status() != WL_CONNECTED) {
// config.begin();
// networkRestart();
// config.configureServer(&server);
// }
if (config.services.OTA) ota.handle();
if (config.services.ftp.enabled) ftpSrv.handleFTP();
server.handleClient();
// Handle mqtt reconnection:
if (!mqttClient.connected())
reconnectMQTT();
mqttClient.loop();
if (config.services.deep_sleep.enabled){
// long time_now = millis();
if (millis() > connection_time + (config.services.deep_sleep.sleep_delay*1000)){
Serial.println("Deep sleeping...");
if (config.services.deep_sleep.mode == "WAKE_RF_DEFAULT")
// sleep_time is in secs, but the function gets microsecs
ESP.deepSleep(config.services.deep_sleep.sleep_time * 1000000, WAKE_RF_DEFAULT);
else if (config.services.deep_sleep.mode == "WAKE_RF_DISABLED")
ESP.deepSleep(config.services.deep_sleep.sleep_time * 1000000, WAKE_RF_DISABLED);
else if (config.services.deep_sleep.mode == "WAKE_RFCAL")
ESP.deepSleep(config.services.deep_sleep.sleep_time * 1000000, WAKE_RFCAL);
else if (config.services.deep_sleep.mode == "WAKE_NO_RFCAL")
ESP.deepSleep(config.services.deep_sleep.sleep_time * 1000000, WAKE_NO_RFCAL);
else {
Serial.println(" - Deep sleep -> mode not available");
return;
}
}
}
}