-
Notifications
You must be signed in to change notification settings - Fork 354
/
Copy pathtelelogger.ino
1385 lines (1275 loc) · 34.4 KB
/
telelogger.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
/******************************************************************************
* Arduino sketch of a vehicle data data logger and telemeter for Freematics Hub
* Works with Freematics ONE+ Model A and Model B
* Developed by Stanley Huang <[email protected]>
* Distributed under BSD license
* Visit https://freematics.com/products for hardware information
* Visit https://hub.freematics.com to view live and history telemetry data
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
******************************************************************************/
#include <FreematicsPlus.h>
#include <httpd.h>
#include "config.h"
#include "telelogger.h"
#include "telemesh.h"
#include "teleclient.h"
#if BOARD_HAS_PSRAM
#include "esp32/himem.h"
#endif
#include "driver/adc.h"
#if ENABLE_OLED
#include "FreematicsOLED.h"
#endif
// states
#define STATE_STORAGE_READY 0x1
#define STATE_OBD_READY 0x2
#define STATE_GPS_READY 0x4
#define STATE_MEMS_READY 0x8
#define STATE_NET_READY 0x10
#define STATE_NET_CONNECTED 0x20
#define STATE_WORKING 0x40
#define STATE_STANDBY 0x100
typedef struct {
byte pid;
byte tier;
int value;
uint32_t ts;
} PID_POLLING_INFO;
PID_POLLING_INFO obdData[]= {
{PID_SPEED, 1},
{PID_RPM, 1},
{PID_THROTTLE, 1},
{PID_ENGINE_LOAD, 1},
{PID_FUEL_PRESSURE, 2},
{PID_TIMING_ADVANCE, 2},
{PID_COOLANT_TEMP, 3},
{PID_INTAKE_TEMP, 3},
};
CBufferManager bufman;
Task subtask;
#if ENABLE_MEMS
float accBias[3] = {0}; // calibrated reference accelerometer data
float accSum[3] = {0};
float temp = 0;
float acc[3] = {0};
float gyr[3] = {0};
float mag[3] = {0};
uint8_t accCount = 0;
#endif
float deviceTemp = 0;
// live data
int16_t rssi = 0;
char vin[18] = {0};
uint16_t dtc[6] = {0};
int16_t batteryVoltage = 0;
GPS_DATA* gd = 0;
char devid[12] = {0};
char isoTime[32] = {0};
// stats data
uint32_t lastMotionTime = 0;
uint32_t timeoutsOBD = 0;
uint32_t timeoutsNet = 0;
uint32_t lastStatsTime = 0;
int32_t syncInterval = SERVER_SYNC_INTERVAL * 1000;
int32_t dataInterval = 1000;
#if STORAGE != STORAGE_NONE
int fileid = 0;
uint16_t lastSizeKB = 0;
#endif
uint32_t lastCmdToken = 0;
String serialCommand;
byte ledMode = 0;
bool serverSetup(IPAddress& ip);
void serverProcess(int timeout);
void processMEMS(CBuffer* buffer);
bool processGPS(CBuffer* buffer);
void processBLE(int timeout);
class State {
public:
bool check(uint16_t flags) { return (m_state & flags) == flags; }
void set(uint16_t flags) { m_state |= flags; }
void clear(uint16_t flags) { m_state &= ~flags; }
uint16_t m_state = 0;
};
FreematicsESP32 sys;
class OBD : public COBD
{
protected:
void idleTasks()
{
// do some quick tasks while waiting for OBD response
#if ENABLE_MEMS
processMEMS(0);
#endif
delay(5);
}
};
OBD obd;
MEMS_I2C* mems = 0;
#if STORAGE == STORAGE_SPIFFS
SPIFFSLogger logger;
#elif STORAGE == STORAGE_SD
SDLogger logger;
#endif
#if SERVER_PROTOCOL == PROTOCOL_UDP
TeleClientUDP teleClient;
#else
TeleClientHTTP teleClient;
#endif
#if ENABLE_OLED
OLED_SH1106 oled;
#endif
State state;
void printTimeoutStats()
{
Serial.print("Timeouts: OBD:");
Serial.print(timeoutsOBD);
Serial.print(" Network:");
Serial.println(timeoutsNet);
}
#if LOG_EXT_SENSORS
void processExtInputs(CBuffer* buffer)
{
int pids[] = {PID_EXT_SENSOR1, PID_EXT_SENSOR2};
#if LOG_EXT_SENSORS == 1
int pins[] = {PIN_SENSOR1, PIN_SENSOR2};
for (int i = 0; i < 2; i++) {
buffer->add(pids[i], digitalRead(pins[i]));
}
#elif LOG_EXT_SENSORS == 2
int reading[] = {adc1_get_raw(ADC1_CHANNEL_0), adc1_get_raw(ADC1_CHANNEL_1)};
Serial.print("GPIO0:");
Serial.print((float)reading[0] * 3.15 / 4095 - 0.01);
Serial.print(" GPIO1:");
Serial.println((float)reading[1] * 3.15 / 4095 - 0.01);
for (int i = 0; i < 2; i++) {
buffer->add(pids[i], reading[i]);
}
#endif
}
#endif
/*******************************************************************************
HTTP API
*******************************************************************************/
#if ENABLE_HTTPD
int handlerLiveData(UrlHandlerParam* param)
{
char *buf = param->pucBuffer;
int bufsize = param->bufSize;
int n = snprintf(buf, bufsize, "{\"obd\":{\"vin\":\"%s\",\"battery\":%.1f,\"pid\":[", vin, (float)batteryVoltage / 100);
uint32_t t = millis();
for (int i = 0; i < sizeof(obdData) / sizeof(obdData[0]); i++) {
n += snprintf(buf + n, bufsize - n, "{\"pid\":%u,\"value\":%d,\"age\":%u},",
0x100 | obdData[i].pid, obdData[i].value, (unsigned int)(t - obdData[i].ts));
}
n--;
n += snprintf(buf + n, bufsize - n, "]}");
#if ENABLE_MEMS
if (accCount) {
n += snprintf(buf + n, bufsize - n, ",\"mems\":{\"acc\":[%d,%d,%d],\"stationary\":%u}",
(int)((accSum[0] / accCount - accBias[0]) * 100), (int)((accSum[1] / accCount - accBias[1]) * 100), (int)((accSum[2] / accCount - accBias[2]) * 100),
(unsigned int)(millis() - lastMotionTime));
}
#endif
if (gd && gd->ts) {
n += snprintf(buf + n, bufsize - n, ",\"gps\":{\"utc\":\"%s\",\"lat\":%f,\"lng\":%f,\"alt\":%f,\"speed\":%f,\"sat\":%d,\"age\":%u}",
isoTime, gd->lat, gd->lng, gd->alt, gd->speed, (int)gd->sat, (unsigned int)(millis() - gd->ts));
}
buf[n++] = '}';
param->contentLength = n;
param->contentType=HTTPFILETYPE_JSON;
return FLAG_DATA_RAW;
}
#endif
/*******************************************************************************
Reading and processing OBD data
*******************************************************************************/
#if ENABLE_OBD
void processOBD(CBuffer* buffer)
{
static int idx[2] = {0, 0};
int tier = 1;
for (byte i = 0; i < sizeof(obdData) / sizeof(obdData[0]); i++) {
if (obdData[i].tier > tier) {
// reset previous tier index
idx[tier - 2] = 0;
// keep new tier number
tier = obdData[i].tier;
// move up current tier index
i += idx[tier - 2]++;
// check if into next tier
if (obdData[i].tier != tier) {
idx[tier - 2]= 0;
i--;
continue;
}
}
byte pid = obdData[i].pid;
if (!obd.isValidPID(pid)) continue;
int value;
if (obd.readPID(pid, value)) {
obdData[i].ts = millis();
obdData[i].value = value;
buffer->add((uint16_t)pid | 0x100, value);
} else {
timeoutsOBD++;
printTimeoutStats();
break;
}
processBLE(0);
if (tier > 1) break;
}
int kph = obdData[0].value;
if (kph >= 2) lastMotionTime = millis();
}
#endif
bool processGPS(CBuffer* buffer)
{
static uint32_t lastGPStime = 0;
static float lastGPSLat = 0;
static float lastGPSLng = 0;
if (!gd) {
lastGPStime = 0;
lastGPSLat = 0;
lastGPSLng = 0;
}
#if GNSS == GNSS_INTERNAL || GNSS == GNSS_EXTERNAL
if (state.check(STATE_GPS_READY)) {
// read parsed GPS data
if (!sys.gpsGetData(&gd)) {
return false;
}
}
#elif NET_DEVICE >= NET_SIM5360
if (!teleClient.net.getLocation(&gd)) {
return false;
}
#endif
if (!gd || lastGPStime == gd->time || gd->date == 0 || (gd->lng == 0 && gd->lat == 0)) return false;
if ((lastGPSLat || lastGPSLng) && (abs(gd->lat - lastGPSLat) > 0.001 || abs(gd->lng - lastGPSLng > 0.001))) {
// invalid coordinates data
lastGPSLat = 0;
lastGPSLng = 0;
return false;
}
lastGPSLat = gd->lat;
lastGPSLng = gd->lng;
float kph = (float)((int)(gd->speed * 1.852f * 10)) / 10;
if (kph >= 2) lastMotionTime = millis();
if (buffer) {
buffer->add(PID_GPS_DATE, gd->date);
buffer->add(PID_GPS_TIME, gd->time);
if (gd->lat && gd->lng && gd->alt) {
buffer->add(PID_GPS_LATITUDE, gd->lat);
buffer->add(PID_GPS_LONGITUDE, gd->lng);
buffer->add(PID_GPS_ALTITUDE, gd->alt); /* m */
buffer->add(PID_GPS_SPEED, kph);
buffer->add(PID_GPS_HEADING, gd->heading);
buffer->add(PID_GPS_SAT_COUNT, gd->sat);
buffer->add(PID_GPS_HDOP, gd->hdop);
}
}
// generate ISO time string
char *p = isoTime + sprintf(isoTime, "%04u-%02u-%02uT%02u:%02u:%02u",
(unsigned int)(gd->date % 100) + 2000, (unsigned int)(gd->date / 100) % 100, (unsigned int)(gd->date / 10000),
(unsigned int)(gd->time / 1000000), (unsigned int)(gd->time % 1000000) / 10000, (unsigned int)(gd->time % 10000) / 100);
unsigned char tenth = (gd->time % 100) / 10;
if (tenth) p += sprintf(p, ".%c00", '0' + tenth);
*p = 'Z';
*(p + 1) = 0;
Serial.print("[GPS] ");
Serial.print(gd->lat, 6);
Serial.print(' ');
Serial.print(gd->lng, 6);
Serial.print(' ');
Serial.print((int)kph);
Serial.print("km/h");
if (gd->sat) {
Serial.print(" SATS:");
Serial.print(gd->sat);
}
Serial.print(" Course:");
Serial.print(gd->heading);
Serial.print(' ');
Serial.println(isoTime);
//Serial.println(gd->errors);
lastGPStime = gd->time;
return true;
}
bool waitMotionGPS(int timeout)
{
unsigned long t = millis();
lastMotionTime = 0;
do {
serverProcess(100);
if (!processGPS(0)) continue;
if (lastMotionTime) return true;
} while (millis() - t < timeout);
return false;
}
#if ENABLE_MEMS
void processMEMS(CBuffer* buffer)
{
if (!state.check(STATE_MEMS_READY)) return;
// load and store accelerometer data
#if ENABLE_ORIENTATION
ORIENTATION ori;
if (!mems->read(acc, gyr, mag, &temp, &ori)) return;
#else
if (!mems->read(acc, gyr, mag, &temp)) return;
#endif
accSum[0] += acc[0];
accSum[1] += acc[1];
accSum[2] += acc[2];
accCount++;
if (buffer) {
if (accCount) {
float value[3];
value[0] = accSum[0] / accCount - accBias[0];
value[1] = accSum[1] / accCount - accBias[1];
value[2] = accSum[2] / accCount - accBias[2];
buffer->add(PID_ACC, value);
#if ENABLE_ORIENTATION
value[0] = ori.yaw;
value[1] = ori.pitch;
value[2] = ori.roll;
buffer->add(PID_ORIENTATION, value);
#endif
if (temp != deviceTemp) {
deviceTemp = temp;
buffer->add(PID_DEVICE_TEMP, (int)temp);
}
#if 0
// calculate motion
float motion = 0;
for (byte i = 0; i < 3; i++) {
motion += value[i] * value[i];
}
if (motion >= MOTION_THRESHOLD * MOTION_THRESHOLD) {
lastMotionTime = millis();
Serial.print("Motion:");
Serial.println(motion);
}
#endif
}
accSum[0] = 0;
accSum[1] = 0;
accSum[2] = 0;
accCount = 0;
}
}
void calibrateMEMS()
{
if (state.check(STATE_MEMS_READY)) {
accBias[0] = 0;
accBias[1] = 0;
accBias[2] = 0;
int n;
unsigned long t = millis();
for (n = 0; millis() - t < 1000; n++) {
float acc[3];
if (!mems->read(acc)) continue;
accBias[0] += acc[0];
accBias[1] += acc[1];
accBias[2] += acc[2];
delay(10);
}
accBias[0] /= n;
accBias[1] /= n;
accBias[2] /= n;
Serial.print("ACC BIAS:");
Serial.print(accBias[0]);
Serial.print('/');
Serial.print(accBias[1]);
Serial.print('/');
Serial.println(accBias[2]);
}
}
#endif
void printTime()
{
time_t utc;
time(&utc);
struct tm *btm = gmtime(&utc);
if (btm->tm_year > 100) {
// valid system time available
char buf[64];
sprintf(buf, "%04u-%02u-%02u %02u:%02u:%02u",
1900 + btm->tm_year, btm->tm_mon + 1, btm->tm_mday, btm->tm_hour, btm->tm_min, btm->tm_sec);
Serial.print("UTC:");
Serial.println(buf);
}
}
/*******************************************************************************
Initializing all data logging components
*******************************************************************************/
void initialize()
{
// turn on buzzer at 2000Hz frequency
sys.buzzer(2000);
delay(100);
// turn off buzzer
sys.buzzer(0);
// dump buffer data
bufman.purge();
#if ENABLE_MEMS
if (state.check(STATE_MEMS_READY)) {
calibrateMEMS();
}
#endif
#if GNSS == GNSS_INTERNAL || GNSS == GNSS_EXTERNAL
// start GPS receiver
if (!state.check(STATE_GPS_READY)) {
Serial.print("GNSS:");
#if GNSS == GNSS_EXTERNAL
if (sys.gpsBegin())
#else
if (sys.gpsBegin(0))
#endif
{
state.set(STATE_GPS_READY);
Serial.println("OK");
#if ENABLE_OLED
oled.println("GNSS OK");
#endif
} else {
Serial.println("NO");
}
}
#endif
#if ENABLE_OBD
// initialize OBD communication
if (!state.check(STATE_OBD_READY)) {
timeoutsOBD = 0;
if (obd.init()) {
Serial.println("OBD:OK");
state.set(STATE_OBD_READY);
#if ENABLE_OLED
oled.println("OBD OK");
#endif
} else {
Serial.println("OBD:NO");
//state.clear(STATE_WORKING);
//return;
}
}
#endif
#if STORAGE != STORAGE_NONE
if (!state.check(STATE_STORAGE_READY)) {
// init storage
if (logger.init()) {
state.set(STATE_STORAGE_READY);
}
}
if (state.check(STATE_STORAGE_READY)) {
fileid = logger.begin();
}
#endif
// re-try OBD if connection not established
#if ENABLE_OBD
if (state.check(STATE_OBD_READY)) {
char buf[128];
if (obd.getVIN(buf, sizeof(buf))) {
memcpy(vin, buf, sizeof(vin) - 1);
Serial.print("VIN:");
Serial.println(vin);
}
int dtcCount = obd.readDTC(dtc, sizeof(dtc) / sizeof(dtc[0]));
if (dtcCount > 0) {
Serial.print("DTC:");
Serial.println(dtcCount);
}
#if ENABLE_OLED
oled.print("VIN:");
oled.println(vin);
#endif
}
#endif
// check system time
printTime();
lastMotionTime = millis();
state.set(STATE_WORKING);
#if ENABLE_OLED
delay(1000);
oled.clear();
oled.print("DEVICE ID: ");
oled.println(devid);
oled.setCursor(0, 7);
oled.print("Packets");
oled.setCursor(80, 7);
oled.print("KB Sent");
oled.setFontSize(FONT_SIZE_MEDIUM);
#endif
}
void showStats()
{
uint32_t t = millis() - teleClient.startTime;
char buf[32];
#if ENABLE_BLE
int len = sprintf(buf, "T:%u P:%u B:%u", t, teleClient.txCount, teleClient.txBytes);
#endif
sprintf(buf, "%02u:%02u.%c ", t / 60000, (t % 60000) / 1000, (t % 1000) / 100 + '0');
Serial.print("[NET] ");
Serial.print(buf);
Serial.print("| Packet #");
Serial.print(teleClient.txCount);
Serial.print(" | Out: ");
Serial.print(teleClient.txBytes >> 10);
Serial.print(" KB | In: ");
Serial.print(teleClient.rxBytes);
Serial.print(" bytes");
Serial.println();
#if ENABLE_OLED
oled.setCursor(0, 2);
oled.println(buf);
oled.setCursor(0, 5);
oled.printInt(teleClient.txCount, 2);
oled.setCursor(80, 5);
oled.printInt(teleClient.txBytes >> 10, 3);
#endif
}
bool waitMotion(long timeout)
{
#if ENABLE_MEMS
unsigned long t = millis();
if (state.check(STATE_MEMS_READY)) {
do {
// calculate relative movement
float motion = 0;
float acc[3];
if (!mems->read(acc)) continue;
if (accCount == 10) {
accCount = 0;
accSum[0] = 0;
accSum[1] = 0;
accSum[2] = 0;
}
accSum[0] += acc[0];
accSum[1] += acc[1];
accSum[2] += acc[2];
accCount++;
for (byte i = 0; i < 3; i++) {
float m = (acc[i] - accBias[i]);
motion += m * m;
}
#if ENABLE_HTTTPD
serverProcess(100);
#endif
processBLE(100);
// check movement
if (motion >= MOTION_THRESHOLD * MOTION_THRESHOLD) {
//lastMotionTime = millis();
Serial.println(motion);
return true;
}
} while ((long)(millis() - t) < timeout || timeout == -1);
return false;
}
#endif
serverProcess(timeout);
return false;
}
/*******************************************************************************
Collecting and processing data
*******************************************************************************/
void process()
{
uint32_t startTime = millis();
CBuffer* buffer = bufman.get();
if (!buffer) {
buffer = bufman.getOldest();
if (!buffer) return;
while (buffer->state == BUFFER_STATE_LOCKED) delay(1);
buffer->purge();
}
buffer->state = BUFFER_STATE_FILLING;
#if ENABLE_OBD
// process OBD data if connected
if (state.check(STATE_OBD_READY)) {
processOBD(buffer);
if (obd.errors >= MAX_OBD_ERRORS) {
if (!obd.init()) {
Serial.println("ECU OFF");
state.clear(STATE_OBD_READY | STATE_WORKING);
return;
}
}
}
#else
buffer->add(PID_DEVICE_HALL, readChipHallSensor() / 200);
#endif
#if ENABLE_OBD
if (sys.devType > 12) {
batteryVoltage = (float)(analogRead(A0) * 40) / 4095;
} else if (state.check(STATE_OBD_READY)) {
batteryVoltage = obd.getVoltage();
}
if (batteryVoltage) {
buffer->add(PID_BATTERY_VOLTAGE, (int)batteryVoltage * 100);
}
#endif
#if LOG_EXT_SENSORS
processExtInputs(buffer);
#endif
#if ENABLE_MEMS
processMEMS(buffer);
#endif
processGPS(buffer);
if (!state.check(STATE_MEMS_READY)) {
deviceTemp = readChipTemperature();
buffer->add(PID_DEVICE_TEMP, deviceTemp);
}
buffer->timestamp = millis();
buffer->state = BUFFER_STATE_FILLED;
// display file buffer stats
if (startTime - lastStatsTime >= 3000) {
bufman.printStats();
lastStatsTime = startTime;
}
#if STORAGE != STORAGE_NONE
if (state.check(STATE_STORAGE_READY)) {
buffer->serialize(logger);
uint16_t sizeKB = (uint16_t)(logger.size() >> 10);
if (sizeKB != lastSizeKB) {
logger.flush();
lastSizeKB = sizeKB;
Serial.print("[FILE] ");
Serial.print(sizeKB);
Serial.println("KB");
}
}
#endif
const int dataIntervals[] = DATA_INTERVAL_TABLE;
#if ENABLE_OBD || ENABLE_MEMS
// motion adaptive data interval control
const uint16_t stationaryTime[] = STATIONARY_TIME_TABLE;
unsigned int motionless = (millis() - lastMotionTime) / 1000;
bool stationary = true;
for (byte i = 0; i < sizeof(stationaryTime) / sizeof(stationaryTime[0]); i++) {
dataInterval = dataIntervals[i];
if (motionless < stationaryTime[i] || stationaryTime[i] == 0) {
stationary = false;
break;
}
}
if (stationary) {
// stationery timeout
Serial.print("Stationary for ");
Serial.print(motionless);
Serial.println(" secs");
// trip ended, go into standby
state.clear(STATE_WORKING);
return;
}
#else
dataInterval = dataIntervals[0];
#endif
do {
long t = dataInterval - (millis() - startTime);
processBLE(t > 0 ? t : 0);
} while (millis() - startTime < dataInterval);
}
bool initNetwork()
{
#if NET_DEVICE == NET_WIFI
#if ENABLE_OLED
oled.print("Connecting WiFi...");
#endif
for (byte attempts = 0; attempts < 3; attempts++) {
Serial.print("Joining ");
Serial.println(WIFI_SSID);
teleClient.net.begin(WIFI_SSID, WIFI_PASSWORD);
if (teleClient.net.setup()) {
state.set(STATE_NET_READY);
String ip = teleClient.net.getIP();
if (ip.length()) {
state.set(STATE_NET_CONNECTED);
Serial.print("IP:");
Serial.println(ip);
#if ENABLE_OLED
oled.println(ip);
#endif
break;
}
} else {
Serial.println("No WiFi");
}
}
#else
// power on network module
if (teleClient.net.begin(&sys)) {
state.set(STATE_NET_READY);
} else {
Serial.println("CELL:NO");
#if ENABLE_OLED
oled.println("No Cell Module");
#endif
return false;
}
#if NET_DEVICE >= SIM800
#if ENABLE_OLED
oled.print(teleClient.net.deviceName());
oled.println(" OK\r");
oled.print("IMEI:");
oled.println(teleClient.net.IMEI);
#endif
Serial.print("CELL:");
Serial.println(teleClient.net.deviceName());
if (!teleClient.net.checkSIM(SIM_CARD_PIN)) {
Serial.println("NO SIM CARD");
//return false;
}
Serial.print("IMEI:");
Serial.println(teleClient.net.IMEI);
if (state.check(STATE_NET_READY) && !state.check(STATE_NET_CONNECTED)) {
if (teleClient.net.setup(CELL_APN)) {
String op = teleClient.net.getOperatorName();
if (op.length()) {
Serial.print("Operator:");
Serial.println(op);
#if ENABLE_OLED
oled.println(op);
#endif
}
#if GNSS == GNSS_CELLULAR
if (teleClient.net.setGPS(true)) {
Serial.println("CELL GNSS:OK");
}
#endif
String ip = teleClient.net.getIP();
if (ip.length()) {
Serial.print("IP:");
Serial.println(ip);
#if ENABLE_OLED
oled.print("IP:");
oled.println(ip);
#endif
}
rssi = teleClient.net.getSignal();
if (rssi) {
Serial.print("RSSI:");
Serial.print(rssi);
Serial.println("dBm");
#if ENABLE_OLED
oled.print("RSSI:");
oled.print(rssi);
oled.println("dBm");
#endif
}
state.set(STATE_NET_CONNECTED);
} else {
char *p = strstr(teleClient.net.getBuffer(), "+CPSI:");
if (p) {
char *q = strchr(p, '\r');
if (q) *q = 0;
Serial.println(p + 7);
#if ENABLE_OLED
oled.println(p + 7);
#endif
} else {
Serial.print(teleClient.net.getBuffer());
}
}
timeoutsNet = 0;
}
#else
state.set(STATE_NET_CONNECTED);
#endif
#endif
return state.check(STATE_NET_CONNECTED);
}
/*******************************************************************************
Initializing network, maintaining connection and doing transmissions
*******************************************************************************/
void telemetry(void* inst)
{
uint8_t connErrors = 0;
CStorageRAM store;
store.init(SERIALIZE_BUFFER_SIZE);
teleClient.reset();
for (;;) {
if (state.check(STATE_STANDBY)) {
if (state.check(STATE_NET_READY)) {
teleClient.shutdown();
}
state.clear(STATE_NET_READY | STATE_NET_CONNECTED);
teleClient.reset();
bufman.purge();
#if GNSS == GNSS_INTERNAL || GNSS == GNSS_EXTERNAL
if (state.check(STATE_GPS_READY)) {
Serial.println("GNSS OFF");
#if GNSS_ALWAYS_ON
sys.gpsEnd(false);
#else
sys.gpsEnd(true);
#endif
state.clear(STATE_GPS_READY);
}
gd = 0;
#endif
uint32_t t = millis();
do {
delay(1000);
} while (state.check(STATE_STANDBY) && millis() - t < 1000L * PING_BACK_INTERVAL);
if (state.check(STATE_STANDBY)) {
// start ping
#if 0
#if GNSS == GNSS_EXTERNAL || GNSS == GNSS_INTERNAL
#if GNSS == GNSS_EXTERNAL
if (sys.gpsBegin())
#else
if (sys.gpsBegin(0))
#endif
{
state.set(STATE_GPS_READY);
for (uint32_t t = millis(); millis() - t < 60000; ) {
if (sys.gpsGetData(&gd)) {
break;
}
}
}
#endif
#endif
if (initNetwork()) {
Serial.print("Ping...");
bool success = teleClient.ping();
Serial.println(success ? "OK" : "NO");
}
teleClient.shutdown();
state.clear(STATE_NET_READY | STATE_NET_CONNECTED);
}
continue;
}
if (!state.check(STATE_NET_CONNECTED)) {
if (!initNetwork() || !teleClient.connect()) {
teleClient.shutdown();
state.clear(STATE_NET_READY | STATE_NET_CONNECTED);
delay(30000);
continue;
}
}
connErrors = 0;
teleClient.startTime = millis();
for (;;) {
CBuffer* buffer = bufman.getNewest();
if (!buffer) {
if (!state.check(STATE_WORKING)) break;
delay(50);
continue;
}
buffer->state = BUFFER_STATE_LOCKED;
#if SERVER_PROTOCOL == PROTOCOL_UDP
store.header(devid);
#endif
store.timestamp(buffer->timestamp);
buffer->serialize(store);
buffer->purge();
store.tailer();
//Serial.println(store.buffer());
// start transmission
#ifdef PIN_LED
if (ledMode == 0) digitalWrite(PIN_LED, HIGH);
#endif
if (teleClient.transmit(store.buffer(), store.length())) {
// successfully sent
connErrors = 0;
showStats();
} else {
connErrors++;
timeoutsNet++;
printTimeoutStats();
}
#ifdef PIN_LED
if (ledMode == 0) digitalWrite(PIN_LED, LOW);
#endif
store.purge();
teleClient.inbound();
if (syncInterval > 10000 && millis() - teleClient.lastSyncTime > syncInterval) {
//Serial.println("Instable connection");
timeoutsNet++;
if (!teleClient.connect()) {
connErrors++;
}
}
if (connErrors >= MAX_CONN_ERRORS_RECONNECT) {
Serial.println("Network errors");
teleClient.shutdown();
state.clear(STATE_NET_READY | STATE_NET_CONNECTED);
delay(5000);
break;
}
if (deviceTemp >= COOLING_DOWN_TEMP) {
// device too hot, cool down by pause transmission
Serial.println("Overheat");
delay(10000);
bufman.purge();
}
}
}
}