瀏覽代碼

Added ntp module, config header

Thomas Buck 7 年之前
父節點
當前提交
45ccabfacd
共有 5 個文件被更改,包括 122 次插入111 次删除
  1. 22
    106
      ESP-Weather.ino
  2. 73
    0
      ntp.cpp
  3. 11
    0
      ntp.h
  4. 15
    4
      storage.cpp
  5. 1
    1
      storage.h

+ 22
- 106
ESP-Weather.ino 查看文件

8
 #include <WiFiServer.h>
8
 #include <WiFiServer.h>
9
 #include <DNSServer.h>
9
 #include <DNSServer.h>
10
 #include <WiFiManager.h>
10
 #include <WiFiManager.h>
11
+#include "config.h"
12
+#include "ntp.h"
11
 #include "storage.h"
13
 #include "storage.h"
12
 
14
 
13
-#define WEB_PORT 80
14
-#define BROADCAST_PORT 2390
15
-#define WEBSOCKET_PORT 2391
16
-#define NTP_PORT_FROM 2392
17
-#define NTP_PORT_TO 123
18
-
19
-#define DEFAULT_SSID "ESP-Weather"
20
-#define DEFAULT_PASS "testtest"
21
-
22
-#define MAX_BROADCAST_WAIT_TIME 550
23
-#define NTP_RETRY_TIMEOUT 2000
24
-
25
-// NTP-Client
26
-IPAddress timeServerIP; 
27
-const char* ntpServerName = "time.nist.gov";
28
-const int NTP_PACKET_SIZE = 48; 
29
-byte ntpPacketBuffer[NTP_PACKET_SIZE]; 
30
-WiFiUDP ntp;
31
-unsigned long timestamp = 0;
32
-unsigned long timeReceived = 0;
33
-unsigned long lastStorageTime = 0;
34
-byte storeAtBoot = 1;
35
-unsigned long lastNTP = 0;
36
-
37
-SHT21 SHT21;
15
+SHT21 sensor;
38
 ESP8266WebServer server(WEB_PORT);
16
 ESP8266WebServer server(WEB_PORT);
39
 WiFiServer serverSocket(WEBSOCKET_PORT);
17
 WiFiServer serverSocket(WEBSOCKET_PORT);
40
 WebSocketServer webSocketServer;
18
 WebSocketServer webSocketServer;
41
-
42
 IPAddress broadcastIP;
19
 IPAddress broadcastIP;
43
-
20
+WiFiUDP udp;
44
 PersistentStorage storage;
21
 PersistentStorage storage;
45
-
46
 std::vector<IPAddress> vecClients; 
22
 std::vector<IPAddress> vecClients; 
47
-
48
-// UDP-Config
49
-#define UDP_PACKET_BUFFER_SIZE 255
50
 char packetBuffer[UDP_PACKET_BUFFER_SIZE];
23
 char packetBuffer[UDP_PACKET_BUFFER_SIZE];
51
-const char pingBuffer[] = "pingESP8266v0.1";
52
-const char echoBuffer[] = "echoESP8266v0.1";
53
-WiFiUDP udp;
54
-
55
-unsigned long lastTime;
24
+unsigned long lastStorageTime = 0;
25
+byte storeAtBoot = 1;
26
+unsigned long lastTime = 0;
56
 bool waitingForReplies = false;
27
 bool waitingForReplies = false;
57
 
28
 
