-
Notifications
You must be signed in to change notification settings - Fork 8
/
wifi.h
375 lines (313 loc) · 14.3 KB
/
wifi.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
#ifndef __WIFI_H
#define __WIFI_H
#include "Settings.h"
#include "Debug.h"
#include "Globals.h"
#ifdef ESP8266
#include <ESP8266WiFi.h>
//#include <Pinger.h> // von url=https://www.technologytourist.com
#endif
String SSID = ""; // bestes WLan
uint8_t WIFIConnect = 5;//not connect 0 else 5
//Pinger pinger;
//IPAddress ROUTER = IPAddress(192,168,1,1);
// Prototypes
time_t getNow ();
boolean setupWifi ();
boolean checkWifi();
String findWifi () {
//----------------------------------------------------------------------------------------------------------------------
String ssid;
int32_t rssi;
uint8_t encryptionType;
uint8_t* bssid;
int32_t channel;
bool hidden;
int scanResult;
String best_ssid = "";
int32_t best_rssi = -100;
DEBUG_OUT.println(F("[WiFi] Starting scan AP's ..."));
scanResult = WiFi.scanNetworks(/*async=*/false, /*hidden=*/true);
if (scanResult == 0) {
DEBUG_OUT.printf("[WiFi] NO WLans\r\n");
} else if (scanResult > 0) {
DEBUG_OUT.printf(PSTR("[WiFi] %d WLan found:\r\n"), scanResult);
// Print unsorted scan results
for (int8_t i = 0; i < scanResult; i++) {
WiFi.getNetworkInfo(i, ssid, encryptionType, rssi, bssid, channel, hidden);
DEBUG_OUT.printf(PSTR(" %02d: [CH %02d] [%02X:%02X:%02X:%02X:%02X:%02X] %ddBm %c %c %s"),
i,
channel,
bssid[0], bssid[1], bssid[2],
bssid[3], bssid[4], bssid[5],
rssi,
(encryptionType == ENC_TYPE_NONE) ? ' ' : '*',
hidden ? 'H' : 'V',
ssid.c_str());
DEBUG_OUT.println("");
delay(1);
boolean check;
#ifdef SSID_PREFIX1
check = ssid.substring(0,strlen(SSID_PREFIX1)).equals(SSID_PREFIX1);
#else
check = true;
#endif
#ifdef SSID_PREFIX2
check = check || ssid.substring(0,strlen(SSID_PREFIX2)).equals(SSID_PREFIX2);
#endif
if (check) {
if (rssi > best_rssi) {
best_rssi = rssi;
best_ssid = ssid;
}
}
}
} else {
DEBUG_OUT.printf("[WiFi] scan error %d\r\n", scanResult);
}
if (! best_ssid.equals("")) {
SSID = best_ssid;
DEBUG_OUT.printf ("[WiFi] best radio: %s\r\n", SSID.c_str());
return SSID;
}
else {
SSID = "";
return "";
}
}//----------------------------------------------------------------------------------------------------------------------
void IP2string (IPAddress IP, char * buf) {
//----------------------------------------------------------------------------------------------------------------------
sprintf (buf, "%d.%d.%d.%d", IP[0], IP[1], IP[2], IP[3]);
}//----------------------------------------------------------------------------------------------------------------------
//todo clean up imho useless //String PrintMyIP (void){
//String PrintMyIP (void){
////----------------------------------------------------------------------------------------------------------------------
// char buffer[30];
// IP2string (WiFi.localIP(), buffer);
//// return (String)buffer;
//}//---------------------------------------------------------------------------------------------------------------------
void connectWifi() {
//----------------------------------------------------------------------------------------------------------------------
//if (SSID.equals(""))
String s = findWifi();
if (!SSID.equals("")) {
//todo DEBUG_OUT.print("[WiFi] try to connect to "); DEBUG_OUT.println(SSID);
DEBUG_OUT.printf("[WiFi] try to connect to %s\r\n",SSID.c_str());
//while (WiFi.status() != WL_CONNECTED) {
WiFi.begin (SSID, SSID_PASSWORD);
int versuche = 20;
while (WiFi.status() != WL_CONNECTED && versuche > 0) {
delay(1000); //toe 1000
versuche--;
DEBUG_OUT.printf(" %i",versuche);
}
//}
if (WiFi.status() == WL_CONNECTED) {
IP2string (WiFi.localIP(), IpStr);
//todo String out = "[WiFi] connected; my IP:" + String (buffer);
// DEBUG_OUT.println (out);
DEBUG_OUT.printf("\r\n[WiFi] connected; my IP: %s\r\n", IpStr);
}
else
DEBUG_OUT.printf("\r\n[WiFi] NO connection with SSID %s\r\n",SSID.c_str());
}
else SSID=""; //toe
}//---------------------------------------------------------------------------------------------------------------------
boolean setupWifi () {
//----------------------------------------------------------------------------------------------------------------------
int count=WIFIConnect;//5;
while (count-- && (WiFi.status() != WL_CONNECTED))
{
connectWifi();
if (WiFi.status() == WL_CONNECTED) DEBUG_OUT.printf("[WiFi] Connected:%i\r\n",WiFi.status());
else DEBUG_OUT.printf("[WiFi] Not Connected:%i\r\n",WiFi.status());
}
if (WiFi.status()== WL_CONNECTED) return true;
else return false;
}//---------------------------------------------------------------------------------------------------------------------
boolean checkWifi() {
//----------------------------------------------------------------------------------------------------------------------
if (WiFi.status()== WL_CONNECTED) return true;
else {
DEBUG_OUT.println(F("[WiFi] CheckWifi: not Connected"));
//toe setupWifi();
return false;
}
}//----------------------------------------------------------------------------------------------------------------------
// ################ Clock #################
#include <WiFiUdp.h>
#include <TimeLib.h>
IPAddress timeServer;
unsigned int localPort = 8888;
const int NTP_PACKET_SIZE= 48; // NTP time stamp is in the first 48 bytes of the message
byte packetBuf[NTP_PACKET_SIZE]; // Buffer to hold incoming and outgoing packets
const int timeZone = 2; // Central European Time = +1
long SYNCINTERVALL = 0;
WiFiUDP Udp; // A UDP instance to let us send and receive packets over UDP
// prototypes
time_t getNtpTime ();
void sendNTPpacket (IPAddress &address);
time_t getNow ();
char* getDateTimeStr (time_t no = getNow());
time_t offsetDayLightSaving (uint32_t local_t);
bool isDayofDaylightChange (time_t local_t);
void _setSyncInterval (long intervall) {
//----------------------------------------------------------------------------------------------------------------------
SYNCINTERVALL = intervall;
setSyncInterval (intervall);
}//----------------------------------------------------------------------------------------------------------------------
void setupClock() {
//----------------------------------------------------------------------------------------------------------------------
DEBUG_OUT.println ("[CLOCK] Setup ");
WiFi.hostByName (TIMESERVER_NAME,timeServer); // at this point the function works
Udp.begin(localPort);
getNtpTime();
setSyncProvider (getNtpTime);
while(timeStatus()== timeNotSet)
delay(1); //
_setSyncInterval (SECS_PER_DAY / 2); // Set seconds between re-sync
//lastClock = now();
//Serial.print("[NTP] get time from NTP server ");
getNow();
getNow(); // todo : it gets some time year 2036 ??????????? get it again, might be useful?
//char buf[20];
DEBUG_OUT.print ("[NTP] get time from NTP server ");
DEBUG_OUT.print (timeServer);
//sprintf (buf, ": %02d:%02d:%02d", hour(no), minute(no), second(no));
DEBUG_OUT.print (": got ");
DEBUG_OUT.println (getDateTimeStr());
}//---------------------------------------------------------------------------------------------------------------------
//*-------- NTP code ----------*/
time_t getNtpTime() {
//----------------------------------------------------------------------------------------------------------------------
sendNTPpacket(timeServer); // send an NTP packet to a time server
//uint32_t beginWait = millis();
//while (millis() - beginWait < 1500) {
int versuch = 0;
while (versuch < 5) {
int wait = 150; // results in max 1500 ms waitTime
while (wait--) {
int size = Udp.parsePacket();
if (size >= NTP_PACKET_SIZE) {
//Serial.println("Receive NTP Response");
Udp.read(packetBuf, NTP_PACKET_SIZE); // read packet into the buffer
unsigned long secsSince1900;
// convert four bytes starting at location 40 to a long integer
secsSince1900 = (unsigned long)packetBuf[40] << 24;
secsSince1900 |= (unsigned long)packetBuf[41] << 16;
secsSince1900 |= (unsigned long)packetBuf[42] << 8;
secsSince1900 |= (unsigned long)packetBuf[43];
// time_t now = secsSince1900 - 2208988800UL + timeZone * SECS_PER_HOUR;
time_t utc = secsSince1900 - 2208988800UL;
time_t now = utc + (timeZone +offsetDayLightSaving(utc)) * SECS_PER_HOUR;
if (isDayofDaylightChange (utc) && hour(utc) <= 4)
_setSyncInterval (SECS_PER_HOUR);
else
_setSyncInterval (SECS_PER_DAY / 2);
return now;
}
else
delay(10);
}
versuch++;
}
return 0;
}//---------------------------------------------------------------------------------------------------------------------
// send an NTP request to the time server at the given address
void sendNTPpacket(IPAddress& address) {
//----------------------------------------------------------------------------------------------------------------------
memset(packetBuf, 0, NTP_PACKET_SIZE); // set all bytes in the buffer to 0
// Initialize values needed to form NTP request
packetBuf[0] = B11100011; // LI, Version, Mode
packetBuf[1] = 0; // Stratum
packetBuf[2] = 6; // Max Interval between messages in seconds
packetBuf[3] = 0xEC; // Clock Precision
// bytes 4 - 11 are for Root Delay and Dispersion and were set to 0 by memset
packetBuf[12] = 49; // four-byte reference ID identifying
packetBuf[13] = 0x4E;
packetBuf[14] = 49;
packetBuf[15] = 52;
// send the packet requesting a timestamp:
Udp.beginPacket(address, 123); //NTP requests are to port 123
Udp.write(packetBuf,NTP_PACKET_SIZE);
Udp.endPacket();
}//---------------------------------------------------------------------------------------------------------------------
int getTimeTrials = 0;
bool isValidDateTime (time_t no) {
//----------------------------------------------------------------------------------------------------------------------
return (year(no) > 2020 && year(no) < 2038);
}//----------------------------------------------------------------------------------------------------------------------
bool isDayofDaylightChange (time_t local_t) {
//----------------------------------------------------------------------------------------------------------------------
int jahr = year (local_t);
int monat = month (local_t);
int tag = day (local_t);
bool ret = ( (monat ==3 && tag == (31 - (5 * jahr /4 + 4) % 7)) ||
(monat==10 && tag == (31 - (5 * jahr /4 + 1) % 7)));
//DEBUG_OUT.print ("isDayofDaylightChange="); DEBUG_OUT.println (ret);
return ret;
}//----------------------------------------------------------------------------------------------------------------------
// calculates the daylight saving time for middle Europe. Input: Unixtime in UTC (!)
// übernommen von Jurs, see : https://forum.arduino.cc/index.php?topic=172044.msg1278536#msg1278536
time_t offsetDayLightSaving (uint32_t local_t) {
//----------------------------------------------------------------------------------------------------------------------
int monat = month (local_t);
if (monat < 3 || monat > 10) return 0; // no DSL in Jan, Feb, Nov, Dez
if (monat > 3 && monat < 10) return 1; // DSL in Apr, May, Jun, Jul, Aug, Sep
int jahr = year (local_t);
int std = hour (local_t);
//int tag = day (local_t);
int stundenBisHeute = (std + 24 * day(local_t));
if ( (monat == 3 && stundenBisHeute >= (1 + timeZone + 24 * (31 - (5 * jahr /4 + 4) % 7))) ||
(monat == 10 && stundenBisHeute < (1 + timeZone + 24 * (31 - (5 * jahr /4 + 1) % 7))) )
return 1;
else
return 0;
/*
int stundenBisWechsel = (1 + 24 * (31 - (5 * year(local_t) / 4 + 4) % 7));
if (monat == 3 && stundenBisHeute >= stundenBisWechsel || monat == 10 && stundenBisHeute < stundenBisWechsel)
return 1;
else
return 0;
*/
}//----------------------------------------------------------------------------------------------------------------------
time_t getNow () {
//----------------------------------------------------------------------------------------------------------------------
time_t jetzt = now();
while (!isValidDateTime(jetzt) && getTimeTrials < 10) { // ungültig, max 10x probieren
if (getTimeTrials) {
//Serial.print (getTimeTrials);
//Serial.println(". Versuch für getNtpTime");
}
jetzt = getNtpTime ();
if (isValidDateTime(jetzt)) {
setTime (jetzt);
getTimeTrials = 0;
}
else
getTimeTrials++;
}
//return jetzt + offsetDayLightSaving(jetzt)*SECS_PER_HOUR;
return jetzt;
}//----------------------------------------------------------------------------------------------------------------------
char _timestr[24];
char* getNowStr (time_t no = getNow()) {
//----------------------------------------------------------------------------------------------------------------------
sprintf (_timestr, "%02d:%02d:%02d", hour(no), minute(no), second(no));
return _timestr;
}//----------------------------------------------------------------------------------------------------------------------
char* getTimeStr (time_t no = getNow()) {
//----------------------------------------------------------------------------------------------------------------------
return getNowStr (no);
}//----------------------------------------------------------------------------------------------------------------------
char* getDateTimeStr (time_t no) {
//----------------------------------------------------------------------------------------------------------------------
sprintf (_timestr, "%04d-%02d-%02d+%02d:%02d:%02d", year(no), month(no), day(no), hour(no), minute(no), second(no));
return _timestr;
}
char* getDateStr (time_t no) {
//----------------------------------------------------------------------------------------------------------------------
sprintf (_timestr, "%04d-%02d-%02d", year(no), month(no), day(no));
return _timestr;
}//----------------------------------------------------------------------------------------------------------------------
#endif