소스 검색

Added ntp module, config header

Thomas Buck 8 년 전
부모
커밋
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,72 +8,30 @@
8 8
 #include <WiFiServer.h>
9 9
 #include <DNSServer.h>
10 10
 #include <WiFiManager.h>
11
+#include "config.h"
12
+#include "ntp.h"
11 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 16
 ESP8266WebServer server(WEB_PORT);
39 17
 WiFiServer serverSocket(WEBSOCKET_PORT);
40 18
 WebSocketServer webSocketServer;
41
-
42 19
 IPAddress broadcastIP;
43
-
20
+WiFiUDP udp;
44 21
 PersistentStorage storage;
45
-
46 22
 std::vector<IPAddress> vecClients; 
47
-
48
-// UDP-Config
49
-#define UDP_PACKET_BUFFER_SIZE 255
50 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 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 29
 void handleRoot() {
72 30
     Serial.println("Sending UDP Broadcast...");
73 31
 
74 32
     // Send UDP broadcast to other modules
75 33
     udp.beginPacket(broadcastIP, BROADCAST_PORT);
76
-    udp.write(pingBuffer);
34
+    udp.write(UDP_PING_CONTENTS);
77 35
     udp.endPacket();
78 36
 
79 37
     // Start reply wait timer
@@ -81,7 +39,7 @@ void handleRoot() {
81 39
     waitingForReplies = true;
82 40
 }
83 41
 
84
-void handleNotFound(){
42
+void handleNotFound() {
85 43
     String message = "File Not Found\n\n";
86 44
     message += "URI: ";
87 45
     message += server.uri();
@@ -102,7 +60,7 @@ void setup(void) {
102 60
     Serial.println();
103 61
     Serial.println("ESP-Weather init...");
104 62
 
105
-    //SHT21.begin();
63
+    //sensor.begin();
106 64
     // The SHT library is simpy calling Wire.begin(), but the default
107 65
     // config does not match the pins i'm using (sda - 2; scl - 0)
108 66
     Wire.begin(2, 0);
@@ -138,17 +96,14 @@ void setup(void) {
138 96
 
139 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 101
     udp.begin(BROADCAST_PORT);
148 102
     Serial.println("ESP-Weather ready!");
149 103
 }
150 104
 
151
-void loop(void){
105
+void loop(void) {
106
+    ntpRun();
152 107
     server.handleClient();
153 108
 
154 109
     // Websocket fuer Browser
@@ -157,10 +112,10 @@ void loop(void){
157 112
         Serial.println("Building WebSocket Response...");
158 113
 
159 114
         String json = "{\"H\":";
160
-        json += String(SHT21.getHumidity());
115
+        json += String(sensor.getHumidity());
161 116
         json += ",";
162 117
         json += "\"T\":";
163
-        json += String(SHT21.getTemperature());
118
+        json += String(sensor.getTemperature());
164 119
         json += ", \"EEPROM\" : [";
165 120
         for (int i = 0; i < storage.header.count; i++) {
166 121
             json += "{\"H\":";
@@ -183,28 +138,6 @@ void loop(void){
183 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 141
     // EEPROM-Schreiben jede Stunde
209 142
     if ((((((millis() - timeReceived) / 1000) + timestamp) % 3600) == 0)
210 143
             && (timestamp != 0) && (((millis() - lastStorageTime) > 100000) || storeAtBoot) ) {
@@ -218,8 +151,8 @@ void loop(void){
218 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 156
         writeMemory(storage);
224 157
     }
225 158
 
@@ -236,12 +169,12 @@ void loop(void){
236 169
         Serial.print("Got UDP packet: ");
237 170
         Serial.println(packetBuffer);
238 171
 
239
-        if (strcmp(packetBuffer, pingBuffer) == 0) {
172
+        if (strcmp(packetBuffer, UDP_PING_CONTENTS) == 0) {
240 173
             Serial.println("Broadcast");
241 174
             udp.beginPacket(udp.remoteIP(), udp.remotePort());
242
-            udp.print(echoBuffer);
175
+            udp.print(UDP_ECHO_CONTENTS);
243 176
             udp.endPacket();
244
-        } else if((strcmp(packetBuffer, echoBuffer) == 0) && (waitingForReplies == true)) {
177
+        } else if((strcmp(packetBuffer, UDP_ECHO_CONTENTS) == 0) && (waitingForReplies == true)) {
245 178
             vecClients.push_back(udp.remoteIP());
246 179
         }
247 180
     }
@@ -249,7 +182,7 @@ void loop(void){
249 182
     if (((millis() - lastTime) >= MAX_BROADCAST_WAIT_TIME) && (waitingForReplies == true)) {
250 183
         Serial.println("Timeout, sending response...");
251 184
         waitingForReplies = false;
252
-        String message = htmlBegin;
185
+        String message = HTML_BEGIN;
253 186
         message += "var clients = Array(";
254 187
         message += "\"" + WiFi.localIP().toString() + "\"";
255 188
         if (vecClients.size() > 0) {
@@ -262,7 +195,7 @@ void loop(void){
262 195
             }
263 196
         }
264 197
         message += ");";
265
-        message += htmlEnd;
198
+        message += HTML_END;
266 199
 
267 200
         vecClients.clear();
268 201
 
@@ -270,20 +203,3 @@ void loop(void){
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 파일 보기

@@ -0,0 +1,73 @@
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 파일 보기

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

+ 1
- 1
storage.h 파일 보기

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

Loading…
취소
저장