58
-// Using the RawGit.com service to serve the scripts directly from GitHub.
59
-// Consider using cdn.rawgit.com to reduce their server load.
60
-const char* htmlBegin = "<html><head>\
61
-<title>Sysadmin</title>\
62
-<script src=\"https://rawgit.com/xythobuz/ESP-Weather/master/static/jquery-3.1.1.min.js\"></script>\
63
-<script src=\"https://rawgit.com/xythobuz/ESP-Weather/master/static/bootstrap.min.js\"></script>\
64
-<script src=\"https://rawgit.com/xythobuz/ESP-Weather/master/static/Chart.bundle.min.js\"></script>\
65
-<script src=\"https://rawgit.com/xythobuz/ESP-Weather/master/static/script.js\"></script>\
66
-<link rel=\"stylesheet\" href=\"https://rawgit.com/xythobuz/ESP-Weather/master/static/bootstrap.min.css\" />\
67
-</head><body>\
68
-<script type=\"text/javascript\">";
69
-const char* htmlEnd = "</script></body></html>";
70
-
71
 void handleRoot() {
29
 void handleRoot() {
72
     Serial.println("Sending UDP Broadcast...");
30
     Serial.println("Sending UDP Broadcast...");
73
 
31
 
74
     // Send UDP broadcast to other modules
32
     // Send UDP broadcast to other modules
75
     udp.beginPacket(broadcastIP, BROADCAST_PORT);
33
     udp.beginPacket(broadcastIP, BROADCAST_PORT);
76
-    udp.write(pingBuffer);
34
+    udp.write(UDP_PING_CONTENTS);
77
     udp.endPacket();
35
     udp.endPacket();
78
 
36
 
79
     // Start reply wait timer
37
     // Start reply wait timer
81
     waitingForReplies = true;
39
     waitingForReplies = true;
82
 }
40
 }
83
 
41
 
84
-void handleNotFound(){
42
+void handleNotFound() {
85
     String message = "File Not Found\n\n";
43
     String message = "File Not Found\n\n";
86
     message += "URI: ";
44
     message += "URI: ";
87
     message += server.uri();
45
     message += server.uri();
102
     Serial.println();
60
     Serial.println();
103
     Serial.println("ESP-Weather init...");
61
     Serial.println("ESP-Weather init...");
104
 
62
 
105
-    //SHT21.begin();
63
+    //sensor.begin();
106
     // The SHT library is simpy calling Wire.begin(), but the default
64
     // The SHT library is simpy calling Wire.begin(), but the default
107
     // config does not match the pins i'm using (sda - 2; scl - 0)
65
     // config does not match the pins i'm using (sda - 2; scl - 0)
108
     Wire.begin(2, 0);
66
     Wire.begin(2, 0);
138
 
96
 
139
     serverSocket.begin();
97
     serverSocket.begin();
140
 
98
 
141
-    // NTP-Client
142
-    ntp.begin(NTP_PORT_FROM);
143
-    WiFi.hostByName(ntpServerName, timeServerIP); 
144
-    lastNTP = millis();
145
-    sendNTPpacket(timeServerIP); 
99
+    ntpInit();
146
 
100
 
147
     udp.begin(BROADCAST_PORT);
101
     udp.begin(BROADCAST_PORT);
148
     Serial.println("ESP-Weather ready!");
102
     Serial.println("ESP-Weather ready!");
149
 }
103
 }
150
 
104
 
