-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathNetwork.h
439 lines (380 loc) · 13.4 KB
/
Network.h
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
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
#ifndef _NETWORK_H
#define _NETWORK_H
/*
***************************************************************************
** Program : network.h, part of DSMRloggerAPI
**
** Copyright (c) 2021 Willem Aandewiel / Martijn Hendriks
**
** TERMS OF USE: MIT License. See bottom of file.
***************************************************************************
*/
#include <ESPmDNS.h>
#include <Update.h>
#include <WiFiManager.h> // https://github.com/tzapu/WiFiManager
#include <HTTPClient.h>
#include "NetTypes.h"
WebServer httpServer(80);
NetServer ws_raw(82);
time_t tWifiLost = 0;
byte WifiReconnect = 0;
IPAddress staticIP, gateway, subnet, dns;
bool bFixedIP = false;
void LogFile(const char*, bool);
void P1Reboot();
void SwitchLED( byte mode, uint32_t color);
void startETH();
void startWiFi(const char* hostname, int timeOut);
void w5500_powerDown();
String MAC_Address();
String IP_Address();
void GetMacAddress(){
String _mac = MAC_Address();
strcpy( macStr, _mac.c_str() );
_mac.replace( ":","" );
strcpy( macID, _mac.c_str() );
USBPrint( "MacStr: " );USBPrintln( macStr ); //only at setup
// USBSerial.print( "MacID: " );USBSerial.println( macID );
}
/***===========================================================================================
POST MAC + IP
https://www.allphptricks.com/create-and-consume-simple-rest-api-in-php/
http://g2pc1.bu.edu/~qzpeng/manual/MySQL%20Commands.htm
**/
void PostMacIP() {
HTTPClient http;
http.begin(wifiClient, APIURL);
http.addHeader("Content-Type", "application/x-www-form-urlencoded");
String httpRequestData = "mac=" + String(macStr) + "&ip=" + IP_Address() + "&version=" + _VERSION_ONLY;
int httpResponseCode = http.POST(httpRequestData);
#ifdef DEBUG
DebugT(F("HTTP RequestData: "));Debugln(httpRequestData);
DebugT(F("HTTP Response code: "));Debugln(httpResponseCode);
#endif
http.end();
}
// #include "driver/adc.h"
void WifiOff(){
if ( WiFi.isConnected() ) WiFi.disconnect(true,true);
// adc_power_off();
btStop();
WiFi.mode(WIFI_OFF);
esp_wifi_stop();
esp_wifi_deinit();
WiFi.setSleep(true);
}
//int WifiDisconnect = 0;
bool bNoNetworkConn = false;
bool bEthUsage = false;
// Network event -> Ethernet is dominant
static void onNetworkEvent (WiFiEvent_t event) {
switch (event) {
#ifdef ETHERNET
//ETH
case ARDUINO_EVENT_ETH_START: //1
DebugTln("ETH Started");
// ETH.setHostname(_HOSTNAME); SDK 3.0 feature
break;
case ARDUINO_EVENT_ETH_CONNECTED: //3
DebugTln("\nETH Connected");
WifiOff();
netw_state = NW_ETH;
bEthUsage = true; //set only once
break;
case ARDUINO_EVENT_ETH_GOT_IP: //5
{
WiFiManager manageWiFi;
// if ( WiFi.isConnected() ) WiFi.disconnect();
WifiOff();
LogFile("ETH GOT IP", true);
netw_state = NW_ETH;
bEthUsage = true; //set only once
SwitchLED( LED_ON , LED_BLUE ); //Ethernet available = RGB LED Blue
// tLastConnect = 0;
break;
}
// case ARDUINO_EVENT_ETH_LOST_IP: //6 not available in SDK 2.x
// DebugTln("!!! ETH Lost IP");
// netw_connected = false;
// break;
case ARDUINO_EVENT_ETH_STOP: //2
DebugTln("!!! ETH Stopped");
case ARDUINO_EVENT_ETH_DISCONNECTED: //4
// if ( Update.isRunning() ) Update.abort();
if ( netw_state != NW_WIFI ) netw_state = NW_NONE;
SwitchLED( LED_ON , LED_RED );
LogFile("ETH Disconnected", true);
break;
#endif //ETHERNET
//WIFI
case ARDUINO_EVENT_WIFI_STA_CONNECTED: //4
sprintf(cMsg,"Connected to %s. Asking for IP address", WiFi.BSSIDstr().c_str());
LogFile(cMsg, true);
// tWifiLost = 0;
break;
case ARDUINO_EVENT_WIFI_STA_GOT_IP: //7
LogFile("Wifi Connected",true);
SwitchLED( LED_ON, LED_BLUE );
Debug (F("IP address: " )); Debug (WiFi.localIP());
Debug(" )\n\n");
WifiReconnect = 0;
if ( netw_state == NW_ETH ) WifiOff();
else netw_state = NW_WIFI;
bNoNetworkConn = false;
break;
case ARDUINO_EVENT_WIFI_STA_LOST_IP:
tWifiLost = millis();
if ( netw_state != NW_ETH ) netw_state = NW_NONE;
break;
case ARDUINO_EVENT_WIFI_STA_DISCONNECTED: //5
#ifdef ULTRA
if ( netw_state != NW_ETH ) SwitchLED( LED_ON, LED_RED );
#else
SwitchLED( LED_OFF, LED_BLUE );
#endif
break;
default:
sprintf(cMsg,"WiFi-event : %d | rssi: %d | channel : %i",event, WiFi.RSSI(), WiFi.channel());
LogFile(cMsg, true);
break;
}
}
//gets called when WiFiManager enters configuration mode
//===========================================================================================
void configModeCallback (WiFiManager *myWiFiManager)
{
DebugTln(F("Entered config mode\r"));
DebugTln(WiFi.softAPIP().toString());
//if you used auto generated SSID, print it
DebugTln(myWiFiManager->getConfigPortalSSID());
} // configModeCallback()
//===========================================================================================
void WifiWatchDog(){
#if not defined ETHERNET || defined ULTRA
//try to reconnect or reboot when wifi is down
if ( bEthUsage ) return; //leave when ethernet is prefered network
if ( WiFi.status() != WL_CONNECTED ){
if ( !bNoNetworkConn ) {
LogFile("Wifi connection lost",true); //log only once
tWifiLost = millis();
bNoNetworkConn = true;
}
if ( (millis() - tWifiLost) >= 20000 ) {
DebugTln("WifiLost > 20.000, disconnect");
WiFi.disconnect();
delay(100); //give it some time
WiFi.reconnect();
// Wifi.begin(WiFi.SSID().c_str(), WiFi.psk().c_str()); // better to disconnect and begin?
tWifiLost = millis();
WifiReconnect++;
DebugT("WifiReconnect: ");Debug(WifiReconnect);
return;
}
if (WifiReconnect >= 3) {
LogFile("Wifi -> Reboot because of timeout",true); //log only once
P1Reboot(); //after 3 x 20.000 millis
}
}
#endif
}
//===========================================================================================
void startWiFi(const char* hostname, int timeOut)
{
#if not defined ETHERNET || defined ULTRA
#ifdef ULTRA
//lets wait on ethernet first for 3.5sec and consume some time to charge the capacitors
uint8_t timeout = 0;
while ( (netw_state == NW_NONE) && (timeout++ < 35) ) {
delay(100);
}
// w5500_powerDown();
#endif
if ( netw_state != NW_NONE ) return;
//lower calibration power
esp_wifi_set_ps(WIFI_PS_MAX_MODEM);
WiFi.setHostname(hostname);
WiFi.enableIpV6();
// WiFi.setMinSecurity(WIFI_AUTH_WEP);
WiFi.setMinSecurity(WIFI_AUTH_WPA_PSK);
WiFi.setSortMethod(WIFI_CONNECT_AP_BY_SIGNAL); //to solve mesh issues
WiFi.setScanMethod(WIFI_ALL_CHANNEL_SCAN); //to solve mesh issues
if ( bFixedIP ) WiFi.config(staticIP, gateway, subnet, dns);
WiFiManager manageWiFi;
LogFile("Wifi Starting",true);
SwitchLED( LED_OFF, LED_BLUE );
manageWiFi.setConfigPortalBlocking(false);
manageWiFi.setDebugOutput(false);
manageWiFi.setShowStaticFields(true); // force show static ip fields
manageWiFi.setShowDnsFields(true); // force show dns field always
manageWiFi.setRemoveDuplicateAPs(false);
manageWiFi.setScanDispPerc(true); // display percentages instead of graphs for RSSI
// manageWiFi.setWiFiAutoReconnect(true); //buggy
//add custom html at inside <head> for all pages -> show pasessword function
manageWiFi.setClass("invert"); //dark theme
//--- set callback that gets called when connecting to previous WiFi fails, and enters Access Point mode
manageWiFi.setAPCallback(configModeCallback);
manageWiFi.setTimeout(timeOut); // in seconden ...
manageWiFi.autoConnect(_HOTSPOT);
//handle wifi webinterface timeout and connection (timeOut in sec)
uint16_t i = 0;
while ( (i++ < timeOut*10) && (netw_state == NW_NONE) ){
Debug("*");
delay(100);
manageWiFi.process();
SwitchLED(i%4?LED_ON:LED_OFF,LED_BLUE); //fast blinking
}
Debugln();
if ( netw_state == NW_NONE ) {
LogFile("WIFI: failed to connect and hit timeout",true);
P1Reboot(); //timeout
}
manageWiFi.stopWebPortal();
if ( netw_state == NW_ETH ) {
WifiOff();
delay(500);
}
SwitchLED( LED_ON, LED_BLUE );
#else
Debugln(F("NO WIFI SUPPORT"));
#endif //ifndef ETHERNET
} // startWiFi()
//===========================================================================================
void WaitOnNetwork()
{
while ( netw_state == NW_NONE ) { //endless wait for network connection
Debug(".");
delay(200);
}
Debugln("\nNetwork connected");
}
bool loadFixedIPConfig(const char *filename) {
File file = LittleFS.open(filename, "r");
if (!file) {
Debugln("Configuratiebestand niet gevonden.");
return false;
}
StaticJsonDocument<512> doc;
DeserializationError error = deserializeJson(doc, file);
if (error) {
Debugln("Fout bij het parsen van JSON-bestand.");
file.close();
return false;
}
staticIP.fromString(doc["static_ip"].as<const char *>());
gateway.fromString(doc["gateway"].as<const char *>());
subnet.fromString(doc["subnet"].as<const char *>());
dns.fromString(doc["dns"].as<const char *>());
file.close();
return true;
}
// validate fixed ip config
bool validateConfig() {
if (!staticIP || !gateway || !subnet || !dns) {
Serial.println("IP-instellingen zijn ongeldig.");
return false;
}
#ifdef DEBUG
Debugf("\n\nFixed IP values: ip[%s] gw[%s] sub[%s] dns[%s]\n\n",staticIP.toString(), gateway.toString(), subnet.toString(), dns.toString());
#endif
return true;
}
//===========================================================================================
void startNetwork()
{
WiFi.onEvent(onNetworkEvent);
if ( loadFixedIPConfig("/fixedip.json") ) bFixedIP = validateConfig();
startETH();
startWiFi(settingHostname, 240); // timeout 4 minuten
WaitOnNetwork();
GetMacAddress();
USBPrint("ip-adres: ");USBPrintln(IP_Address());
}
//===========================================================================================
void startTelnet()
{
TelnetStream.begin();
ws_raw.begin();
TelnetStream.flush();
DebugTln(F("Telnet server started .."));
} // startTelnet()
//=======================================================================
void startMDNS(const char *Hostname)
{
DebugTf("[1] mDNS setup as [%s.local]\r\n", Hostname);
if ( !MDNS.begin(Hostname) ) DebugTln(F("[3] Error setting up MDNS responder!\r\n"));
MDNS.addService("http", "tcp", 80);
} // startMDNS()
#endif
#ifdef ETHERNET
#include <WebServer_ESP32_SC_W5500.h>
/*
#define W5500_MR 0x002E // Mode Register adres
#define W5500_WRITE 0x04 // SPI Write Command (inclusief Block Select Bits)
// Zet de W5500 in Power-Down Mode
void w5500_powerDown() {
digitalWrite(CS_GPIO, LOW); // Selecteer W5500
SPI.transfer((W5500_MR >> 8) & 0xFF); // Hoog byte van adres
SPI.transfer(W5500_MR & 0xFF); // Laag byte van adres
SPI.transfer(W5500_WRITE); // Schrijfcommando met Block Select Bits
SPI.transfer(6<<3); // Bit 4 zetten (Power Down Mode)
digitalWrite(CS_GPIO, HIGH); // Deselecteer W5500
}
void w5500_wakeup() {
digitalWrite(CS_GPIO, LOW);
SPI.transfer((W5500_MR >> 8) & 0xFF);
SPI.transfer(W5500_MR & 0xFF);
SPI.transfer(W5500_WRITE);
SPI.transfer(0x00); // Alle bits op 0 → W5500 weer actief
digitalWrite(CS_GPIO, HIGH);
}
void disableSPI() {
SPI.end(); // Stopt de SPI-bus en verlaagt stroomverbruik
pinMode(CS_GPIO, OUTPUT);
digitalWrite(CS_GPIO, HIGH); // Voorkomt ongewenste communicatie
}
*/
void startETH(){
ETH.begin( MISO_GPIO, MOSI_GPIO, SCK_GPIO, CS_GPIO, INT_GPIO, SPI_CLOCK_MHZ, ETH_SPI_HOST );
if ( bFixedIP ) ETH.config(staticIP, gateway, subnet, dns);
}
#else
void startETH(){}
#endif //def ETHERNET
String IP_Address(){
#ifdef ETHERNET
if ( netw_state == NW_ETH ) return ETH.localIP().toString();
else return WiFi.localIP().toString();
#else
return WiFi.localIP().toString();
#endif
}
String MAC_Address(){
#ifdef ETHERNET
if ( netw_state == NW_ETH ) return ETH.macAddress();
else return WiFi.macAddress();
#else
return WiFi.macAddress();
#endif
}
/***************************************************************************
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to permit
* persons to whom the Software is furnished to do so, subject to the
* following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT
* OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR
* THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
***************************************************************************/