Browse Source

added ESP8266 arduino project

g40st 8 years ago
parent
commit
b4b708332c
2 changed files with 325 additions and 2 deletions
  1. 3
    2
      js/script.js
  2. 322
    0
      sysAdmin/sysAdmin.ino

+ 3
- 2
js/script.js View File

157
             tmpDataTemperature.push(tmp.actualTemp);
157
             tmpDataTemperature.push(tmp.actualTemp);
158
             tmpDataHumidity.push(tmp.actualHum);
158
             tmpDataHumidity.push(tmp.actualHum);
159
             
159
             
160
+            var lineColor = getRandomColor();
160
             dataTemperature.push({label: "Sensor " + tmp.id, data: tmpDataTemperature, fill: false,
161
             dataTemperature.push({label: "Sensor " + tmp.id, data: tmpDataTemperature, fill: false,
161
-                borderWidth: 3, borderColor : getRandomColor(),});
162
+                borderWidth: 3, borderColor : lineColor,});
162
             dataHumidity.push({label: "Sensor " + tmp.id, data: tmpDataHumidity, fill: false,
163
             dataHumidity.push({label: "Sensor " + tmp.id, data: tmpDataHumidity, fill: false,
163
-                borderWidth: 3, borderColor : getRandomColor(),});
164
+                borderWidth: 3, borderColor : lineColor,});
164
 
165
 
165
             tmpDataTemperature = [];
166
             tmpDataTemperature = [];
166
             tmpDataHumidity = [];
167
             tmpDataHumidity = [];

+ 322
- 0
sysAdmin/sysAdmin.ino View File