151
-void loop(void){
105
+void loop(void) {
106
+    ntpRun();
152
     server.handleClient();
107
     server.handleClient();
153
 
108
 
154
     // Websocket fuer Browser
109
     // Websocket fuer Browser
157
         Serial.println("Building WebSocket Response...");
112
         Serial.println("Building WebSocket Response...");
158
 
113
 
159
         String json = "{\"H\":";
114
         String json = "{\"H\":";
160
-        json += String(SHT21.getHumidity());
115
+        json += String(sensor.getHumidity());
161
         json += ",";
116
         json += ",";
162
         json += "\"T\":";
117
         json += "\"T\":";
163
-        json += String(SHT21.getTemperature());
118
+        json += String(sensor.getTemperature());
164
         json += ", \"EEPROM\" : [";
119
         json += ", \"EEPROM\" : [";
165
         for (int i = 0; i < storage.header.count; i++) {
120
         for (int i = 0; i < storage.header.count; i++) {
166
             json += "{\"H\":";
121
             json += "{\"H\":";
183
         client.stop();
138
         client.stop();
184
     }
139
     }
185
 
140
 
186
-    // NTP wiederholen falls keine Antwort
187
-    if ((timestamp == 0) && ((millis() - lastNTP) > NTP_RETRY_TIMEOUT)) {
188
-        Serial.println("NTP packet retry...");
189
-        WiFi.hostByName(ntpServerName, timeServerIP);
190
-        lastNTP = millis();
191
-        sendNTPpacket(timeServerIP);
192
-    }
193
-
194
-    // NTP Paket vom Server erhalten
195
-    if (ntp.parsePacket() >= NTP_PACKET_SIZE) {
196
-        ntp.read(ntpPacketBuffer, NTP_PACKET_SIZE);
197
-        unsigned long highWord = word(ntpPacketBuffer[40], ntpPacketBuffer[41]);
198
-        unsigned long lowWord = word(ntpPacketBuffer[42], ntpPacketBuffer[43]);
199
-        unsigned long secsSince1900 = highWord << 16 | lowWord;
200
-        const unsigned long seventyYears = 2208988800UL;
201
-        unsigned long epoch = secsSince1900 - seventyYears;
202
-        timestamp = epoch;
203
-        timeReceived = millis();
204
-        Serial.print("Got NTP time: ");
205
-        Serial.println(epoch);
206
-    }
207
-
208
     // EEPROM-Schreiben jede Stunde
141
     // EEPROM-Schreiben jede Stunde
209
     if ((((((millis() - timeReceived) / 1000) + timestamp) % 3600) == 0)
142
     if ((((((millis() - timeReceived) / 1000) + timestamp) % 3600) == 0)
210
             && (timestamp != 0) && (((millis() - lastStorageTime) > 100000) || storeAtBoot) ) {
143
             && (timestamp != 0) && (((millis() - lastStorageTime) > 100000) || storeAtBoot) ) {
218
                 storage.data[i] = storage.data[i+1];
151
                 storage.data[i] = storage.data[i+1];
219
             }
152
             }
220
         }
153
         }
221
-        storage.data[storage.header.count - 1].temperature = SHT21.getTemperature();
222
-        storage.data[storage.header.count - 1].humidity = SHT21.getHumidity();
154
+        storage.data[storage.header.count - 1].temperature = sensor.getTemperature();
155
+        storage.data[storage.header.count - 1].humidity = sensor.getHumidity();
223
         writeMemory(storage);
156
         writeMemory(storage);
224
     }
157
     }
225
 
158
 
236
         Serial.print("Got UDP packet: ");
169
         Serial.print("Got UDP packet: ");
237
         Serial.println(packetBuffer);
170
         Serial.println(packetBuffer);
238
 
171
 
239
-        if (strcmp(packetBuffer, pingBuffer) == 0) {
172
+        if (strcmp(packetBuffer, UDP_PING_CONTENTS) == 0) {
240
             Serial.println("Broadcast");
173
             Serial.println("Broadcast");
241
             udp.beginPacket(udp.remoteIP(), udp.remotePort());
174
             udp.beginPacket(udp.remoteIP(), udp.remotePort());
242
-            udp.print(echoBuffer);
175
+            udp.print(UDP_ECHO_CONTENTS);
243
             udp.endPacket();
176
             udp.endPacket();
244
-        } else if((strcmp(packetBuffer, echoBuffer) == 0) && (waitingForReplies == true)) {
177
+        } else if((strcmp(packetBuffer, UDP_ECHO_CONTENTS) == 0) && (waitingForReplies == true)) {
245
             vecClients.push_back(udp.remoteIP());
178
             vecClients.push_back(udp.remoteIP());
246
         }
179
         }
247
     }
180
     }
249
     if (((millis() - lastTime) >= MAX_BROADCAST_WAIT_TIME) && (waitingForReplies == true)) {
182
     if (((millis() - lastTime) >= MAX_BROADCAST_WAIT_TIME) && (waitingForReplies == true)) {
250
         Serial.println("Timeout, sending response...");
183
         Serial.println("Timeout, sending response...");
251
         waitingForReplies = false;
184
         waitingForReplies = false;
252
-        String message = htmlBegin;
185
+        String message = HTML_BEGIN;
253
         message += "var clients = Array(";
186
         message += "var clients = Array(";
254
         message += "\"" + WiFi.localIP().toString() + "\"";
187
         message += "\"" + WiFi.localIP().toString() + "\"";
255
         if (vecClients.size() > 0) {
188
         if (vecClients.size() > 0) {
262
             }
195
             }
263
         }
196
         }
