-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathremote.ino
1963 lines (1807 loc) · 73.3 KB
/
remote.ino
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
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* ESP8266 Remote Control. Also sends weather data from multiple kinds of sensors (configured in config.c)
* originally built on the basis of something I found on https://circuits4you.com
* reorganized and extended by Gus Mueller, April 24 2022 - June 22 2024
* Also resets a Moxee Cellular hotspot if there are network problems
* since those do not include watchdog behaviors
*/
#include <ArduinoJson.h>
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <IRremoteESP8266.h>
#include <IRsend.h>
#include <Adafruit_INA219.h>
#include <Adafruit_VL53L0X.h>
#include <Adafruit_ADT7410.h>
#include <Adafruit_FRAM_I2C.h>
#include <NTPClient.h>
#include <WiFiUdp.h>
#include <SimpleMap.h>
#include "config.h"
#include "Zanshin_BME680.h" // Include the BME680 Sensor library
#include <DHT.h>
#include <Adafruit_AHTX0.h>
#include <SFE_BMP180.h>
#include <Adafruit_BMP085.h>
#include <Temperature_LM75_Derived.h>
#include <Adafruit_BMP280.h>
#include <Wire.h>
#include <tuple>
#include <cmath>
#include "index.h" //Our HTML webpage contents with javascriptrons
//i created 12 of each sensor object in case we added lots more sensors via device_features
//amusingly, this barely ate into memory at all
//since many I2C sensors only permit two sensors per I2C bus, you could reduce the size of these object arrays
//and so i've dropped some of these down to 2
Adafruit_ADT7410 adt7410[4];
DHT* dht[4];
Adafruit_AHTX0 AHT[2];
SFE_BMP180 BMP180[2];
BME680_Class BME680[2];
Adafruit_BMP085 BMP085d[2];
Generic_LM75 LM75[2];
Adafruit_BMP280 BMP280[2];
IRsend irsend(ir_pin);
Adafruit_INA219* ina219;
Adafruit_VL53L0X lox[4];
Adafruit_FRAM_I2C fram;
uint16_t framIndexAddress = 0;
uint16_t currentRecordCount = 0;
StaticJsonDocument<500> jsonBuffer;
WiFiUDP ntpUDP; //i guess i need this for time lookup
NTPClient timeClient(ntpUDP, "pool.ntp.org");
bool localSource = false; //turns true when a local edit to the data is done. at that point we have to send local upstream to the server
byte justDeviceJson = 1;
long connectionFailureTime = 0;
long lastDataLogTime = 0;
long localChangeTime = 0;
long lastPoll = 0;
int pinTotal = 12;
String pinList[12]; //just a list of pins
String pinName[12]; //for friendly names
String ipAddress;
String ipAddressAffectingChange;
int changeSourceId = 0;
String deviceName = "";
String additionalSensorInfo; //we keep it stored in a delimited string just the way it came from the server and unpack it periodically to get the data necessary to read sensors
float measuredVoltage = 0;
float measuredAmpage = 0;
bool canSleep = false;
long latencySum = 0;
long latencyCount = 0;
bool offlineMode = false;
long lastOfflineLog = 0;
uint8_t lastRecordSize = 0;
//https://github.com/spacehuhn/SimpleMap
SimpleMap<String, int> *pinMap = new SimpleMap<String, int>([](String &a, String &b) -> int {
if (a == b) return 0; // a and b are equal
else if (a > b) return 1; // a is bigger than b
else return -1; // a is smaller than b
});
SimpleMap<String, int> *sensorObjectCursor = new SimpleMap<String, int>([](String &a, String &b) -> int {
if (a == b) return 0; // a and b are equal
else if (a > b) return 1; // a is bigger than b
else return -1; // a is smaller than b
});
long moxeeRebootTimes[] = {0,0,0,0,0,0,0,0,0,0,0};
int moxeeRebootCount = 0;
int timeOffset = 0;
long lastCommandId = 0;
bool glblRemote = false;
bool onePinAtATimeMode = false; //used when the server starts gzipping data and we can't make sense of it
char requestNonJsonPinInfo = 0; //use to get much more compressed data double-delimited data from data.php if 1, otherwise if 0 it requests JSON
int pinCursor = -1;
bool connectionFailureMode = true; //when we're in connectionFailureMode, we check connection much more than polling_granularity. otherwise, we check it every polling_granularity
ESP8266WebServer server(80); //Server on port 80
//ESP8266's home page:----------------------------------------------------
void handleRoot() {
String s = MAIN_page; //Read HTML contents
server.send(200, "text/html", s); //Send web page
}
void lookupLocalPowerData() {//sets the globals with the current reading from the ina219
if(ina219_address < 0) { //if we don't have a ina219 then do not bother
return;
}
float shuntvoltage = 0;
float busvoltage = 0;
float current_mA = 0;
float loadvoltage = 0;
float power_mW = 0;
shuntvoltage = ina219->getShuntVoltage_mV();
busvoltage = ina219->getBusVoltage_V();
current_mA = ina219->getCurrent_mA();
power_mW = ina219->getPower_mW();
loadvoltage = busvoltage + (shuntvoltage / 1000);
measuredVoltage = loadvoltage;
measuredAmpage = current_mA;
/*
Serial.print("volt: ");
Serial.print(measuredVoltage);
Serial.print(" amp: ");
Serial.println(measuredAmpage);
Serial.print("Bus Voltage: "); Serial.print(busvoltage); Serial.println(" V");
Serial.print("Shunt Voltage: "); Serial.print(shuntvoltage); Serial.println(" mV");
Serial.print("Load Voltage: "); Serial.print(loadvoltage); Serial.println(" V");
Serial.print("Current: "); Serial.print(current_mA); Serial.println(" mA");
Serial.print("Power: "); Serial.print(power_mW); Serial.println(" mW");
Serial.println("");
*/
}
//returns a "*"-delimited string containing weather data, starting with temperature and ending with deviceFeatureId, a url-encoded sensorName, and consolidateAllSensorsToOneRecord
//we might send multiple-such strings (separated by "!") to the backend for multiple sensors on an ESP8266
//i've made this to handle all the weather sensors i have so i can mix and match, though of course there are many others
String weatherDataString(int sensor_id, int sensor_sub_type, int dataPin, int powerPin, int i2c, int deviceFeatureId, char objectCursor, String sensorName, int ordinalOfOverwrite, int consolidateAllSensorsToOneRecord) {
double humidityValue = NULL;
double temperatureValue = NULL;
double pressureValue = NULL;
double gasValue = NULL;
int32_t humidityRaw = NULL;
int32_t temperatureRaw = NULL;
int32_t pressureRaw = NULL;
int32_t gasRaw = NULL;
int32_t alt = NULL;
static char buf[16];
static uint16_t loopCounter = 0;
String transmissionString = "";
String sensorValue;
double humidityFromSensor = NULL;
double temperatureFromSensor = NULL;
double pressureFromSensor = NULL;
double gasFromSensor = NULL;
if(deviceFeatureId == NULL) {
objectCursor = 0;
}
if(sensor_id == 1) { //simple analog input. we can use subType to decide what kind of sensor it is!
//an even smarter system would somehow be able to put together multiple analogReads here
if(powerPin > -1) {
digitalWrite(powerPin, HIGH); //turn on sensor power.
}
delay(10);
double value = NULL;
if(i2c){
//i forget how we read a pin on an i2c slave. lemme see:
sensorValue = (double)getPinValueOnSlave((char)i2c, (char)dataPin);
} else {
sensorValue = (double)analogRead(dataPin);
}
/*
for(char i=0; i<12; i++){ //we have 12 separate possible sensor functions:
//temperature*pressure*humidity*gas*windDirection*windSpeed*windIncrement*precipitation*reserved1*reserved2*reserved3*reserved4
//if you have some particular sensor communicating through a pin and want it to be one of these
//you set sensor_sub_type to be the 0-based value in that *-delimited string
//i'm thinking i don't bother defining the reserved ones and just let them be application-specific and different in different implementations
//a good one would be radioactive counts per unit time
if((int)i == ordinalOfOverwrite) { //had been using sensor_sub_type
transmissionString = transmissionString + nullifyOrNumber(value);
}
transmissionString = transmissionString + "*";
}
*/
//note, if temperature ends up being NULL, the record won't save. might want to tweak data.php to save records if it contains SOME data
if(powerPin > -1) {
digitalWrite(powerPin, LOW);
}
} else if (sensor_id == 53) { //distance sensor, does not produce weather data
VL53L0X_RangingMeasurementData_t measure;
lox[objectCursor].rangingTest(&measure, false); // pass in 'true' to get debug data printout!
if (measure.RangeStatus != 4) { // phase failures have incorrect data
sensorValue = String(measure.RangeMilliMeter);
} else {
sensorValue = "-1";
}
} else if (sensor_id == 680) { //this is the primo sensor chip, so the trouble is worth it
//BME680 code:
BME680[objectCursor].getSensorData(temperatureRaw, humidityRaw, pressureRaw, gasRaw);
//i'm not sure what all this is about, since i just copied it from the BME680 example:
sprintf(buf, "%4d %3d.%02d", (loopCounter - 1) % 9999, // Clamp to 9999,
(int8_t)(temperatureRaw / 100), (uint8_t)(temperatureRaw % 100)); // Temp in decidegrees
//Serial.print(buf);
sprintf(buf, "%3d.%03d", (int8_t)(humidityRaw / 1000),
(uint16_t)(humidityRaw % 1000)); // Humidity milli-pct
//Serial.print(buf);
sprintf(buf, "%7d.%02d", (int16_t)(pressureRaw / 100),
(uint8_t)(pressureRaw % 100)); // Pressure Pascals
//Serial.print(buf);
//Serial.print(buf);
sprintf(buf, "%4d.%02d\n", (int16_t)(gasRaw / 100), (uint8_t)(gasRaw % 100)); // Resistance milliohms
//Serial.print(buf);
humidityFromSensor = (double)humidityRaw/1000;
temperatureFromSensor = (double)temperatureRaw/100;
pressureFromSensor = (double)pressureRaw/100;
gasFromSensor = (double)gasRaw/100; //all i ever get for this is 129468.6 and 8083.7
} else if (sensor_id == 2301) { //i love the humble DHT
if(powerPin > -1) {
digitalWrite(powerPin, HIGH); //turn on DHT power, in case you're doing that.
}
delay(10);
humidityFromSensor = (double)dht[objectCursor]->readHumidity();
temperatureFromSensor = (double)dht[objectCursor]->readTemperature();
if(powerPin > -1) {
digitalWrite(powerPin, LOW);//turn off DHT power. maybe it saves energy, and that's why MySpool did it this way
}
} else if(sensor_id == 280) {
temperatureFromSensor = BMP280[objectCursor].readTemperature();
pressureFromSensor = BMP280[objectCursor].readPressure()/100;
} else if(sensor_id == 2320) { //AHT20
sensors_event_t humidity, temp;
AHT[objectCursor].getEvent(&humidity, &temp);
humidityFromSensor = humidity.relative_humidity;
temperatureFromSensor = temp.temperature;
} else if(sensor_id == 7410) {
temperatureFromSensor = adt7410[objectCursor].readTempC();
} else if(sensor_id == 180) { //so much trouble for a not-very-good sensor
char status;
double p0,a;
status = BMP180[objectCursor].startTemperature();
if (status != 0)
{
// Wait for the measurement to complete:
delay(status);
// Retrieve the completed temperature measurement:
// Note that the measurement is stored in the variable T.
// Function returns 1 if successful, 0 if failure.
status = BMP180[objectCursor].getTemperature(temperatureFromSensor);
if (status != 0)
{
status = BMP180[objectCursor].startPressure(3);
if (status != 0)
{
// Wait for the measurement to complete:
delay(status);
// Retrieve the completed pressure measurement:
// Note that the measurement is stored in the variable P.
// Note also that the function requires the previous temperature measurement (temperatureValue).
// (If temperature is stable, you can do one temperature measurement for a number of pressure measurements.)
// Function returns 1 if successful, 0 if failure.
status = BMP180[objectCursor].getPressure(pressureFromSensor,temperatureFromSensor);
if (status == 0) {
//Serial.println("error retrieving pressure measurement\n");
}
} else {
//Serial.println("error starting pressure measurement\n");
}
} else {
//Serial.println("error retrieving temperature measurement\n");
}
} else {
//Serial.println("error starting temperature measurement\n");
}
} else if (sensor_id == 85) {
//https://github.com/adafruit/Adafruit-BMP085-Library
temperatureFromSensor = BMP085d[objectCursor].readTemperature();
pressureFromSensor = BMP085d[objectCursor].readPressure()/100; //to get millibars!
} else if (sensor_id == 75) { //LM75, so ghetto
//https://electropeak.com/learn/interfacing-lm75-temperature-sensor-with-arduino/
temperatureFromSensor = LM75[objectCursor].readTemperatureC();
} else { //either sensor_id is NULL or 0
//no sensor at all
}
//ordinalOfOverwrite allows us to take the temperature (and other values) from one of the previous sensors and place it in an arbitrary position of the delimited string
if(ordinalOfOverwrite < 0) {
temperatureValue = temperatureFromSensor;
pressureValue = pressureFromSensor;
humidityValue = humidityFromSensor;
gasValue = gasFromSensor;
} else {
if(sensorValue == NULL) {
if(sensor_sub_type == 1){
sensorValue = String(pressureFromSensor);
} else if (sensor_sub_type == 2){
sensorValue = String(humidityFromSensor);
} else if (sensor_sub_type == 3){
sensorValue = String(gasFromSensor);
} else {
sensorValue = String(temperatureFromSensor);
}
}
}
//
if(sensor_id > 0) {
transmissionString = nullifyOrNumber(temperatureValue) + "*" + nullifyOrNumber(pressureValue);
transmissionString = transmissionString + "*" + nullifyOrNumber(humidityValue);
transmissionString = transmissionString + "*" + nullifyOrNumber(gasValue);
transmissionString = transmissionString + "*********"; //for esoteric weather sensors that measure wind and precipitation. the last four are reserved for now
if(offlineMode) {
if(millis() - lastOfflineLog > 1000 * offline_log_granularity) {
long millisVal = millis();
//store that data in the FRAM:
std::vector<std::tuple<uint8_t, uint8_t, double>> framWeatherRecord;
addOfflineRecord(framWeatherRecord, 0, 5, temperatureValue);
addOfflineRecord(framWeatherRecord, 1, 5, pressureValue);
addOfflineRecord(framWeatherRecord, 2, 5, humidityValue);
//addOfflineRecord(framWeatherRecord, 28, 2, (double)millis());
if(rtc_address > 0) {
addOfflineRecord(framWeatherRecord, 40, 2, currentRTCTimestamp());
} else {
addOfflineRecord(framWeatherRecord, 40, 2, timeClient.getEpochTime());
}
//addOfflineRecord(framWeatherRecord, 8, 6, 3.141592653872233);
writeRecordToFRAM(framWeatherRecord);
Serial.println("Saved a record to FRAM.");
Serial.print(transmissionString);
Serial.println(millisVal);
//Serial.println("stored millis:");
//printHexBytes(millisVal);
lastOfflineLog = millis();
}
}
}
//using delimited data instead of JSON to keep things simple
transmissionString = transmissionString + nullifyOrInt(sensor_id) + "*" + nullifyOrInt(deviceFeatureId) + "*" + sensorName + "*" + nullifyOrInt(consolidateAllSensorsToOneRecord);
if(ordinalOfOverwrite > -1) {
transmissionString = replaceNthElement(transmissionString, ordinalOfOverwrite, sensorValue, '*');
}
return transmissionString;
}
void startWeatherSensors(int sensorIdLocal, int sensorSubTypeLocal, int i2c, int pinNumber, int powerPin) {
//i've made all these inputs generic across different sensors, though for now some apply and others do not on some sensors
//for example, you can set the i2c address of a BME680 or a BMP280 but not a BMP180. you can specify any GPIO as a data pin for a DHT
int objectCursor = 0;
if(sensorObjectCursor->has((String)sensor_id)) {
objectCursor = sensorObjectCursor->get((String)sensorIdLocal);;
}
if(sensorIdLocal == 1) { //simple analog input
//all we need to do is turn on power to whatever the analog device is
if(powerPin > -1) {
pinMode(powerPin, OUTPUT);
digitalWrite(powerPin, LOW);
}
/*
//if i implemented an IR transmitter as a weather device:
} else if(sensorIdLocal == 2) { //IR sender LED, not weather equipment, but a device certainly
//we don't need the objectCursor system because there will only ever be one ir sender diode
if(pinNumber > -1) {
irsend.begin();
}
*/
} else if(sensorIdLocal == 53) {
if(!lox[objectCursor].begin(i2c)) {
Serial.println(F("Failed to boot VL53L0X"));
} else {
Serial.print(F("VL53L0X at "));
Serial.println(i2c);
}
} else if(sensorIdLocal == 680) {
Serial.print(F("Initializing BME680 sensor...\n"));
while (!BME680[objectCursor].begin(I2C_STANDARD_MODE, i2c)) { // Start B DHTME680 using I2C, use first device found
Serial.print(F(" - Unable to find BME680.\n"));
} // of loop until device is located
Serial.print(F("- Setting 16x oversampling for all sensors\n"));
BME680[objectCursor].setOversampling(TemperatureSensor, Oversample16); // Use enumerated type values
BME680[objectCursor].setOversampling(HumiditySensor, Oversample16); // Use enumerated type values
BME680[objectCursor].setOversampling(PressureSensor, Oversample16); // Use enumerated type values
//Serial.print(F("- Setting IIR filter to a value of 4 samples\n"));
BME680[objectCursor].setIIRFilter(IIR4); // Use enumerated type values
//Serial.print(F("- Setting gas measurement to 320\xC2\xB0\x43 for 150ms\n")); // "?C" symbols
BME680[objectCursor].setGas(320, 150); // 320?c for 150 milliseconds
} else if (sensorIdLocal == 2301) {
Serial.print(F("Initializing DHT AM2301 sensor at pin: "));
if(powerPin > -1) {
pinMode(powerPin, OUTPUT);
digitalWrite(powerPin, LOW);
}
dht[objectCursor] = new DHT(pinNumber, sensorSubTypeLocal);
dht[objectCursor]->begin();
} else if (sensorIdLocal == 2320) { //AHT20
if (AHT[objectCursor].begin()) {
Serial.println("Found AHT20");
} else {
Serial.println("Didn't find AHT20");
}
} else if (sensorIdLocal == 7410) { //adt7410
adt7410[objectCursor].begin(i2c);
adt7410[objectCursor].setResolution(ADT7410_16BIT);
} else if (sensorIdLocal == 180) { //BMP180
BMP180[objectCursor].begin();
} else if (sensorIdLocal == 85) { //BMP085
Serial.print(F("Initializing BMP085...\n"));
BMP085d[objectCursor].begin();
} else if (sensorIdLocal == 280) {
Serial.print("Initializing BMP280 at i2c: ");
Serial.print((int)i2c);
Serial.print(" objectcursor:");
Serial.print((int)objectCursor);
Serial.println();
if(!BMP280[objectCursor].begin(i2c)){
Serial.println("Couldn't find BMX280!");
}
}
sensorObjectCursor->put((String)sensorIdLocal, objectCursor + 1); //we keep track of how many of a particular sensor_id we use
}
void handleWeatherData() {
String transmissionString = "";
if(ipAddress.indexOf(' ') > 0) { //i was getting HTML header info mixed in for some reason
ipAddress = ipAddress.substring(0, ipAddress.indexOf(' '));
}
String ipAddressToUse = ipAddress;
if(ipAddressAffectingChange != "") {
ipAddressToUse = ipAddressAffectingChange;
changeSourceId = 1;
}
int deviceFeatureId = 0;
if(onePinAtATimeMode) {
pinCursor++;
if(pinCursor >= pinTotal) {
pinCursor = 0;
}
}
if(sensor_id > -1) {
transmissionString = weatherDataString(sensor_id, sensor_sub_type, sensor_data_pin, sensor_power_pin, sensor_i2c, NULL, 0, deviceName, -1, consolidate_all_sensors_to_one_record);
}
//add the data for any additional sensors, delimited by '!' for each sensor
String additionalSensorData = handleDeviceNameAndAdditionalSensors((char *)additionalSensorInfo.c_str(), false);
if(transmissionString == "") {
additionalSensorData = additionalSensorData.substring(1); //trim off leading "!" if there is no default sensor data
}
transmissionString = transmissionString + additionalSensorData;
//the time-stamps of connection failures, delimited by *
transmissionString = transmissionString + "|" + joinValsOnDelimiter(moxeeRebootTimes, "*", 10);
//the values of the pins as the microcontroller understands them, delimited by *, in the order of the pin_list provided by the server
transmissionString = transmissionString + "|" + joinMapValsOnDelimiter(pinMap, "*", pinTotal); //also send pin as they are known back to the server
//other server-relevant info as needed, delimited by *
transmissionString = transmissionString + "|" + lastCommandId + "*" + pinCursor + "*" + (int)localSource + "*" + ipAddressToUse + "*" + (int)requestNonJsonPinInfo + "*" + (int)justDeviceJson + "*" + changeSourceId + "*" + timeClient.getEpochTime();
transmissionString = transmissionString + "*" + millis(); //so we can know how long the gizmo has been up
transmissionString = transmissionString + "*";
if(latencyCount > 0) {
transmissionString = transmissionString + (1000 * latencySum)/latencyCount;
}
transmissionString = transmissionString + "|*" + measuredVoltage + "*" + measuredAmpage; //if this device could timestamp data from its archives, it would put the numeric timetamp before measuredVoltage
//transmissionString = transmissionString + "*" + latitude + "*" + longitude; //not yet supported. might also include accelerometer data some day
//Serial.println(transmissionString);
//had to use a global, died a little inside
if(glblRemote) {
if(!offlineMode) {
sendRemoteData(transmissionString);
}
} else {
server.send(200, "text/plain", transmissionString); //Send values only to client ajax request
}
}
void wiFiConnect() {
WiFi.persistent(false); //hopefully keeps my flash from being corrupted, see: https://rayshobby.net/wordpress/esp8266-reboot-cycled-caused-by-flash-memory-corruption-fixed/
WiFi.begin(wifi_ssid, wifi_password);
Serial.println();
// Wait for connection
int wiFiSeconds = 0;
bool initialAttemptPhase = true;
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.print(".");
wiFiSeconds++;
if(wiFiSeconds > wifi_timeout) {
Serial.println("WiFi taking too long, rebooting Moxee");
rebootMoxee();
wiFiSeconds = 0; //if you don't do this, you'll be stuck in a rebooting loop if WiFi fails once
initialAttemptPhase = false;
}
if(!initialAttemptPhase && wiFiSeconds > (wifi_timeout/2)) {
//give up for the time being
offlineMode = true;
Serial.print("Entering offline mode...");
return;
}
}
Serial.println("");
Serial.print("Connected to ");
Serial.println(wifi_ssid);
Serial.print("IP address: ");
ipAddress = WiFi.localIP().toString();
Serial.println(WiFi.localIP()); //IP address assigned to your ESP
}
//SEND DATA TO A REMOTE SERVER TO STORE IN A DATABASE----------------------------------------------------
void sendRemoteData(String datastring) {
WiFiClient clientGet;
const int httpGetPort = 80;
String url;
String mode = "getDeviceData";
//most of the time we want to getDeviceData, not saveData. the former picks up remote control activity. the latter sends sensor data
if(millis() - lastDataLogTime > data_logging_granularity * 1000 || lastDataLogTime == 0) {
mode = "saveData";
}
if(deviceName == "") {
mode = "getInitialDeviceInfo";
}
String encryptedStoragePassword = encryptStoragePassword(datastring);
url = (String)url_get + "?key=" + encryptedStoragePassword + "&device_id=" + device_id + "&mode=" + mode + "&data=" + urlEncode(datastring, true);
Serial.println("\r>>> Connecting to host: ");
//Serial.println(host_get);
int attempts = 0;
while(!clientGet.connect(host_get, httpGetPort) && attempts < connection_retry_number) {
attempts++;
delay(200);
}
Serial.print("Connection attempts: ");
Serial.print(attempts);
Serial.println();
if (attempts >= connection_retry_number) {
Serial.print("Connection failed, moxee rebooted: ");
connectionFailureTime = millis();
connectionFailureMode = true;
rebootMoxee();
Serial.print(host_get);
Serial.println();
} else {
connectionFailureTime = 0;
connectionFailureMode = false;
Serial.println(url);
clientGet.println("GET " + url + " HTTP/1.1");
clientGet.print("Host: ");
clientGet.println(host_get);
clientGet.println("User-Agent: ESP8266/1.0");
clientGet.println("Accept-Encoding: identity");
clientGet.println("Connection: close\r\n\r\n");
unsigned long timeoutP = millis();
while (clientGet.available() == 0) {
if (millis() - timeoutP > 10000) {
//let's try a simpler connection and if that fails, then reboot moxee
//clientGet.stop();
if(clientGet.connect(host_get, httpGetPort)){
clientGet.println("GET / HTTP/1.1");
clientGet.print("Host: ");
clientGet.println(host_get);
clientGet.println("User-Agent: ESP8266/1.0");
clientGet.println("Accept-Encoding: identity");
clientGet.println("Connection: close\r\n\r\n");
}//if (clientGet.connect(
//clientGet.stop();
return;
} //if( millis() -
}
delay(1); //see if this improved data reception. OMG IT TOTALLY WORKED!!!
bool receivedData = false;
bool receivedDataJson = false;
if(clientGet.available() && ipAddressAffectingChange != "") { //don't turn these globals off until we have data back from the server
ipAddressAffectingChange = "";
changeSourceId = 0;
}
while(clientGet.available()){
receivedData = true;
String retLine = clientGet.readStringUntil('\n');
retLine.trim();
//Here the code is designed to be able to handle either JSON or double-delimited data from data.php
//I started with just JSON, but that's a notoriously bulky data format, what with the names of all the
//entities embedded and the overhead of quotes and brackets. This is a problem because when the
//amount of data being sent by my server reached some critical threshold (I'm not sure what it is!)
//it automatically gzipped the data, which I couldn't figure out how to unzip on a ESP8266.
//So then I made a system of sending only some of the data at a time via JSON. That introduced a lot of
//complexity and also made the system less responsive, since you now had to wait for the device_feature to
//get its turn in a fairly slow round-robin (on a slow internet connection, it would take ten seconds per item).
//So that's why I implemented the non-JSON data format, which can easily specify the values for all
//device_features in one data object (assuming it's not too big). The ESP8266 still can respond to data in the
//JSON format, which it will assume if the first character of the data is a '{' -- but if the first character
//is a '|' then it assumes the data is non-JSON. Otherwise it assumes it's HTTP boilerplate and ignores it.
if(retLine.indexOf("\"error\":") < 0 && mode == "saveData" && (retLine.charAt(0)== '{' || retLine.charAt(0)== '*' || retLine.charAt(0)== '|' || retLine.charAt(0)== '|')) {
Serial.println("can sleep because: ");
Serial.println(retLine);
Serial.println(retLine.indexOf("error:"));
lastDataLogTime = millis();
canSleep = true; //canSleep is a global and will not be set until all the tasks of the device are finished.
}
if(retLine.charAt(0) == '*') { //getInitialDeviceInfo
Serial.print("Initial Device Data: ");
Serial.println(retLine);
//set the global string; we'll just use that to store our data about addtional sensors
if(sensor_config_string != "") {
retLine = replaceFirstOccurrenceAtChar(retLine, String(sensor_config_string), '|');
//retLine = retLine + "|" + String(sensor_config_string); //had been doing it this way; not as good!
}
additionalSensorInfo = retLine;
//once we have it
handleDeviceNameAndAdditionalSensors((char *)additionalSensorInfo.c_str(), true);
break;
} else if(retLine.charAt(0) == '{') {
Serial.print("JSON: ");
Serial.println(retLine);
setLocalHardwareToServerStateFromJson((char *)retLine.c_str());
receivedDataJson = true;
break;
} else if(retLine.charAt(0) == '|') {
Serial.print("non-JSON: ");
Serial.println(retLine);
String serverCommandParts[2];
splitString(retLine, '!', serverCommandParts, 2);
setLocalHardwareToServerStateFromNonJson((char *)serverCommandParts[0].c_str());
if(retLine.indexOf("!") > -1) {
if(serverCommandParts[1].length()>5) { //just has latency data
Serial.print("COMMAND (beside pin data): ");
Serial.println(serverCommandParts[1]);
}
runCommandsFromNonJson((char *)("!" + serverCommandParts[1]).c_str());
}
receivedDataJson = true;
break;
} else if(retLine.charAt(0) == '!') { //it's a command, so an exclamation point seems right
Serial.print("COMMAND: ");
Serial.println(retLine);
runCommandsFromNonJson((char *)retLine.c_str());
break;
} else {
Serial.print("non-readable line returned: ");
Serial.println(retLine);
}
}
if(receivedData && !receivedDataJson) { //an indication our server is gzipping data needed for remote control. So instead pull it down one pin at a time and hopefully get under the gzip cutoff
onePinAtATimeMode = true;
}
} //if (attempts >= connection_retry_number)....else....
clientGet.stop();
}
String handleDeviceNameAndAdditionalSensors(char * sensorData, bool intialize){
String additionalSensorArray[12];
String specificSensorData[8];
int i2c;
int pinNumber;
int powerPin;
int sensorIdLocal;
int sensorSubTypeLocal;
int deviceFeatureId;
int consolidateAllSensorsToOneRecord = 0;
String out = "";
int objectCursor = 0;
int oldsensor_id = -1;
int ordinalOfOverwrite = 0;
String sensorName;
splitString(sensorData, '|', additionalSensorArray, 12);
deviceName = additionalSensorArray[0].substring(1);
requestNonJsonPinInfo = 1; //set this global
for(int i=1; i<12; i++) {
String sensorDatum = additionalSensorArray[i];
if(sensorDatum.indexOf('*')>-1) {
splitString(sensorDatum, '*', specificSensorData, 8);
pinNumber = specificSensorData[0].toInt();
powerPin = specificSensorData[1].toInt();
sensorIdLocal = specificSensorData[2].toInt();
sensorSubTypeLocal = specificSensorData[3].toInt();
i2c = specificSensorData[4].toInt();
deviceFeatureId = specificSensorData[5].toInt();
sensorName = specificSensorData[6];
ordinalOfOverwrite = specificSensorData[7].toInt();
consolidateAllSensorsToOneRecord = specificSensorData[8].toInt();
if(oldsensor_id != sensorIdLocal) { //they're sorted by sensor_id, so the objectCursor needs to be set to zero if we're seeing the first of its type
objectCursor = 0;
}
if(sensorIdLocal == sensor_id) { //this particular additional sensor is the same type as the base (non-additional) sensor, so we have to pre-start it higher
objectCursor++;
}
if(intialize) {
startWeatherSensors(sensorIdLocal, sensorSubTypeLocal, i2c, pinNumber, powerPin); //guess i have to pass all this additional info
} else {
//otherwise do a weatherDataString
out = out + "!" + weatherDataString(sensorIdLocal, sensorSubTypeLocal, pinNumber, powerPin, i2c, deviceFeatureId, objectCursor, sensorName, ordinalOfOverwrite, consolidateAllSensorsToOneRecord);
}
objectCursor++;
oldsensor_id = sensorIdLocal;
}
}
return out;
}
//if the backend sends too much text data at once, it is likely to get gzipped, which is hard to deal with on a microcontroller with limited resources
//so a better strategy is to send double-delimited data instead of JSON, with data consistently in known ordinal positions
//thereby making the data payloads small enough that the server never gzips them
//i've made it so the ESP8266 can receive data in either format. it takes the lead on specifying which format it prefers
//but if it misbehaves, i can force it to be one format or the other remotely
void setLocalHardwareToServerStateFromNonJson(char * nonJsonLine){
int pinNumber = 0;
String key;
int value = -1;
int canBeAnalog = 0;
int enabled = 0;
int pinCounter = 0;
int serverSaved = 0;
String friendlyPinName = "";
String nonJsonPinArray[12];
String nonJsonDatumString;
String nonJsonPinDatum[5];
String pinIdParts[2];
char i2c = 0;
splitString(nonJsonLine, '|', nonJsonPinArray, 12);
int foundPins = 0;
for(int i=1; i<12; i++) {
nonJsonDatumString = nonJsonPinArray[i];
if(nonJsonDatumString.indexOf('*')>-1) {
splitString(nonJsonDatumString, '*', nonJsonPinDatum, 5);
key = nonJsonPinDatum[1];
friendlyPinName = nonJsonPinDatum[0];
value = nonJsonPinDatum[2].toInt();
pinName[foundPins] = friendlyPinName;
canBeAnalog = nonJsonPinDatum[3].toInt();
serverSaved = nonJsonPinDatum[4].toInt();
if(key.indexOf('.')>0) {
splitString(key, '.', pinIdParts, 2);
i2c = pinIdParts[0].toInt();
pinNumber = pinIdParts[1].toInt();
} else {
pinNumber = key.toInt();
}
//Serial.println("!ABOUT TO TURN OF localsource: " + (String)localSource + " serverSAVED: " + (String)serverSaved);
if(!localSource || serverSaved == 1){
if(serverSaved == 1) {//confirmation of serverSaved, so localSource flag is no longer needed
Serial.println("SERVER SAVED==1!!");
localSource = false;
} else {
pinMap->remove(key);
pinMap->put(key, value);
}
}
pinList[foundPins] = key;
pinMode(pinNumber, OUTPUT);
if(i2c > 0) {
//Serial.print("Non-JSON i2c: ");
//Serial.println(key);
setPinValueOnSlave(i2c, (char)pinNumber, (char)value);
} else {
if(canBeAnalog) {
analogWrite(pinNumber, value);
} else {
//Serial.print("Non-JSON reg: ");
//Serial.println(key);
if(value > 0) {
digitalWrite(pinNumber, HIGH);
} else {
digitalWrite(pinNumber, LOW);
}
}
}
}
foundPins++;
}
pinTotal = foundPins;
}
//this will set any pins specified in the JSON
void setLocalHardwareToServerStateFromJson(char * json){
if(millis() - localChangeTime < 1000) { //don't accept any server values withing 5 seconds of a local change
return;
}
char * nodeName="device_data";
int pinNumber = 0;
int value = -1;
int canBeAnalog = 0;
int enabled = 0;
int pinCounter = 0;
int serverSaved = 0;
String friendlyPinName = "";
char i2c = 0;
DeserializationError error = deserializeJson(jsonBuffer, json);
if(jsonBuffer["device"]) { //deviceName is a global
deviceName = (String)jsonBuffer["device"];
Serial.println("DEVICE: " + deviceName);
//once we have deviceName, we can get data this way:
requestNonJsonPinInfo = 1;
}
if(jsonBuffer[nodeName]) {
pinCounter = 0;
if(!onePinAtATimeMode) {
pinMap->clear(); //this won't work
}
for(int i=0; i<jsonBuffer[nodeName].size(); i++) {
friendlyPinName = (String)jsonBuffer[nodeName][i]["name"];
pinNumber = (int)jsonBuffer[nodeName][i]["pin_number"];
value = (int)jsonBuffer[nodeName][i]["value"];
canBeAnalog = (int)jsonBuffer["nodeName"][i]["can_be_analog"];
enabled = (int)jsonBuffer[nodeName][i]["enabled"];
serverSaved = (int)jsonBuffer[nodeName][i]["ss"];
i2c = (int)jsonBuffer[nodeName][i]["i2c"];
if(i2c > 0) {
i2c = 0;
}
Serial.print("pin: ");
Serial.print(pinNumber);
Serial.print("; value: ");
Serial.print(value);
Serial.println();
pinMode(pinNumber, OUTPUT);
if(enabled) {
for(char j=0; j<pinTotal; j++){
String key;
char sprintBuffer[6];
sprintf(sprintBuffer, "%d.%d", i2c, pinNumber);
key = (String)sprintBuffer;
if(i2c < 1){
key = (String)pinNumber;
}
//Serial.println("! " + (String)pinList[j] + " =?: " + key + " correcto? " + (int((String)pinList[j] == key)));
if(!localSource || serverSaved == 1){
if((String)pinList[j] == key) {
if(serverSaved == 1) {//confirmation of serverSaved, so localSource flag is no longer needed
Serial.println("SERVER SAVED==1!!");
localSource = false;
} else { //this will have the wrong value if serverSaved == 1
pinMap->remove(key);
pinMap->put(key, value);
}
pinName[j] = friendlyPinName;
}
}
}
if(i2c > 0) {
setPinValueOnSlave(i2c, (char)pinNumber, (char)value);
} else {
if(canBeAnalog) {
analogWrite(pinNumber, value);
} else {
if(value > 0) {
digitalWrite(pinNumber, HIGH);
} else {
digitalWrite(pinNumber, LOW);
}
}
}
}
pinCounter++;
}
}
nodeName="pin_list";
String pinString;
if(jsonBuffer[nodeName]) {
pinCounter = 0;
for(int i=0; i<jsonBuffer[nodeName].size(); i++) {
pinString = (String)jsonBuffer[nodeName][i];
pinList[pinCounter] = (String)pinString;
pinCounter++;
}
}
pinTotal = pinCounter;
}
long getPinValueOnSlave(char i2cAddress, char pinNumber) { //might want a user-friendlier API here
//reading an analog or digital value from the slave:
Wire.beginTransmission(i2cAddress);
Wire.write(pinNumber); //addresses greater than 64 are the same as AX (AnalogX) where X is 64-value
Wire.endTransmission();
delay(100);
Wire.requestFrom(i2cAddress, 4); //we only ever get back four-byte long ints
long totalValue = 0;
int byteCursor = 1;
while (Wire.available()) {
byte receivedValue = Wire.read(); // Read the received value from slave
totalValue = totalValue + receivedValue * pow(256, 4-byteCursor);
//Serial.println(receivedValue); // Print the received value
byteCursor++;
}
return totalValue;
}
void setPinValueOnSlave(char i2cAddress, char pinNumber, char pinValue) {
//if you have a slave Arduino set up with this code:
//https://github.com/judasgutenberg/Generic_Arduino_I2C_Slave
//and a device_type_feature specifies an i2c address
//then this code will send the data to that slave Arduino
/*
Serial.print((int)i2cAddress);
Serial.print(" ");
Serial.print((int)pinNumber);
Serial.print(" ");
Serial.print((int)pinValue);
Serial.println("");
*/
Wire.beginTransmission(i2cAddress);
Wire.write(pinNumber);
Wire.write(pinValue);
Wire.endTransmission();
}
//i don't want to use JSON because the format is too bulky:
/*
//this will run commands sent to the server
//still needs to be implemented on the backend. but if i need it, it's here
void runCommandsFromJson(char * json){
String command;
int commandId;
char * nodeName="commands";
DeserializationError error = deserializeJson(jsonBuffer, json);
if(jsonBuffer[nodeName]) {
Serial.print("number of commands: ");
Serial.print(jsonBuffer[nodeName].size());
Serial.println();
Serial.println();
for(int i=0; i<jsonBuffer[nodeName].size(); i++) {
command = (String)jsonBuffer[nodeName][i]["command"];
commandId = (int)jsonBuffer[nodeName][i]["commandId"];
//still have to run command!
if(command == "reboot") {
rebootEsp();
} else if(command == "allpinsatonce") {
onePinAtATimeMode = 0;
}
lastCommandId = commandId;
}
}
}
*/
void runCommandsFromNonJson(char * nonJsonLine){
//can change the default values of some config data for things like polling
String command;
int commandId;
String commandData;
String commandArray[4];
int latency;
//first get rid of the first character, since all it does is signal that we are receiving a command:
nonJsonLine++;
splitString(nonJsonLine, '|', commandArray, 3);
commandId = commandArray[0].toInt();
command = commandArray[1];
commandData = commandArray[2];
latencyCount++;
latency = commandArray[3].toInt();
latencySum += latency;
//Serial.println(commandId);
if(commandId) {
//Serial.println(command);
if(command == "reboot") {
rebootEsp();
} else if(command == "one pin at a time") {
onePinAtATimeMode = (boolean)commandData.toInt(); //setting a global.
} else if(command == "sleep seconds per loop") {
deep_sleep_time_per_loop = commandData.toInt(); //setting a global.
} else if(command == "snooze seconds per loop") {
light_sleep_time_per_loop = commandData.toInt(); //setting a global.
} else if(command == "polling granularity") {
polling_granularity = commandData.toInt(); //setting a global.
} else if(command == "logging granularity") {
data_logging_granularity = commandData.toInt(); //setting a global.
} else if(command == "clear latency average") {
latencyCount = 0;
latencySum = 0;
} else if(command == "ir") {
sendIr(commandData); //ir data must be comma-delimited
} else if(command == "clear fram") {