forked from mlukasek/M5_NightscoutMon
-
Notifications
You must be signed in to change notification settings - Fork 0
/
M5_NightscoutMon.ino
2889 lines (2666 loc) · 103 KB
/
M5_NightscoutMon.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
/* M5Stack Nightscout monitor
Copyright (C) 2018-2021 Martin Lukasek <[email protected]>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
This software uses some 3rd party libraries:
IniFile by Steve Marple <[email protected]> (GNU LGPL v2.1)
ArduinoJson by Benoit BLANCHON (MIT License)
IoT Icon Set by Artur Funk (GPL v3)
DHT12 by Bobadas (Public domain)
Additions to the code:
Peter Leimbach (Nightscout token)
Patrick Sonnerat (Dexcom Sugarmate connection)
Sulka Haro (Nightscout API queries help)
Ben West (AP WiFi configuration)
*/
// Official M5Stack Arduino board definitions are required, please add board from following location:
// https://m5stack.oss-cn-shenzhen.aliyuncs.com/resource/arduino/package_m5stack_index.json
//
// Only following boards are supported in this code:
// M5Stack Arduino / M5Stack-Core-ESP32
// M5Stack Arduino / M5Stack-Core2
#include <Arduino.h>
#ifdef ARDUINO_M5STACK_Core2
#include <M5Core2.h>
#include <driver/i2s.h>
#else
#include <M5Stack.h>
#endif
#include <Preferences.h>
#include <WiFi.h>
#include <WiFiMulti.h>
#include <WiFiUdp.h>
#include <WebServer.h>
#include <ESPmDNS.h>
#include <DNSServer.h>
#include <HTTPClient.h>
#include <HTTPUpdate.h>
#include "time.h"
#include "externs.h"
// #include <util/eu_dst.h>
#define ARDUINOJSON_USE_LONG_LONG 1
#include <ArduinoJson.h>
#include "soc/rtc_io_reg.h"
#include <Adafruit_NeoPixel.h>
Adafruit_NeoPixel pixels(10, 15, NEO_GRB + NEO_KHZ800);
#include "Free_Fonts.h"
#include "IniFile.h"
#include "M5NSconfig.h"
#include "M5NSWebConfig.h"
#include <Wire.h> //The DHT12 uses I2C comunication.
#include "DHT12.h"
DHT12 dht12;
#include "SHT3X.h"
SHT3X sht30;
#include "microdot.h"
MicroDot MD;
String M5NSversion("2022100201");
#ifdef ARDUINO_M5STACK_Core2
#define CONFIG_I2S_BCK_PIN 12
#define CONFIG_I2S_LRCK_PIN 0
#define CONFIG_I2S_DATA_PIN 2
#define CONFIG_I2S_DATA_IN_PIN 34
#define Speak_I2S_NUMBER I2S_NUM_0
#define MODE_SPK 1
#endif
#define VIBfreq 10000
#define VIBchannel 14
#define VIBresolution 10
// The UDP library class
WiFiUDP udp;
#define UDP_TX_PACKET_MAX_SIZE 2048
#define UDP_SEND_RETRIES 3
// IP address to send UDP data to
// const char * udpAddress = "192.168.1.255";
const int udpPort = 50555;
// buffers for receiving and sending UDP data
char packetBuffer[UDP_TX_PACKET_MAX_SIZE]; //buffer to hold incoming packet,
// extern const unsigned char alarmSndData[];
extern const unsigned char sun_icon16x16[];
extern const unsigned char clock_icon16x16[];
extern const unsigned char timer_icon16x16[];
// extern const unsigned char powerbutton_icon16x16[];
extern const unsigned char door_icon16x16[];
extern const unsigned char warning_icon16x16[];
extern const unsigned char wifi1_icon16x16[];
extern const unsigned char wifi2_icon16x16[];
extern const unsigned char bat0_icon16x16[];
extern const unsigned char bat1_icon16x16[];
extern const unsigned char bat2_icon16x16[];
extern const unsigned char bat3_icon16x16[];
extern const unsigned char bat4_icon16x16[];
extern const unsigned char plug_icon16x16[];
Preferences preferences;
tConfig cfg;
// Starfield Services Root Certificate Authority - G2
// Valid till Dec 31 23:59:59 2037 GMT
const char* rootCACertificate = \
"-----BEGIN CERTIFICATE-----\n" \
"MIID7zCCAtegAwIBAgIBADANBgkqhkiG9w0BAQsFADCBmDELMAkGA1UEBhMCVVMx" \
"EDAOBgNVBAgTB0FyaXpvbmExEzARBgNVBAcTClNjb3R0c2RhbGUxJTAjBgNVBAoT" \
"HFN0YXJmaWVsZCBUZWNobm9sb2dpZXMsIEluYy4xOzA5BgNVBAMTMlN0YXJmaWVs" \
"ZCBTZXJ2aWNlcyBSb290IENlcnRpZmljYXRlIEF1dGhvcml0eSAtIEcyMB4XDTA5" \
"MDkwMTAwMDAwMFoXDTM3MTIzMTIzNTk1OVowgZgxCzAJBgNVBAYTAlVTMRAwDgYD" \
"VQQIEwdBcml6b25hMRMwEQYDVQQHEwpTY290dHNkYWxlMSUwIwYDVQQKExxTdGFy" \
"ZmllbGQgVGVjaG5vbG9naWVzLCBJbmMuMTswOQYDVQQDEzJTdGFyZmllbGQgU2Vy" \
"dmljZXMgUm9vdCBDZXJ0aWZpY2F0ZSBBdXRob3JpdHkgLSBHMjCCASIwDQYJKoZI" \
"hvcNAQEBBQADggEPADCCAQoCggEBANUMOsQq+U7i9b4Zl1+OiFOxHz/Lz58gE20p" \
"OsgPfTz3a3Y4Y9k2YKibXlwAgLIvWX/2h/klQ4bnaRtSmpDhcePYLQ1Ob/bISdm2" \
"8xpWriu2dBTrz/sm4xq6HZYuajtYlIlHVv8loJNwU4PahHQUw2eeBGg6345AWh1K" \
"Ts9DkTvnVtYAcMtS7nt9rjrnvDH5RfbCYM8TWQIrgMw0R9+53pBlbQLPLJGmpufe" \
"hRhJfGZOozptqbXuNC66DQO4M99H67FrjSXZm86B0UVGMpZwh94CDklDhbZsc7tk" \
"6mFBrMnUVN+HL8cisibMn1lUaJ/8viovxFUcdUBgF4UCVTmLfwUCAwEAAaNCMEAw" \
"DwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMCAQYwHQYDVR0OBBYEFJxfAN+q" \
"AdcwKziIorhtSpzyEZGDMA0GCSqGSIb3DQEBCwUAA4IBAQBLNqaEd2ndOxmfZyMI" \
"bw5hyf2E3F/YNoHN2BtBLZ9g3ccaaNnRbobhiCPPE95Dz+I0swSdHynVv/heyNXB" \
"ve6SbzJ08pGCL72CQnqtKrcgfU28elUSwhXqvfdqlS5sdJ/PHLTyxQGjhdByPq1z" \
"qwubdQxtRbeOlKyWN7Wg0I8VRw7j6IPdj/3vQQF3zCepYoUz8jcI73HPdwbeyBkd" \
"iEDPfUYd/x7H4c7/I9vG+o1VTqkC50cRRj70/b17KSa7qWFiNyi2LSr2EIZkyXCn" \
"0q23KXB56jzaYyWf/Wi3MOxw+3WKt21gZ7IeyLnp2KhvAotnDU0mV3HaIPzBSlCN" \
"sSi6" \
"-----END CERTIFICATE-----\n";
WebServer w3srv(80);
const byte DNS_PORT = 53;
DNSServer dnsServer;
const char* ntpServer = "pool.ntp.org"; // "time.nist.gov", "time.google.com"
struct tm localTimeInfo;
int MAX_TIME_RETRY = 30;
int lastSec = 61;
int lastMin = 61;
char localTimeStr[30];
struct err_log_item {
struct tm err_time;
int err_code;
} err_log[10];
int err_log_ptr = 0;
int err_log_count = 0;
int rcnt = 4;
int dispPage = 0;
#define MAX_PAGE 3
int maxPage = MAX_PAGE;
// icon positions for the first page - WiFi/log, Snooze, Battery
int icon_xpos[3] = {144, 144+18, 144+2*18};
int icon_ypos[3] = {0, 0, 0};
// analog clock global variables
uint16_t osx=120, osy=120, omx=120, omy=120, ohx=120, ohy=120; // Saved H, M, S x & y coords
boolean initial = 1;
boolean mDNSactive = false;
#ifndef min
#define min(a,b) (((a) < (b)) ? (a) : (b))
#endif
#ifndef M_PI
#define M_PI 3.14159265358979323846
#endif
void draw_page();
WiFiMulti WiFiMultiple;
unsigned long msCount;
// unsigned long msCountLog;
unsigned long msStart;
uint8_t lcdBrightness = 10;
const char iniFilename[] = "/M5NS.INI";
DynamicJsonDocument JSONdoc(16384);
time_t lastAlarmTime = 0;
time_t snoozeUntil = 0;
int snoozeMult = 0;
unsigned long lastButtonMillis = 0;
int udpSendSnoozeRetries = 0;
bool is_task_bootstrapping = 0;
#ifdef ARDUINO_M5STACK_Core2
static int16_t music_data[25000]; // 2s in sample rate 11025 samp/s
#else
static uint8_t music_data[25000]; // 5s in sample rate 5000 samp/s
#endif
struct NSinfo ns;
void setPageIconPos(int page) {
switch(page) {
case 0:
icon_xpos[0] = 144;
icon_xpos[1] = 144+18;
icon_xpos[2] = 144+2*18;
icon_ypos[0] = 0;
icon_ypos[1] = 0;
icon_ypos[2] = 0;
break;
case 1:
icon_xpos[0] = 126;
icon_xpos[1] = 126+18;
icon_xpos[2] = 126+18; // 320-16;
icon_ypos[0] = 0;
icon_ypos[1] = 0;
icon_ypos[2] = 18; // 220;
break;
case 2:
icon_xpos[0] = 0+18;
icon_xpos[1] = 0+18;
icon_xpos[2] = 0+18;
icon_ypos[0] = 110-18-9;
icon_ypos[1] = 110-18+9;
icon_ypos[2] = 110-18+27;
break;
default:
icon_xpos[0] = 266;
icon_xpos[1] = 266+18;
icon_xpos[2] = 266+2*18;
icon_ypos[0] = 0;
icon_ypos[1] = 0;
icon_ypos[2] = 0;
break;
}
}
void lcdSetBrightness(uint8_t brightness) {
if( brightness>100 )
brightness = 100;
#ifdef ARDUINO_M5STACK_Core2
M5.Axp.SetLcdVoltage(2500+brightness*8);
#else
M5.Lcd.setBrightness(brightness);
#endif
}
void addErrorLog(int code){
if(err_log_ptr>9) {
for(int i=0; i<9; i++) {
err_log[i].err_time=err_log[i+1].err_time;
err_log[i].err_code=err_log[i+1].err_code;
}
err_log_ptr=9;
}
getLocalTime(&err_log[err_log_ptr].err_time);
err_log[err_log_ptr].err_code=code;
err_log_ptr++;
err_log_count++;
}
uint16_t crc16_update(uint16_t crc, uint8_t a)
{
int i;
crc ^= a;
for (i = 0; i < 8; ++i)
{
if (crc & 1)
crc = (crc >> 1) ^ 0xA001;
else
crc = (crc >> 1);
}
return crc;
}
uint16_t calcCRC(char* str)
{
uint16_t crc=0; // starting value as you like, must be the same before each calculation
for (int i=0;i<strlen(str);i++) // for each character in the string
{
crc= crc16_update (crc, str[i]); // update the crc value
}
return crc;
}
void startupLogo() {
// static uint8_t brightness, pre_brightness;
lcdSetBrightness(0);
if(!SD.exists(cfg.bootPic)) {
// M5.Lcd.pushImage(0, 0, 320, 240, (uint16_t *)gImage_logoM5);
M5.Lcd.clear();
M5.Lcd.setTextColor(TFT_WHITE, TFT_BLACK);
M5.Lcd.drawString("M5 Stack", 120, 60, GFXFF);
M5.Lcd.drawString("Nightscout monitor", 60, 80, GFXFF);
M5.Lcd.drawString("(c) 2019-21 Martin Lukasek", 0, 120, GFXFF);
} else {
M5.Lcd.drawJpgFile(SD, cfg.bootPic);
}
lcdSetBrightness(100);
#ifndef ARDUINO_M5STACK_Core2 // no .update() on M5Stack CORE2
M5.update();
#endif
}
void printLocalTime() {
if(!getLocalTime(&localTimeInfo)){
Serial.println("Failed to obtain time");
M5.Lcd.println("Failed to obtain time");
return;
}
Serial.println(&localTimeInfo, "%A, %B %d %Y %H:%M:%S");
M5.Lcd.println(&localTimeInfo, "%A, %B %d %Y %H:%M:%S");
}
#ifdef ARDUINO_M5STACK_Core2
// audio functions for Core2
bool InitI2SSpeakOrMic(int mode)
{
esp_err_t err = ESP_OK;
i2s_driver_uninstall(Speak_I2S_NUMBER);
i2s_config_t i2s_config = {
.mode = (i2s_mode_t)(I2S_MODE_MASTER),
.sample_rate = 11025,
.bits_per_sample = I2S_BITS_PER_SAMPLE_16BIT, // is fixed at 12bit, stereo, MSB
.channel_format = I2S_CHANNEL_FMT_ONLY_RIGHT,
.communication_format = I2S_COMM_FORMAT_I2S,
.intr_alloc_flags = ESP_INTR_FLAG_LEVEL1,
.dma_buf_count = 2,
.dma_buf_len = 128,
};
i2s_config.mode = (i2s_mode_t)(I2S_MODE_MASTER | I2S_MODE_TX);
i2s_config.use_apll = false;
i2s_config.tx_desc_auto_clear = true;
err += i2s_driver_install(Speak_I2S_NUMBER, &i2s_config, 0, NULL);
i2s_pin_config_t tx_pin_config;
tx_pin_config.bck_io_num = CONFIG_I2S_BCK_PIN;
tx_pin_config.ws_io_num = CONFIG_I2S_LRCK_PIN;
tx_pin_config.data_out_num = CONFIG_I2S_DATA_PIN;
tx_pin_config.data_in_num = CONFIG_I2S_DATA_IN_PIN;
err += i2s_set_pin(Speak_I2S_NUMBER, &tx_pin_config);
err += i2s_set_clk(Speak_I2S_NUMBER, 11025, I2S_BITS_PER_SAMPLE_16BIT, I2S_CHANNEL_MONO);
return true;
}
void play_tone(uint16_t frequency, uint32_t duration, uint8_t volume) {
size_t bytes_written = 0;
// Serial.print("start fill music data "); Serial.println(millis());
uint32_t data_length = duration * 11;
if( data_length > 22050 )
data_length = 22050;
float interval = 2*M_PI*float(frequency)/float(11025);
float volMul = volume/100.0;
for (uint32_t i=0;i<data_length;i++) {
music_data[i]=32767.0*sin(interval*i)*volMul; // 16383.0+ /(101-volume)
}
music_data[data_length-1]=32767;
// Serial.print("finish fill music data, start play "); Serial.println(millis());
i2s_write(Speak_I2S_NUMBER, music_data, data_length*2, &bytes_written, portMAX_DELAY);
// Serial.print("finish play "); Serial.println(millis());
}
#else // M5Stack BASIC audio functions
// this function is for original M5Stack only, as Core2 uses DMA to I2S
void play_music_data(uint32_t data_length, uint8_t volume) {
uint8_t vol;
if( volume>100 )
vol=1;
else
vol=101-volume;
if(vol != 101) {
ledcSetup(TONE_PIN_CHANNEL, 0, 13);
ledcAttachPin(SPEAKER_PIN, TONE_PIN_CHANNEL);
delay(10);
for(int i=0; i<data_length; i++) {
dacWrite(SPEAKER_PIN, music_data[i]/vol);
delayMicroseconds(194); // 200 = 1 000 000 microseconds / sample rate 5000
}
/* takes too long
// slowly set DAC to zero from the last value
for(int t=music_data[data_length-1]; t>=0; t--) {
dacWrite(SPEAKER_PIN, t);
delay(2);
} */
for(int t = music_data[data_length - 1] / vol; t >= 0; t--) {
dacWrite(SPEAKER_PIN, t);
delay(2);
}
// dacWrite(SPEAKER_PIN, 0);
// delay(10);
ledcAttachPin(SPEAKER_PIN, TONE_PIN_CHANNEL);
ledcWriteTone(TONE_PIN_CHANNEL, 0);
CLEAR_PERI_REG_MASK(RTC_IO_PAD_DAC1_REG, RTC_IO_PDAC1_XPD_DAC | RTC_IO_PDAC1_DAC_XPD_FORCE);
} else {
// silence must make a delay for duration
delay(data_length/5);
}
}
void play_tone(uint16_t frequency, uint32_t duration, uint8_t volume) {
// Serial.print("start fill music data "); Serial.println(millis());
uint32_t data_length = 5000;
if( duration*5 < data_length )
data_length = duration*5;
float interval = 2*M_PI*float(frequency)/float(5000);
for (int i=0;i<data_length;i++) {
music_data[i]=127+126*sin(interval*i);
}
// Serial.print("finish fill music data "); Serial.println(millis());
if(cfg.vibration_mode != 0) {
ledcSetup(VIBchannel, VIBfreq, VIBresolution);
ledcAttachPin(cfg.vibration_pin, VIBchannel);
delay(10);
ledcWrite(VIBchannel, cfg.vibration_strength);
}
play_music_data(data_length, volume);
if(cfg.vibration_mode != 0) {
ledcSetup(VIBchannel, VIBfreq, VIBresolution);
ledcAttachPin(cfg.vibration_pin, VIBchannel);
delay(10);
if(duration<180) // minimum vibration lenght is 200 ms
delay(180-duration);
ledcWrite(VIBchannel, 0);
}
}
#endif
void sndAlarm() {
for(int j=0; j<6; j++) {
if(cfg.LED_strip_mode != 0) {
int maxint = 255;
maxint *= cfg.LED_strip_brightness;
maxint /= 100;
pixels.fill(pixels.Color(maxint, 0, 0));
pixels.show();
}
if( cfg.dev_mode )
play_tone(660, 400, 1);
else
play_tone(660, 400, cfg.alarm_volume);
if(cfg.LED_strip_mode != 0) {
pixels.clear();
pixels.show();
}
delay(200);
}
}
void sndWarning() {
for(int j=0; j<3; j++) {
if(cfg.LED_strip_mode != 0) {
int maxint = 255;
maxint *= cfg.LED_strip_brightness;
maxint /= 100;
int lessint = 192;
lessint *= cfg.LED_strip_brightness;
lessint /= 100;
pixels.fill(pixels.Color(maxint, lessint, 0));
pixels.show();
}
if( cfg.dev_mode )
play_tone(3000, 100, 1);
else
play_tone(3000, 100, cfg.warning_volume);
if(cfg.LED_strip_mode != 0) {
pixels.clear();
pixels.show();
}
delay(300);
}
}
void drawIcon(int16_t x, int16_t y, const uint8_t *bitmap, uint16_t color) {
int16_t w = 16;
int16_t h = 16;
int32_t i, j, byteWidth = (w + 7) / 8;
for (j = 0; j < h; j++) {
for (i = 0; i < w; i++) {
if (pgm_read_byte(bitmap + j * byteWidth + i / 8) & (128 >> (i & 7))) {
M5.Lcd.drawPixel(x + i, y + j, color);
}
}
}
}
void waitBtnRelease() {
#ifdef ARDUINO_M5STACK_Core2
// wait release
TouchPoint_t pos;
pos = M5.Touch.getPressPoint();
while((pos.x != -1) || (pos.y != -1)) {
pos = M5.Touch.getPressPoint();
delay(20);
}
#endif
}
void buttons_test() {
bool btnA_wasPressed = false;
bool btnB_wasPressed = false;
bool btnC_wasPressed = false;
#ifdef ARDUINO_M5STACK_Core2
TouchPoint_t pos;
pos = M5.Touch.getPressPoint();
// Serial.printf("Touch point: %d : %d\r\n", pos.x, pos.y);
btnA_wasPressed = (pos.x >= 0) && (pos.x < 109) && (pos.y > 210); // 240 is bellow display, but we have displayed icons on the last line
btnB_wasPressed = (pos.x >= 109) && (pos.x <= 218) && (pos.y > 210);
btnC_wasPressed = (pos.x > 218) && (pos.y > 210);
#else
btnA_wasPressed = M5.BtnA.wasPressed();
btnB_wasPressed = M5.BtnB.wasPressed();
btnC_wasPressed = M5.BtnC.wasPressed();
#endif
if(btnA_wasPressed) {
// M5.Lcd.printf("A");
Serial.printf("A");
// play_tone(1000, 10, 1);
// sndAlarm();
if(lcdBrightness==cfg.brightness1)
lcdBrightness = cfg.brightness2;
else
if(lcdBrightness==cfg.brightness2)
lcdBrightness = cfg.brightness3;
else
lcdBrightness = cfg.brightness1;
lcdSetBrightness(lcdBrightness);
#ifdef ARDUINO_M5STACK_Core2
waitBtnRelease();
#else
M5.update();
#endif
// addErrorLog(500);
/* UDP send test
IPAddress broadcastIp = ~WiFi.subnetMask() | WiFi.gatewayIP();
Serial.print("Sending broadcast to: ");
Serial.println(broadcastIp);
udp.beginPacket(broadcastIp, udpPort); // udpAddress
udp.printf("Seconds since boot: %lu", millis()/1000);
udp.endPacket();
*/
}
if(btnB_wasPressed) {
// M5.Lcd.printf("B");
Serial.printf("B");
/*
play_tone(440, 100, 1);
delay(10);
play_tone(880, 100, 1);
delay(10);
play_tone(1760, 100, 1);
*/
struct tm timeinfo;
bool timeOK = getLocalTime(&timeinfo);
if( (millis()-lastButtonMillis)<2000 ) {
// snoozing just recently - will multiply snooze time
// Serial.printf("lastButton < 2s \r\n");
snoozeMult++;
if(snoozeMult>4)
snoozeMult = 0;
} else {
// Serial.printf("lastButton > 2s, MULT = 1\r\n");
// new Snooze
snoozeMult = 1;
}
if(!timeOK){
// Serial.printf("Time not OK - NO SLEEP\r\n");
snoozeUntil = 0;
} else {
snoozeUntil = mktime(&timeinfo) + snoozeMult*cfg.snooze_timeout*60;
Serial.print("snoozeUntil = "); Serial.println(snoozeUntil);
}
M5.Lcd.fillRect(110, 220, 100, 20, TFT_WHITE);
M5.Lcd.setTextDatum(TL_DATUM);
M5.Lcd.setTextSize(1);
M5.Lcd.setFreeFont(FSSB12);
M5.Lcd.setTextColor(TFT_BLACK, TFT_WHITE);
char tmpStr[10];
int snoozeRemaining = 0;
if(timeOK) {
snoozeRemaining = difftime(snoozeUntil, mktime(&timeinfo));
if(snoozeRemaining<0)
snoozeRemaining = 0;
}
if(snoozeMult==0)
strcpy(tmpStr, "OFF");
else {
sprintf(tmpStr, "%i", (snoozeRemaining+59)/60);
if(cfg.LED_strip_mode==2) {
pixels.clear();
pixels.show();
}
}
int txw=M5.Lcd.textWidth(tmpStr);
Serial.print("Set SNOOZE: "); Serial.print(tmpStr); Serial.print(", snoozeUntil-now = "); Serial.println(snoozeRemaining);
M5.Lcd.drawString(tmpStr, 159-txw/2, 220, GFXFF);
if(dispPage<maxPage) {
if(snoozeMult==0)
M5.Lcd.fillRect(icon_xpos[1], icon_ypos[1], 16, 16, BLACK);
else
drawIcon(icon_xpos[1], icon_ypos[1], (uint8_t*)clock_icon16x16, TFT_RED);
}
udpSendSnoozeRetries = UDP_SEND_RETRIES;
lastButtonMillis = millis();
#ifdef ARDUINO_M5STACK_Core2
waitBtnRelease();
#else
M5.update();
#endif
}
if(btnC_wasPressed) {
// M5.Lcd.printf("C");
Serial.printf("C");
int longPress = 0;
#ifndef ARDUINO_M5STACK_Core2 // long press check only on real buttons, ARDUINO_M5STACK_Core2 has its own power button with long press to power off
unsigned long btnCPressTime = millis();
long pwrOffTimeout = 4000;
int lastDispTime = pwrOffTimeout/1000;
char tmpstr[32];
while(M5.BtnC.read()) {
M5.Lcd.setTextSize(1);
M5.Lcd.setFreeFont(FSSB12);
// M5.Lcd.fillRect(110, 220, 100, 20, TFT_RED);
// M5.Lcd.fillRect(0, 220, 320, 20, TFT_RED);
M5.Lcd.setTextColor(TFT_WHITE, TFT_BLACK);
int timeToPwrOff = (pwrOffTimeout - (millis()-btnCPressTime))/1000;
if((lastDispTime!=timeToPwrOff) && (millis()-btnCPressTime>800)) {
longPress = 1;
sprintf(tmpstr, "OFF in %1d ", timeToPwrOff);
M5.Lcd.drawString(tmpstr, 210, 220, GFXFF);
lastDispTime=timeToPwrOff;
}
if(timeToPwrOff<=0) {
// play_tone(3000, 100, 1);
M5.Power.setWakeupButton(BUTTON_C_PIN);
M5.Power.powerOFF();
}
#ifndef ARDUINO_M5STACK_Core2 // no .update() on M5Stack CORE2
M5.update();
#endif
}
#endif
if(longPress) {
M5.Lcd.fillRect(210, 220, 110, 20, TFT_BLACK);
drawIcon(246, 220, (uint8_t*)door_icon16x16, TFT_LIGHTGREY);
} else {
dispPage++;
if(dispPage>maxPage)
dispPage = 0;
setPageIconPos(dispPage);
M5.Lcd.clear(BLACK);
// msCount = millis()-16000;
draw_page();
// play_tone(440, 100, 1);
}
/*
for (int i=0;i<25000;i++) {
music_data[i]=alarmSndData[i];
}
play_music_data(25000, 10); */
#ifdef ARDUINO_M5STACK_Core2
waitBtnRelease();
#else
M5.update();
#endif
}
}
const char * CONSONANTS = "bcdfghjklmnpqrstvwxyz";
const char * VOWELS = "aeiouy";
int passLen = 8;
void generate_ssid_passphrase (char * buffer) {
char passphrase[passLen+1];
int max_consonants;
int max_vowels;
max_consonants = strlen(CONSONANTS);
max_vowels = strlen(VOWELS);
randomSeed(analogRead(0));
passphrase[0] = CONSONANTS[random(0, max_consonants)];
passphrase[1] = VOWELS[random(0, max_vowels)];
passphrase[2] = VOWELS[random(0, max_vowels)];
passphrase[3] = CONSONANTS[random(0, max_consonants)];
passphrase[4] = VOWELS[random(0, max_vowels)];
passphrase[5] = VOWELS[random(0, max_vowels)];
passphrase[6] = CONSONANTS[random(0, max_consonants)];
passphrase[7] = VOWELS[random(0, max_vowels)];
passphrase[8] = VOWELS[random(0, max_vowels)];
passphrase[9] = '\0';
strcpy(buffer, passphrase);
}
void wifi_connect() {
char ssid_passphrase[80];
if (is_task_bootstrapping) {
// offer access point to join for configuration purposes
WiFi.enableAP(true);
WiFi.mode(WIFI_AP);
IPAddress ip(192, 168, 0, 1);
IPAddress gateway(192, 168, 0, 1);
IPAddress subnet(255, 255, 255, 0);
Serial.print("Setting soft-AP configuration ... ");
Serial.println(WiFi.softAPConfig(ip, gateway, subnet) ? "Ready" : "Failed!");
// set random password
generate_ssid_passphrase(ssid_passphrase);
Serial.print("Setting soft-AP ... ");
Serial.println(WiFi.softAP(cfg.deviceName, ssid_passphrase) ? "Ready" : "Failed!");
delay(250);
Serial.print("Soft-AP IP address = ");
Serial.println(WiFi.softAPIP());
// WiFi.begin( );
dnsServer.setTTL(300);
dnsServer.setErrorReplyCode(DNSReplyCode::ServerFailure);
dnsServer.start(DNS_PORT, "*", ip);
} else {
WiFi.mode(WIFI_STA);
WiFi.disconnect();
delay(100);
Serial.println("WiFi connect start");
M5.Lcd.println("WiFi connect start");
// We start by connecting to a WiFi network
for(int i=0; i<=9; i++) {
if(cfg.wlanssid[i][0]!=0) {
if(cfg.wlanpass[i][0]==0) {
// no or empty password -> send NULL
WiFiMultiple.addAP(cfg.wlanssid[i], NULL);
} else {
WiFiMultiple.addAP(cfg.wlanssid[i], cfg.wlanpass[i]);
}
}
}
Serial.println();
M5.Lcd.println("");
Serial.print("Wait for WiFi... ");
M5.Lcd.print("Wait for WiFi... ");
while(WiFiMultiple.run() != WL_CONNECTED) {
Serial.print(".");
M5.Lcd.print(".");
delay(500);
}
}
Serial.println("");
M5.Lcd.println("");
Serial.print("WiFi connected to SSID ");
if (is_task_bootstrapping) {
Serial.println(cfg.deviceName);
M5.Lcd.print("WiFi SSID: "); M5.Lcd.println(cfg.deviceName);
Serial.print("SSID Passphrase: "); Serial.println(ssid_passphrase);
M5.Lcd.print("SSID Passphrase: "); M5.Lcd.println(ssid_passphrase);
M5.Lcd.println();
M5.Lcd.print("Join WiFi & Visit URL:\nhttp://");
M5.Lcd.print(cfg.deviceName);
M5.Lcd.print(".local\n");
M5.Lcd.print("IP address: ");
M5.Lcd.println(WiFi.softAPIP());
} else {
Serial.println(WiFi.SSID());
M5.Lcd.print("WiFi SSID: "); M5.Lcd.println(WiFi.SSID());
Serial.print("IP address: ");
M5.Lcd.print("IP address: ");
Serial.println(WiFi.localIP());
M5.Lcd.println(WiFi.localIP());
configTime(cfg.timeZone, cfg.dst, ntpServer, "time.nist.gov", "time.google.com");
delay(1000);
Serial.print("Waiting for time.");
int i = 0;
while(!getLocalTime(&localTimeInfo)) {
Serial.print(".");
delay(1000);
i++;
if (i > MAX_TIME_RETRY) {
Serial.print("Gave up waiting for time to have a valid value.");
break;
}
}
Serial.println();
printLocalTime();
Serial.println("Connection done");
M5.Lcd.println("Connection done");
}
}
int8_t getBatteryLevel()
{
#ifdef ARDUINO_M5STACK_Core2
float dta;
int8_t batLev = 0;
dta = M5.Axp.GetBatVoltage();
if(dta>4.1)
batLev = 100;
else
if(dta>3.9)
batLev = 75;
else
if(dta>3.75)
batLev = 50;
else
if(dta>3.6)
batLev = 25;
Serial.printf("Battery %4.2f V = %d%%\r\n", dta, batLev);
return batLev;
#else
int8_t bl = M5.Power.getBatteryLevel();
/*
// write battery info to logfile.txt
File fileLog = SD.open("/logfile.txt", FILE_WRITE);
if(!fileLog) {
Serial.println("Cannot write to logfile.txt");
} else {
int pos = fileLog.seek(fileLog.size());
struct tm timeinfo;
getLocalTime(&timeinfo);
fileLog.print(asctime(&timeinfo));
fileLog.print(" Battery level: "); fileLog.println(bdata, HEX);
fileLog.close();
Serial.print("Log file written: "); Serial.print(asctime(&timeinfo));
}
*/
return bl;
#endif
return -1;
}
void drawArrow(int x, int y, int asize, int aangle, int pwidth, int plength, uint16_t color){
float dx = (asize-10)*cos(aangle-90)*PI/180+x; // calculate X position
float dy = (asize-10)*sin(aangle-90)*PI/180+y; // calculate Y position
float x1 = 0; float y1 = plength;
float x2 = pwidth/2; float y2 = pwidth/2;
float x3 = -pwidth/2; float y3 = pwidth/2;
float angle = aangle*PI/180-135;
float xx1 = x1*cos(angle)-y1*sin(angle)+dx;
float yy1 = y1*cos(angle)+x1*sin(angle)+dy;
float xx2 = x2*cos(angle)-y2*sin(angle)+dx;
float yy2 = y2*cos(angle)+x2*sin(angle)+dy;
float xx3 = x3*cos(angle)-y3*sin(angle)+dx;
float yy3 = y3*cos(angle)+x3*sin(angle)+dy;
M5.Lcd.fillTriangle(xx1,yy1,xx3,yy3,xx2,yy2, color);
M5.Lcd.drawLine(x, y, xx1, yy1, color);
M5.Lcd.drawLine(x+1, y, xx1+1, yy1, color);
M5.Lcd.drawLine(x, y+1, xx1, yy1+1, color);
M5.Lcd.drawLine(x-1, y, xx1-1, yy1, color);
M5.Lcd.drawLine(x, y-1, xx1, yy1-1, color);
M5.Lcd.drawLine(x+2, y, xx1+2, yy1, color);
M5.Lcd.drawLine(x, y+2, xx1, yy1+2, color);
M5.Lcd.drawLine(x-2, y, xx1-2, yy1, color);
M5.Lcd.drawLine(x, y-2, xx1, yy1-2, color);
}
void drawMiniGraph(struct NSinfo *ns){
/*
// draw help lines
for(int i=0; i<320; i+=40) {
M5.Lcd.drawLine(i, 0, i, 240, TFT_DARKGREY);
}
for(int i=0; i<240; i+=30) {
M5.Lcd.drawLine(0, i, 320, i, TFT_DARKGREY);
}
M5.Lcd.drawLine(0, 120, 320, 120, TFT_LIGHTGREY);
M5.Lcd.drawLine(160, 0, 160, 240, TFT_LIGHTGREY);
*/
int i;
float glk;
uint16_t sgvColor;
// M5.Lcd.drawLine(231, 110, 319, 110, TFT_DARKGREY);
// M5.Lcd.drawLine(231, 110, 231, 207, TFT_DARKGREY);
// M5.Lcd.drawLine(231, 207, 319, 207, TFT_DARKGREY);
// M5.Lcd.drawLine(319, 110, 319, 207, TFT_DARKGREY);
M5.Lcd.drawLine(231, 113, 319, 113, TFT_LIGHTGREY);
M5.Lcd.drawLine(231, 203, 319, 203, TFT_LIGHTGREY);
M5.Lcd.drawLine(231, 200-(4-3)*10+3, 319, 200-(4-3)*10+3, TFT_LIGHTGREY);
M5.Lcd.drawLine(231, 200-(9-3)*10+3, 319, 200-(9-3)*10+3, TFT_LIGHTGREY);
Serial.print("Last 10 values: ");
for(i=9; i>=0; i--) {
sgvColor = TFT_GREEN;
glk = *(ns->last10sgv+9-i);
if(glk>12) {
glk = 12;
} else {
if(glk<3) {
glk = 3;
}
}
if(glk<cfg.red_low || glk>cfg.red_high) {
sgvColor = TFT_RED;
} else {
if(glk<cfg.yellow_low || glk>cfg.yellow_high) {
sgvColor = TFT_YELLOW;
}
}
Serial.print(*(ns->last10sgv+i)); Serial.print(" ");
if(*(ns->last10sgv+9-i)!=0)
M5.Lcd.fillCircle(234+i*9, 203-(glk-3.0)*10.0, 3, sgvColor);
}
Serial.println();
}
int readNightscout(char *url, char *token, struct NSinfo *ns) {
HTTPClient http;
WiFiClientSecure sclient;
sclient.setCACert(rootCACertificate);
char NSurl[128];
int err=0;
char tmpstr[64];
bool is_https_Heroku = false;
// http.setReuse(false);
// if(client) {
// sclient.setCACert(rootCACertificate);
// Serial.println("Client OK, setCACert OK");
//}
if((WiFiMultiple.run() == WL_CONNECTED)) {
// configure target server and url
if(strncmp(url, "http", 4))
strcpy(NSurl,"https://");
else
strcpy(NSurl,"");
strcat(NSurl,url);
if(strlen(NSurl)>0) {
if(NSurl[strlen(NSurl)-1]=='/') {
NSurl[strlen(NSurl)-1]=0;
}
}
if(strstr(NSurl,"sugarmate") != NULL) // Sugarmate JSON URL for Dexcom follower
ns->is_Sugarmate = 1;
else
{
ns->is_Sugarmate = 0;
is_https_Heroku = (strstr(NSurl,"https://") != NULL) && (strstr(NSurl,"herokuapp.com") != NULL);
Serial.print("is_https_Heroku "); Serial.println(is_https_Heroku);
if(cfg.sgv_only) {
strcat(NSurl,"/api/v1/entries.json?find[type][$eq]=sgv&count=10");
} else {
strcat(NSurl,"/api/v1/entries.json?count=10");
}
if ((token!=NULL) && (strlen(token)>0)) {
strcat(NSurl,"&token=");
strcat(NSurl,token);
}
}
M5.Lcd.fillRect(icon_xpos[0], icon_ypos[0], 16, 16, BLACK);
drawIcon(icon_xpos[0], icon_ypos[0], (uint8_t*)wifi2_icon16x16, TFT_BLUE);
Serial.print("JSON query NSurl = \'");Serial.print(NSurl);Serial.print("\'\r\n");
// http.begin(NSurl, "94:FC:F6:23:6C:37:D5:E7:92:78:3C:0B:5F:AD:0C:E4:9E:FD:9E:A8"); //HTTP
if( is_https_Heroku ) {
if(http.begin(sclient, NSurl)) {
Serial.println("http.begin HTTPS Heroku OK");
} else {
Serial.println("http.begin HTTPS Heroku FAILED");
}
} else {
if(http.begin(NSurl)) {
Serial.println("http.begin OK");
} else {
Serial.println("http.begin FAILED");
}
}
// http.connect();
// Serial.print("Connected "); Serial.println(http.connected()?"YES":"NO");
// http.setConnectTimeout(15000);
// http.setTimeout(15000);