264
         message += ");";
197
         message += ");";
265
-        message += htmlEnd;
198
+        message += HTML_END;
266
 
199
 
267
         vecClients.clear();
200
         vecClients.clear();
268
 
201
 
270
     }
203
     }
271
 }
204
 }
272
 
205
 
273
-void sendNTPpacket(IPAddress& address) {
274
-    Serial.println("Sending NTP packet...");
275
-    memset(ntpPacketBuffer, 0, NTP_PACKET_SIZE);
276
-    ntpPacketBuffer[0] = 0b11100011; // LI, Version, Mode
277
-    ntpPacketBuffer[1] = 0;
278
-    ntpPacketBuffer[2] = 6;
279
-    ntpPacketBuffer[3] = 0xEC;
280
-    ntpPacketBuffer[12]  = 49;
281
-    ntpPacketBuffer[13]  = 0x4E;
282
-    ntpPacketBuffer[14]  = 49;
283
-    ntpPacketBuffer[15]  = 52;
284
-
285
-    ntp.beginPacket(address, NTP_PORT_TO);
286
-    ntp.write(ntpPacketBuffer, NTP_PACKET_SIZE);
287
-    ntp.endPacket();
288
-}
289
-

+ 73
- 0
ntp.cpp 查看文件

1
+#include <Arduino.h>
2
+#include <ESP8266WiFi.h>
3
+#include <WiFiUdp.h>
4
+#include "config.h"
5
+#include "ntp.h"
6
+
7
+//#define DEBUG
8
+
9
+IPAddress timeServerIP;
10
+byte ntpPacketBuffer[NTP_PACKET_SIZE];
11
+WiFiUDP ntp;
12
+
13
+unsigned long lastNTP = 0; // timer for retries
14
+unsigned long timestamp = 0; // received epoch time
15
+unsigned long timeReceived = 0; // systick matching received epoch
16
+
17
+static void sendNTPpacket(IPAddress& address) {
18
+#ifdef DEBUG
19
+    Serial.println("Sending NTP packet...");
20
+#endif
21
+
22
+    memset(ntpPacketBuffer, 0, NTP_PACKET_SIZE);
23
+    ntpPacketBuffer[0] = 0b11100011; // LI, Version, Mode
24
+    ntpPacketBuffer[1] = 0;
25
+    ntpPacketBuffer[2] = 6;
26
+    ntpPacketBuffer[3] = 0xEC;
27
+    ntpPacketBuffer[12]  = 49;
28
+    ntpPacketBuffer[13]  = 0x4E;
29
+    ntpPacketBuffer[14]  = 49;
30
+    ntpPacketBuffer[15]  = 52;
31
+
32
+    ntp.beginPacket(address, NTP_PORT_TO);
33
+    ntp.write(ntpPacketBuffer, NTP_PACKET_SIZE);
34
+    ntp.endPacket();
35
+}
36
+
37
+void ntpInit(void) {
38
+    ntp.begin(NTP_PORT_FROM);
39
+    WiFi.hostByName(NTP_SERVER_NAME, timeServerIP);
40
+    lastNTP = millis();
41
+    sendNTPpacket(timeServerIP);
42
+}
43
+
44
+void ntpRun(void) {
45
+    // Retry if we haven't received an answer soon enough
46
+    if ((timestamp == 0) && ((millis() - lastNTP) > NTP_RETRY_TIMEOUT)) {
47
+#ifdef DEBUG
48
+        Serial.println("NTP packet retry...");
49
+#endif // DEBUG
50
+
51
+        WiFi.hostByName(NTP_SERVER_NAME, timeServerIP);
52
+        lastNTP = millis();
53
+        sendNTPpacket(timeServerIP);
54
+    }
55
+
56
+    // Process received response
57
+    if (ntp.parsePacket() >= NTP_PACKET_SIZE) {
58
+        ntp.read(ntpPacketBuffer, NTP_PACKET_SIZE);
59
+        unsigned long highWord = word(ntpPacketBuffer[40], ntpPacketBuffer[41]);
60
+        unsigned long lowWord = word(ntpPacketBuffer[42], ntpPacketBuffer[43]);
61
+        unsigned long secsSince1900 = highWord << 16 | lowWord;
62
+        const unsigned long seventyYears = 2208988800UL;
63
+        unsigned long epoch = secsSince1900 - seventyYears;
64
+        timestamp = epoch;
65
+        timeReceived = millis();
66
+
67
+#ifdef DEBUG
68
+        Serial.print("Got NTP time: ");
69
+        Serial.println(epoch);
70
+#endif // DEBUG
71
+    }
72
+}
73
+

