-
Notifications
You must be signed in to change notification settings - Fork 0
/
espmote.ino
372 lines (294 loc) · 9.74 KB
/
espmote.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
#include <ESP8266WiFi.h>
#include <ESP8266mDNS.h>
#include "FS.h"
#include <WiFiUdp.h>
#include <ArduinoOTA.h>
extern "C" {
#include "user_interface.h"
}
#define GPIO_PIN 0
#define LED_PIN 2 //NodeMCU
//#define LED_PIN 13 //Sonoff
void changeLED() {
digitalWrite(LED_PIN, !digitalRead(LED_PIN));
}
#include <Ticker.h>
Ticker ticker;
Ticker tickerPing;
#define DEFAULT_NAME "newdevice" // Enter your device friendly name
#define DEFAULT_SSID "ssid" // Enter your network SSID
#define DEFAULT_KEY "" // Enter your network WPA key
#define DEFAULT_PASSWORD "moteconfig" // Enter network WPA key for AP (config) mode
#define DEFAULT_USE_STATIC_IP false // true or false enabled or disabled set static IP
#define DEFAULT_IP "192.168.0.50" // Enter your IP address
#define DEFAULT_DNS "192.168.0.1" // Enter your DNS
#define DEFAULT_GW "192.168.0.1" // Enter your gateway
#define DEFAULT_SUBNET "255.255.255.0" // Enter your subnet
#define SETTINGS_VERSION 170815
#define VERSION 170815
struct SettingsStr
{
unsigned int settings_version;
unsigned int Version;
byte IP[4];
byte Gateway[4];
byte Subnet[4];
byte DNS[4];
char WifiSSID[32];
char WifiKey[64];
char Name[32];
char Password[64];
boolean led;
int8_t chi[3]; //channel input
int8_t cho[3]; //channel output
} Settings;
#include <ESP8266WebServer.h>
ESP8266WebServer server (80);
boolean wifiSetup = false;
boolean tryToConnect = false;
/** Last time I tried to connect to WLAN */
long lastConnectTry = 0;
#include <DNSServer.h>
// Setup DNS, only used if the ESP has no valid WiFi config
const byte DNS_PORT = 53;
IPAddress apIP(192, 168, 4, 1);
DNSServer dnsServer;
#include <ESP8266HTTPClient.h>
HTTPClient http;
/********************************************************
/* Debug Print *
/********************************************************/
void dbg_printf ( const char *format, ... )
{
static char sbuf[1400]; // For debug lines
va_list varArgs; // For variable number of params
va_start ( varArgs, format ); // Prepare parameters
vsnprintf ( sbuf, sizeof ( sbuf ), format, varArgs ); // Format the message
va_end ( varArgs ); // End of using parameters
Serial.print ( sbuf );
}
WiFiEventHandler onConnectedHandler;
WiFiEventHandler onGotIPHandler;
WiFiEventHandler onDisconnectedHandler;
uint16_t lowestRAM = 0;
void setup()
{
lowestRAM = FreeMem();
pinMode(LED_PIN, OUTPUT);
digitalWrite(LED_PIN, HIGH);
ticker.attach(0.2, changeLED);
Serial.begin(115200);
Serial.println();
fileSystemCheck();
LoadSettings();
if (Settings.settings_version != SETTINGS_VERSION)
{
Serial.println(F("INIT : Incorrect settings version!"));
delay(1000);
//TODO fix instead reset
ResetFactory();
}
configureOutputs();
if (strcasecmp(Settings.WifiSSID, "ssid") == 0)
wifiSetup = true;
WiFi.persistent(false); // Do not use SDK storage of SSID/WPA parameters
char hostString[16] = {0};
sprintf(hostString, "ESP_%06X", ESP.getChipId());
ArduinoOTA.setHostname(hostString);
// setup ssid for AP Mode when needed
WiFi.softAP(hostString, Settings.Password);
dbg_printf ("[AP] Configured, Host: %s, Password: %s\n", hostString, Settings.Password);
// We start in STA mode
Serial.printf("Wi-Fi mode set to WIFI_STA %s\n", WiFi.mode(WIFI_STA) ? "" : "Failed!");
if (WifiConnect(3)) {
sendPingFlag();
tickerPing.attach(300, sendPingFlag);
ticker.detach();
WiFi.setAutoReconnect(false);
} else {
delay(2000);
WifiAPMode(true);
tryToConnect = true;
}
//enable MDNS
if (!MDNS.begin(hostString)) {
Serial.println("Error setting up MDNS responder!");
} else {
Serial.println("mDNS responder started");
MDNS.addService("espmote", "tcp", 80);
}
OTAConfigure();
// Start the server
setupServer();
// Turn led off and set interrupt
pinMode(GPIO_PIN, INPUT);
attachInterrupt(GPIO_PIN, buttonChange, CHANGE);
// ticker.detach();
digitalWrite(LED_PIN, HIGH);
// Start DNS, only used if the ESP has no valid WiFi config
// It will reply with it's own address on all DNS requests
// (captive portal concept)
if (wifiSetup) {
dnsServer.start(DNS_PORT, "*", apIP);
}
// WiFi.onEvent(eventWiFi);
onConnectedHandler = WiFi.onStationModeConnected(&onConnected);
onGotIPHandler = WiFi.onStationModeGotIP(&onGotIP);
onDisconnectedHandler = WiFi.onStationModeDisconnected(&onDisconnected);
}
int buttonState = 0; // current state of the button
int startPressed = 0; // the time button was pressed
int endPressed = 0; // the time button was released
int timeHold = 0; // the time button is hold
int timeReleased = 0; // the time button is released
void buttonChange() {
delay(250);
buttonState = digitalRead(GPIO_PIN);
if (buttonState == LOW) {
startPressed = millis();
Serial.println("Button pressed");
} else {
endPressed = millis();
timeHold = endPressed - startPressed;
Serial.println("Button released");
if (timeHold >= 3000) {
//change configuration portal
Serial.println("Button hold for three seconds or more");
bool isEnabled = ((WiFi.getMode() & WIFI_AP) != 0);
if (isEnabled) {
Serial.print("Disabling soft-AP ... ");
Serial.println(WiFi.enableAP(false) ? " OK" : " Failed!");
delay(500);
} else {
Serial.print("Enabling soft-AP ... ");
Serial.println(WiFi.enableAP(true) ? " OK" : " Failed!");
// Serial.print(WiFi.hostname().c_str());
// Serial.println(WiFi.softAP(WiFi.hostname().c_str(), "12345678") ? " Ready" : " Failed!");
delay(500);
}
} else {
Serial.println("Button hold for no mor than three seconds");
digitalWrite(LED_PIN, !digitalRead(LED_PIN));
}
}
}
void loop()
{
ArduinoOTA.handle();
if (tryToConnect)
{
// try to connect for setup wizard
if (millis() > (lastConnectTry + 15000) ) {
Serial.print("Loop connecting... ");
/* If WLAN disconnected and idle try to connect */
/* Don't set retry time too low as retry interfere the softAP operation */
lastConnectTry = millis();
if (WifiConnect(1)) {
WiFi.setAutoReconnect(false);
Serial.print("Loop conected ... ");
ticker.detach();
WifiAPMode(false);
tryToConnect = false;
SaveSettings();
}
}
}
backgroundtasks();
}
void backgroundtasks()
{
// process DNS, only used if the ESP has no valid WiFi config
if (wifiSetup) {
dnsServer.processNextRequest();
}
server.handleClient();
sendPing();
yield();
}
/********************************************************
/* Handle WiFi events *
/********************************************************/
void eventWiFi(WiFiEvent_t event) {
switch (event) {
case WIFI_EVENT_STAMODE_CONNECTED:
dbg_printf("[WiFi] %d, Connected\n", event);
break;
case WIFI_EVENT_STAMODE_DISCONNECTED:
dbg_printf("[WiFi] %d, Disconnected - Status %d, %s\n", event, WiFi.status(), connectionStatus( WiFi.status() ).c_str() );
break;
case WIFI_EVENT_STAMODE_AUTHMODE_CHANGE:
dbg_printf("[WiFi] %d, AuthMode Change\n", event);
break;
case WIFI_EVENT_STAMODE_GOT_IP:
sendPingFlag();
tickerPing.attach(300, sendPingFlag);
dbg_printf("[WiFi] %d, Got IP\n", event);
// setupOTA();
break;
case WIFI_EVENT_STAMODE_DHCP_TIMEOUT:
dbg_printf("[WiFi] %d, DHCP Timeout\n", event);
break;
case WIFI_EVENT_SOFTAPMODE_STACONNECTED:
dbg_printf("[AP] %d, Client Connected\n", event);
break;
case WIFI_EVENT_SOFTAPMODE_STADISCONNECTED:
dbg_printf("[AP] %d, Client Disconnected\n", event);
break;
case WIFI_EVENT_SOFTAPMODE_PROBEREQRECVED:
// dbg_printf("[AP] %d, Probe Request Recieved\n", event);
break;
}
}
/********************************************************
/* WiFi Connection Status *
/********************************************************/
String connectionStatus ( int which )
{
switch ( which )
{
case WL_CONNECTED:
return "Connected";
break;
case WL_NO_SSID_AVAIL:
return "Network not availible";
break;
case WL_CONNECT_FAILED:
return "Wrong password";
break;
case WL_IDLE_STATUS:
return "Idle status";
break;
case WL_DISCONNECTED:
return "Disconnected";
break;
default:
return "Unknown";
break;
}
}
void onConnected(const WiFiEventStationModeConnected& evt) {
Serial.print("---Station connected: ");
Serial.println(evt.ssid.c_str());
}
void onDisconnected(const WiFiEventStationModeDisconnected& evt) {
Serial.print("---Station disconnected: ");
Serial.print(evt.ssid.c_str());
Serial.print(" reason: ");
Serial.println(evt.reason);
// if (evt.reason == WIFI_DISCONNECT_REASON_AUTH_LEAVE) {
if (!tryToConnect) {
dbg_printf("tryToConnect\r\n");
tickerPing.detach();
ticker.attach(0.2, changeLED);
tryToConnect = true;
}
// }
}
void onGotIP(WiFiEventStationModeGotIP ipInfo) { // As soon WiFi is connected, start NTP Client
tryToConnect = false;
Serial.printf("Got IP: %s\r\n", ipInfo.ip.toString().c_str());
sendPingFlag();
tickerPing.attach(300, sendPingFlag);
ticker.detach();
digitalWrite(LED_PIN, HIGH);
}