1
+#include <ESP8266WiFi.h>
2
+#include <WiFiClient.h>
3
+#include <ESP8266WebServer.h>
4
+#include <WiFiUdp.h>
5
+#include "SHT21.h"
6
+#include <vector>
7
+#include <WebSocketServer.h>
8
+#include <WiFiServer.h>
9
+#include <EEPROM.h>
10
+
11
+#define NTP_PORT 2392
12
+#define MAX_WAIT_TIME 550
13
+#define EEPROM_SIZE 512
14
+
15
+// NTP-Client
16
+IPAddress timeServerIP; 
17
+const char* ntpServerName = "time.nist.gov";
18
+const int NTP_PACKET_SIZE = 48; 
19
+byte ntpPacketBuffer[NTP_PACKET_SIZE]; 
20
+WiFiUDP ntp;
21
+unsigned long timestamp = 0;
22
+unsigned long timeReceived = 0;
23
+unsigned long lastStorageTime = 0;
24
+byte storeAtBoot = 1;
25
+unsigned long lastNTP = 0;
26
+
27
+SHT21 SHT21;
28
+ESP8266WebServer server(80);
29
+WiFiServer serverSocket(2391);
30
+WebSocketServer webSocketServer;
31
+
32
+const char* ssid = "SysadminWLAN";
33
+const char* password = "sysadmin";
34
+IPAddress broadcastIP;
35
+
36
+struct __attribute__((__packed__)) Measurement {
37
+  float temperature;
38
+  float humidity;
39
+};
40
+
41
+struct __attribute__((__packed__)) Header {
42
+  uint8_t count;
43
+  uint16_t checksum;
44
+};
45
+
46
+#define MAX_STORAGE (EEPROM_SIZE - sizeof(Header)) / sizeof(Measurement)
47
+
48
+struct __attribute__((__packed__)) PersistentStorage {
49
+  Measurement data[MAX_STORAGE];
50
+  Header header;
51
+};
52
+
53
+PersistentStorage storage;
54
+
55
+void writeMemory(PersistentStorage &s) {
56
+  Serial.println("write Memory");
57
+  unsigned char* r = (unsigned char*) &s;
58
+  uint16_t a = 0, b = 0;
59
+  for(int i = 0; i < sizeof(PersistentStorage) - 2; i++) {
60
+    a = (a + r[i]) % 255;
61
+    b = (b + a) % 255; 
62
+  }
63
+  s.header.checksum = (b << 8) | a;
64
+  for(int i = 0; i < sizeof(PersistentStorage); i++) {
65
+    EEPROM.write(i, r[i]);
66
+  }
67
+  EEPROM.commit();
68
+}
69
+
70
+PersistentStorage readMemory() {
71
+  PersistentStorage s;
72
+  unsigned char* r = (unsigned char*) &s;
73
+  for(int i = 0; i < sizeof(PersistentStorage); i++) {
74
+    r[i] = EEPROM.read(i);
75
+  }
76
+  uint16_t a = 0, b = 0;
77
+  for(int i = 0; i < sizeof(PersistentStorage) - 2; i++) {
78
+    a = (a + r[i]) % 255;
79
+    b = (b + a) % 255; 
80
+  }
81
+  if(s.header.checksum != ((b << 8) | a)) {
82
+    Serial.print("Checksum error ");
83
+    Serial.print(s.header.checksum);
84
+    Serial.print(" ");
85
+    Serial.println((b << 8) | a);
86
+    s.header.count = 0;
87
+  } else {
88
+    Serial.println("Checksum ok");  
89
+  }
90
+  return s;
91
+}
92
+
93
+std::vector<IPAddress> vecClients; 
94
+
95
+// UDP-Config
96
+unsigned int localPort = 2390;
97
+char packetBuffer[255];                                       
98
+char pingBuffer[] = "pingESP8266v0.1";
99
+char echoBuffer[] = "echoESP8266v0.1";
100
+WiFiUDP Udp;
101
+
102
+unsigned long lastTime;
103
+bool waitingForReplies = false;
104
+
105
+const char* htmlBegin = "<html>\
106
+  <head>\
107
+    <title>Sysadmin</title>\
108
+    <script src=\"http://hoegerle-home.de/sysAdmin/js/jquery-3.1.1.min.js\"></script>\
109
+    <script src=\"http://hoegerle-home.de/sysAdmin/js/bootstrap.min.js\"></script>\ 
110
+    <script src=\"http://hoegerle-home.de/sysAdmin/js/Chart.bundle.min.js\"></script>\
111
+    <script src=\"http://hoegerle-home.de/sysAdmin/js/script.js\"></script>\
112
+    <link rel=\"stylesheet\" href=\"http://hoegerle-home.de/sysAdmin/css/bootstrap.min.css\" />\
113
+  </head>\
114
+  <body>\
115
+    <script type=\"text/javascript\">";
116
+const char* htmlEnd = "</script>\
117
+  </body>\
118
+</html>";
119
+
120
+// root-URL
121
+void handleRoot() {
122
+  // send a reply, to the IP address and port that sent us the packet we received
123
+  Udp.beginPacket(broadcastIP, 2390);
124
+  Udp.write(pingBuffer);
125
+  Udp.endPacket();
126
+
127
+  // Timer starten
128
+  lastTime = millis();
129
+  waitingForReplies = true;
130
+  
131
+  Serial.println("broadcast send");
132
+}
133
+
134
+// URL nicht vorhanden
135
+void handleNotFound(){
136
+  String message = "File Not Found\n\n";
137
+  message += "URI: ";
138
+  message += server.uri();
139
+  message += "\nMethod: ";
140
+  message += (server.method() == HTTP_GET)?"GET":"POST";
141
+  message += "\nArguments: ";
142
+  message += server.args();
143
+  message += "\n";
144
+  for (uint8_t i=0; i<server.args(); i++){
145
+    message += " " + server.argName(i) + ": " + server.arg(i) + "\n";
146
+  }
147
+  server.send(404, "text/plain", message);
148
+}
149
+
150
+void setup(void) {
151
+  SHT21.begin();
152
+  
153
+  EEPROM.begin(512);
154
+    
155
+  // Debugging
156
+  Serial.begin(115200);
157
+  WiFi.begin(ssid, password);
158
+  Serial.println("");
159
+
160
+  // Wait for connection
161
+  while (WiFi.status() != WL_CONNECTED) {
162
+    delay(500);
163
+    Serial.print(".");
164
+  }
165
+  Serial.println("");
166
+  Serial.print("Connected to ");
167
+  Serial.println(ssid);
168
+  Serial.print("IP address: ");
169
+  Serial.println(WiFi.localIP());
170
+    
171
+  broadcastIP = ~WiFi.subnetMask() | WiFi.gatewayIP();
172
+  
173
+  storage = readMemory();
174
+  
175
+  server.on("/", handleRoot);
176
+  server.onNotFound(handleNotFound);
177
+  server.begin();
178
+
179
+  serverSocket.begin();
180
+
181
+  // NTP-Client
182
+  ntp.begin(NTP_PORT);
183
+  WiFi.hostByName(ntpServerName, timeServerIP); 
184
+  lastNTP = millis();
185
+  sendNTPpacket(timeServerIP); 
186
+  
187
+  Udp.begin(localPort);
188
+  Serial.println("HTTP server and UDP started");
189
+}
190
+
191
+void loop(void){
192
+  server.handleClient();
193
+
194
+  // Websocket fuer Browser
195
+  WiFiClient client = serverSocket.available();
196
+  if(client.connected() && webSocketServer.handshake(client)) {
197
+    
198
+    String json = "{\"H\":";
199
+    json += String(SHT21.getHumidity());
200
+    json += ",";
201
+    json += "\"T\":";
202
+    json += String(SHT21.getTemperature());
203
+    json += ", \"EEPROM\" : [";
204
+    for(int i = 0; i < storage.header.count; i++) {
205
+      json += "{\"H\":";
206
+      json += String(storage.data[i].humidity);
207
+      json += ",";
208
+      json += "\"T\":";
209
+      json += String(storage.data[i].temperature);
210
+      json += "}";
211
+      if(i < storage.header.count - 1) {
212
+        json += ",";
213
+      }
214
+    }
215
+    json += "]}";
216
+    Serial.println(json);
217
+    
218
+    webSocketServer.sendData(json);
219
+    client.flush();
220
+    client.stop();
221
+  }
222
+
223
+  // NTP wiederholen falls keine Antwort
224
+  if((timestamp == 0) && ((millis() - lastNTP) > 2000)) {
225
+    WiFi.hostByName(ntpServerName, timeServerIP); 
226
+    lastNTP = millis();
227
+    sendNTPpacket(timeServerIP); 
228
+  }
229
+  
230
+  // NTP Paket vom Server erhalten
231
+  if(ntp.parsePacket() >= NTP_PACKET_SIZE) {
232
+    ntp.read(ntpPacketBuffer, NTP_PACKET_SIZE);   
233
+    unsigned long highWord = word(ntpPacketBuffer[40], ntpPacketBuffer[41]);
234
+    unsigned long lowWord = word(ntpPacketBuffer[42], ntpPacketBuffer[43]);
235
+    unsigned long secsSince1900 = highWord << 16 | lowWord;
236
+    const unsigned long seventyYears = 2208988800UL;
237
+    unsigned long epoch = secsSince1900 - seventyYears;
238
+    timestamp = epoch;
239
+    timeReceived = millis();
240
+    Serial.println(epoch);
241
+  }
242
+
243
+  // EEPROM-Schreiben jede Stunde
244
+  if((((((millis() - timeReceived) / 1000) + timestamp) % 3600) == 0) && (timestamp != 0) && (((millis() - lastStorageTime) > 100000) || storeAtBoot) ) {
245
+      lastStorageTime = millis();
246
+      storeAtBoot = 0;
247
+      if(storage.header.count < MAX_STORAGE) {
248
+        storage.header.count++;
249
+      } else {
250
+        for(int i = 0; i < MAX_STORAGE - 1; i++) {
251
+          storage.data[i] = storage.data[i+1];
252
+        }
253
+      }
254
+      storage.data[storage.header.count-1].temperature = SHT21.getTemperature();
255
+      storage.data[storage.header.count-1].humidity = SHT21.getHumidity(); 
256
+      writeMemory(storage); 
257
+  }
258
+  
259
+  // UDP
260
+  int packetSize = Udp.parsePacket();
261
+  if(packetSize) {
262
+    IPAddress remoteIp = Udp.remoteIP();
263
+    // read the packet into packetBufffer
264
+    int len = Udp.read(packetBuffer, 255);
265
+    if (len > 0) {
266
+      packetBuffer[len] = 0;
267
+    }
268
+    
269
+    Serial.println(packetBuffer);
270
+       
271
+    if(strcmp(packetBuffer, pingBuffer) == 0) {
272
+      Serial.println("Broadcast");
273
+      Udp.beginPacket(Udp.remoteIP(), Udp.remotePort());
274
+      Udp.print(echoBuffer);
275
+      Udp.endPacket();
276
+    } else if((strcmp(packetBuffer, echoBuffer) == 0) && (waitingForReplies == true)) {
277
+      vecClients.push_back(Udp.remoteIP());
278
+    }
279
+  }
280
+  
281
+  if(((millis() - lastTime) >= MAX_WAIT_TIME) && (waitingForReplies == true)) {
282
+    Serial.println("waiting done");
283
+    waitingForReplies = false;
284
+    String message = htmlBegin;
285
+    message += "var clients = Array(";
286
+    message += "\"" + WiFi.localIP().toString() + "\"";
287
+    if(vecClients.size() > 0) {
288
+      message += ", ";
289
+    }
290
+    for(int i = 0; i < vecClients.size(); i++) {
291
+      message += "\"" + vecClients[i].toString() + "\"";
292
+      if(i < (vecClients.size() - 1)) {
293
+        message += ", ";
294
+      }
295
+    }
296
+    message += ");";
297
+    message += htmlEnd;
298
+
299
+    vecClients.clear();
300
+    
301
+    server.send(200, "text/html", message);
302
+  }
303
+}
304
+
305
+void sendNTPpacket(IPAddress& address) {
306
+  Serial.println("sending NTP packet...");
307
+  memset(ntpPacketBuffer, 0, NTP_PACKET_SIZE);
308
+  ntpPacketBuffer[0] = 0b11100011;   // LI, Version, Mode
309
+  ntpPacketBuffer[1] = 0;    
310
+  ntpPacketBuffer[2] = 6;     
311
+  ntpPacketBuffer[3] = 0xEC; 
312
+  ntpPacketBuffer[12]  = 49;
313
+  ntpPacketBuffer[13]  = 0x4E;
314
+  ntpPacketBuffer[14]  = 49;
315
+  ntpPacketBuffer[15]  = 52;
316
+
317
+  ntp.beginPacket(address, 123);
318
+  ntp.write(ntpPacketBuffer, NTP_PACKET_SIZE);
319
+  ntp.endPacket();
320
+}
321
+
322
+

Loading…
Cancel
Save