+ 11
- 0
ntp.h 查看文件

1
+#ifndef __NTP_H__
2
+#define __NTP_H__
3
+
4
+extern unsigned long timestamp; // received epoch time, 0 until valid
5
+extern unsigned long timeReceived; // systick matching received epoch, 0 until valid
6
+
7
+void ntpInit(void);
8
+void ntpRun(void);
9
+
10
+#endif // __NTP_H__
11
+

+ 15
- 4
storage.cpp 查看文件

2
 #include <EEPROM.h>
2
 #include <EEPROM.h>
3
 #include "storage.h"
3
 #include "storage.h"
4
 
4
 
5
+//#define DEBUG
6
+
5
 void initMemory(void) {
7
 void initMemory(void) {
6
     EEPROM.begin(EEPROM_SIZE);
8
     EEPROM.begin(EEPROM_SIZE);
7
 }
9
 }
8
 
10
 
9
 void writeMemory(PersistentStorage &s) {
11
 void writeMemory(PersistentStorage &s) {
10
-    Serial.println("write Memory");
11
     unsigned char* r = (unsigned char*) &s;
12
     unsigned char* r = (unsigned char*) &s;
12
     uint16_t a = 0, b = 0;
13
     uint16_t a = 0, b = 0;
13
     for (int i = 0; i < sizeof(PersistentStorage) - 2; i++) {
14
     for (int i = 0; i < sizeof(PersistentStorage) - 2; i++) {
15
         b = (b + a) % 255;
16
         b = (b + a) % 255;
16
     }
17
     }
17
     s.header.checksum = (b << 8) | a;
18
     s.header.checksum = (b << 8) | a;
19
+
20
+#ifdef DEBUG
21
+    Serial.print("write memory: ");
22
+    Serial.println(s.header.checksum);
23
+#endif // DEBUG
24
+
18
     for (int i = 0; i < sizeof(PersistentStorage); i++) {
25
     for (int i = 0; i < sizeof(PersistentStorage); i++) {
19
         EEPROM.write(i, r[i]);
26
         EEPROM.write(i, r[i]);
20
     }
27
     }
33
         b = (b + a) % 255;
40
         b = (b + a) % 255;
34
     }
41
     }
35
     if (s.header.checksum != ((b << 8) | a)) {
42
     if (s.header.checksum != ((b << 8) | a)) {
36
-        Serial.print("Checksum error ");
43
+#ifdef DEBUG
44
+        Serial.print("read memory: checksum error: ");
37
         Serial.print(s.header.checksum);
45
         Serial.print(s.header.checksum);
38
-        Serial.print(" ");
46
+        Serial.print(" != ");
39
         Serial.println((b << 8) | a);
47
         Serial.println((b << 8) | a);
48
+#endif // DEBUG
40
         s.header.count = 0;
49
         s.header.count = 0;
41
     } else {
50
     } else {
42
-        Serial.println("Checksum ok");
51
+#ifdef DEBUG
52
+        Serial.println("read memory: checksum ok");
53
+#endif // DEBUG
43
     }
54
     }
44
     return s;
55
     return s;
45
 }
56
 }

+ 1
- 1
storage.h 查看文件

1
 #ifndef __STORAGE_H__
1
 #ifndef __STORAGE_H__
2
 #define __STORAGE_H__
2
 #define __STORAGE_H__
3
 
3
 
4
-#define EEPROM_SIZE 512
4
+#include "config.h"
5
 
5
 
6
 struct __attribute__((__packed__)) Measurement {
6
 struct __attribute__((__packed__)) Measurement {
7
     float temperature;
7
     float temperature;

Loading…
取消
儲存