~jochen/Calculateur

ref: 3aa34544e9da8c5344cbf5444a05c243fc3f26ea Calculateur/Calculateur.cpp -rw-r--r-- 32.6 KiB
3aa34544Jochen added Alarm1 info 10 months ago
                                                                                
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
#include "Calculateur.h"

DS3232RTC Watchy::RTC(false); 
GxEPD2_BW<GxEPD2_154_D67, GxEPD2_154_D67::HEIGHT> Watchy::display(GxEPD2_154_D67(CS, DC, RESET, BUSY));

RTC_DATA_ATTR int guiState;
RTC_DATA_ATTR int menuIndex;
RTC_DATA_ATTR BMA423 sensor;
RTC_DATA_ATTR bool WIFI_CONFIGURED;
RTC_DATA_ATTR bool BLE_CONFIGURED;

Watchy::Watchy(){} //constructor

int steps[] = {126, 252, 419, 545, 712, 838, 1004, 1131, 1257, 1423, 1550, 1716, 1843, 2009, 2136, 2302, 2428, 2555, 2721, 2848, 3014, 3140, 3307, 3433, 3600, 3726, 3852, 4019, 4145, 4312, 4438, 4604, 4731, 4857, 5024, 5150, 5316, 5443, 5609, 5736, 5902, 10028, 10155, 10321, 10448, 10614, 10740, 10907, 11033, 11200, 11326, 11452, 11619, 11745, 11912, 12038, 12204, 12331, 12457, 12623, 12750, 12916, 13043, 13209, 13335, 13502, 13628, 13755, 13921, 14047, 14214, 14340, 14507, 14633, 14759, 14926, 15052, 15219, 15345, 15511, 15638, 15804, 15931, 20057, 20223, 20350, 20516, 20643, 20809, 20935, 21102, 21228, 21355, 21521, 21647, 21814, 21940, 22107, 22233, 22359, 22526, 22652, 22819, 22945, 23111, 23238, 23404, 23531, 23657, 23823, 23950, 24116, 24243, 24409, 24535, 24702, 24828, 24955, 25121, 25247, 25414, 25540, 25707, 25833, 25959, 30126, 30252, 30419, 30545, 30711, 30838, 31004, 31131, 31257, 31423, 31550, 31716, 31843, 32009, 32135, 32302, 32428, 32555, 32721, 32847, 33014, 33140, 33307, 33433, 33559, 33726, 33852, 34019, 34145, 34311, 34438, 34604, 34731, 34857, 35023, 35150, 35316, 35443, 35609, 35735, 35902, 40028, 40155, 40321, 40447, 40614, 40740, 40907, 41033, 41159, 41326, 41452, 41619, 41745, 41911, 42038, 42204, 42331, 42457, 42623, 42750, 42916, 43043, 43209, 43335, 43502, 43628, 43755, 43921, 44047, 44214, 44340, 44507, 44633, 44759, 44926, 45052, 45219, 45345, 45511, 45638, 45804, 45931, 50057, 50223, 50350, 50516, 50643, 50809, 50935, 51102, 51228, 51355, 51521, 51647, 51814, 51940, 52107, 52233, 52400, 52526, 52652, 52819, 52945, 53112, 53238, 53404, 53531, 53657, 53824, 53950, 54116, 54243, 54409, 54536, 54702, 54828, 54955, 55121, 55248, 55414, 55540, 55707, 55833, 60000, 60126, 60252, 60419, 60545, 60712, 60838, 61004, 61131, 61257, 61424, 61550, 61716, 61843, 62009, 62136, 62302, 62428, 62555, 62721, 62848, 63014, 63140, 63307, 63433, 63600, 63726, 63852, 64019, 64145, 64312, 64438, 64604, 64731, 64857, 65024, 65150, 65316, 65443, 65609, 65736, 65902, 70028, 70155, 70321, 70448, 70614, 70740, 70907, 71033, 71200, 71326, 71452, 71619, 71745, 71912, 72038, 72204, 72331, 72457, 72624, 72750, 72916, 73043, 73209, 73336, 73502, 73628, 73755, 73921, 74048, 74214, 74340, 74507, 74633, 74800, 74926, 75052, 75219, 75345, 75512, 75638, 75804, 75931, 80057, 80224, 80350, 80516, 80643, 80809, 80936, 81102, 81228, 81355, 81521, 81648, 81814, 81940, 82107, 82233, 82400, 82526, 82652, 82819, 82945, 83112, 83238, 83404, 83531, 83657, 83824, 83950, 84116, 84243, 84409, 84536, 84702, 84828, 84955, 85121, 85248, 85414, 85540, 85707, 85833, 90000, 90126, 90252, 90419, 90545, 90712, 90838, 91004, 91131, 91257, 91424, 91550, 91716, 91843, 92009, 92136, 92302, 92428, 92555, 92721, 92848, 93014, 93140, 93307, 93433, 93600, 93726, 93852, 94019, 94145, 94312, 94438, 94604, 94731, 94857, 95024, 95150, 95316, 95443, 95609, 95736, 95902, 100028, 100155, 100321, 100448, 100614, 100740, 100907, 101033, 101200, 101326, 101452, 101619, 101745, 101912, 102038, 102204, 102331, 102457, 102624, 102750, 102916, 103043, 103209, 103336, 103502, 103628, 103755, 103921, 104048, 104214, 104340, 104507, 104633, 104800, 104926, 105052, 105219, 105345, 105512, 105638, 105804, 105931, 110057, 110224, 110350, 110516, 110643, 110809, 110936, 111102, 111228, 111355, 111521, 111648, 111814, 111940, 112107, 112233, 112400, 112526, 112652, 112819, 112945, 113112, 113238, 113404, 113531, 113657, 113824, 113950, 114116, 114243, 114409, 114536, 114702, 114828, 114955, 115121, 115248, 115414, 115540, 115707, 115833, 120000, 120126, 120252, 120419, 120545, 120712, 120838, 121004, 121131, 121257, 121424, 121550, 121716, 121843, 122009, 122136, 122302, 122428, 122555, 122721, 122848, 123014, 123140, 123307, 123433, 123600, 123726, 123852, 124019, 124145, 124312, 124438, 124604, 124731, 124857, 125024, 125150, 125316, 125443, 125609, 125736, 125902, 130028, 130155, 130321, 130448, 130614, 130740, 130907, 131033, 131200, 131326, 131452, 131619, 131745, 131912, 132038, 132204, 132331, 132457, 132624, 132750, 132916, 133043, 133209, 133336, 133502, 133628, 133755, 133921, 134048, 134214, 134340, 134507, 134633, 134800, 134926, 135052, 135219, 135345, 135512, 135638, 135804, 135931, 140057, 140224, 140350, 140516, 140643, 140809, 140936, 141102, 141228, 141355, 141521, 141648, 141814, 141940, 142107, 142233, 142400, 142526, 142652, 142819, 142945, 143112, 143238, 143404, 143531, 143657, 143824, 143950, 144116, 144243, 144409, 144536, 144702, 144828, 144955, 145121, 145248, 145414, 145540, 145707, 145833, 150000, 150126, 150252, 150419, 150545, 150712, 150838, 151004, 151131, 151257, 151424, 151550, 151716, 151843, 152009, 152136, 152302, 152428, 152555, 152721, 152848, 153014, 153140, 153307, 153433, 153600, 153726, 153852, 154019, 154145, 154312, 154438, 154604, 154731, 154857, 155024, 155150, 155316, 155443, 155609, 155736, 155902, 160028, 160155, 160321, 160448, 160614, 160740, 160907, 161033, 161200, 161326, 161452, 161619, 161745, 161912, 162038, 162204, 162331, 162457, 162624, 162750, 162916, 163043, 163209, 163336, 163502, 163628, 163755, 163921, 164048, 164214, 164340, 164507, 164633, 164800, 164926, 165052, 165219, 165345, 165512, 165638, 165804, 165931, 170057, 170224, 170350, 170516, 170643, 170809, 170936, 171102, 171228, 171355, 171521, 171648, 171814, 171940, 172107, 172233, 172400, 172526, 172652, 172819, 172945, 173112, 173238, 173404, 173531, 173657, 173824, 173950, 174116, 174243, 174409, 174536, 174702, 174828, 174955, 175121, 175248, 175414, 175540, 175707, 175833, 180000, 180126, 180252, 180419, 180545, 180712, 180838, 181004, 181131, 181257, 181424, 181550, 181716, 181843, 182009, 182136, 182302, 182428, 182555, 182721, 182848, 183014, 183140, 183307, 183433, 183600, 183726, 183852, 184019, 184145, 184312, 184438, 184604, 184731, 184857, 185024, 185150, 185316, 185443, 185609, 185736, 185902, 190028, 190155, 190321, 190448, 190614, 190740, 190907, 191033, 191200, 191326, 191452, 191619, 191745, 191912, 192038, 192204, 192331, 192457, 192624, 192750, 192916, 193043, 193209, 193336, 193502, 193628, 193755, 193921, 194048, 194214, 194340, 194507, 194633, 194800, 194926, 195052, 195219, 195345, 195512, 195638, 195804, 195931, 200057, 200224, 200350, 200516, 200643, 200809, 200936, 201102, 201228, 201355, 201521, 201648, 201814, 201940, 202107, 202233, 202400, 202526, 202652, 202819, 202945, 203112, 203238, 203404, 203531, 203657, 203824, 203950, 204116, 204243, 204409, 204536, 204702, 204828, 204955, 205121, 205248, 205414, 205540, 205707, 205833, 210000, 210126, 210252, 210419, 210545, 210712, 210838, 211004, 211131, 211257, 211424, 211550, 211716, 211843, 212009, 212136, 212302, 212428, 212555, 212721, 212847, 213014, 213140, 213307, 213433, 213559, 213726, 213852, 214019, 214145, 214311, 214438, 214604, 214731, 214857, 215023, 215150, 215316, 215443, 215609, 215735, 215902, 220028, 220155, 220321, 220447, 220614, 220740, 220907, 221033, 221159, 221326, 221452, 221619, 221745, 221911, 222038, 222204, 222331, 222457, 222623, 222750, 222916, 223043, 223209, 223335, 223502, 223628, 223755, 223921, 224047, 224214, 224340, 224507, 224633, 224759, 224926, 225052, 225219, 225345, 225511, 225638, 225804, 225931, 230057, 230223, 230350, 230516, 230643, 230809, 230935, 231102, 231228, 231355, 231521, 231647, 231814, 231940, 232107, 232233, 232359, 232526, 232652, 232819, 232945, 233111, 233238, 233404, 233531, 233657, 233823, 233950, 234116, 234243, 234409, 234535, 234702, 234828, 234955, 235121, 235247, 235414, 235540, 235707, 235833, 235959};
int steps_index;

void Watchy::init(){
    esp_sleep_wakeup_cause_t wakeup_reason;
    wakeup_reason = esp_sleep_get_wakeup_cause(); //get wake up reason
    Wire.begin(SDA, SCL); //init i2c

    switch (wakeup_reason)
    {
        case ESP_SLEEP_WAKEUP_EXT0: //RTC Alarm
            RTC.alarm(ALARM_1); //resets the alarm flag in the RTC
            if(guiState == WATCHFACE_STATE){
                RTC.read(currentTime);
                temps();
                showWatchFace(true); //partial updates on tick
            }else{
            //
            }
            break;
        case ESP_SLEEP_WAKEUP_EXT1: //button Press
            handleButtonPress();
            break;
        default: //reset
            _rtcConfig();
            temps();
            RTC.alarmInterrupt(ALARM_2, false);
            RTC.alarmInterrupt(ALARM_1, true); //enable alarm interrupt
    RTC.read(currentTime);
            _bmaConfig();
            showWatchFace(false); //full update on reset
            break;
    }
    deepSleep();
}

void Watchy::deepSleep(){
  esp_sleep_enable_ext0_wakeup(RTC_PIN, 0); //enable deep sleep wake on RTC interrupt
  esp_sleep_enable_ext1_wakeup(BTN_PIN_MASK, ESP_EXT1_WAKEUP_ANY_HIGH); //enable deep sleep wake on button press
  esp_deep_sleep_start();
}

void Watchy::_rtcConfig(){
    //https://github.com/JChristensen/DS3232RTC
    RTC.squareWave(SQWAVE_NONE); //disable square wave output
    //RTC.set(compileTime()); //set RTC time to compile time
}

void Watchy::handleButtonPress(){
  uint64_t wakeupBit = esp_sleep_get_ext1_wakeup_status();
  //Menu Button
  if (wakeupBit & MENU_BTN_MASK){
    if(guiState == WATCHFACE_STATE){//enter menu state if coming from watch face
      showMenu(menuIndex, false);
    }else if(guiState == MAIN_MENU_STATE){//if already in menu, then select menu item
      switch(menuIndex)
      {
        case 0:
          showBattery();
          break;
        case 1:
          showBuzz();
          break;          
        case 2:
          showAccelerometer();
          break;
        case 3:
          setTime();
          break;
        case 4:
          setupWifi();
          break;                    
        case 5:
          showUpdateFW();
          break;
        default:
          break;                              
      }
    }else if(guiState == FW_UPDATE_STATE){
      updateFWBegin();
    }
  }
  //Back Button
  else if (wakeupBit & BACK_BTN_MASK){
    if(guiState == MAIN_MENU_STATE){//exit to watch face if already in menu
      RTC.alarm(ALARM_1); //resets the alarm flag in the RTC
      RTC.read(currentTime);
      temps();
      showWatchFace(false);
    }else if(guiState == APP_STATE){
      showMenu(menuIndex, false);//exit to menu if already in app
    }else if(guiState == FW_UPDATE_STATE){
      showMenu(menuIndex, false);//exit to menu if already in app
    }
  }
  //Up Button
  else if (wakeupBit & UP_BTN_MASK){
    if(guiState == MAIN_MENU_STATE){//increment menu index
      menuIndex--;
      if(menuIndex < 0){
        menuIndex = MENU_LENGTH - 1;
      }    
      showMenu(menuIndex, true);
    }
  }
  //Down Button
  else if (wakeupBit & DOWN_BTN_MASK){
    if(guiState == MAIN_MENU_STATE){//decrement menu index
      menuIndex++;
      if(menuIndex > MENU_LENGTH - 1){
        menuIndex = 0;
      }
      showMenu(menuIndex, true);
    }
  }    
}

void Watchy::showMenu(byte menuIndex, bool partialRefresh){
    display.init(0, false); //_initial_refresh to false to prevent full update on init
    display.setFullWindow();
    display.fillScreen(GxEPD_BLACK);
    display.setFont(&FreeMonoBold9pt7b);

    int16_t  x1, y1;
    uint16_t w, h;
    int16_t yPos;

    char *menuItems[] = {"Check Battery", "Vibrate Motor", "Show Accelerometer", "Set Time", "Setup WiFi", "Update Firmware"};
    for(int i=0; i<MENU_LENGTH; i++){
    yPos = 30+(MENU_HEIGHT*i);
    display.setCursor(0, yPos);
    if(i == menuIndex){
        display.getTextBounds(menuItems[i], 0, yPos, &x1, &y1, &w, &h);
        display.fillRect(x1-1, y1-10, 200, h+15, GxEPD_WHITE);
        display.setTextColor(GxEPD_BLACK);
        display.println(menuItems[i]);      
    }else{
        display.setTextColor(GxEPD_WHITE);
        display.println(menuItems[i]);
    }   
    }

    display.display(partialRefresh);
    display.hibernate();

    guiState = MAIN_MENU_STATE;    
}

void Watchy::showBattery(){
    display.init(0, false); //_initial_refresh to false to prevent full update on init
    display.setFullWindow();
    display.fillScreen(GxEPD_BLACK);
    display.setFont(&FreeMonoBold9pt7b);
    display.setTextColor(GxEPD_WHITE);
    display.setCursor(20, 30);
    display.println("Battery Voltage:");
    float voltage = getBatteryVoltage();
    display.setCursor(70, 80);
    display.print(voltage);
    display.println("V");
    display.display(false); //full refresh
    display.hibernate();

    guiState = APP_STATE;      
}

void Watchy::showBuzz(){
    display.init(0, false); //_initial_refresh to false to prevent full update on init
    display.setFullWindow();
    display.fillScreen(GxEPD_BLACK);
    display.setFont(&FreeMonoBold9pt7b);
    display.setTextColor(GxEPD_WHITE);
    display.setCursor(70, 80);
    display.println("Buzz!");
    display.display(false); //full refresh
    display.hibernate();
    vibMotor();
    showMenu(menuIndex, false);    
}

void Watchy::vibMotor(uint8_t intervalMs, uint8_t length){
    pinMode(VIB_MOTOR_PIN, OUTPUT);
    bool motorOn = false;
    for(int i=0; i<length; i++){
        motorOn = !motorOn;
        digitalWrite(VIB_MOTOR_PIN, motorOn);
        delay(intervalMs);
    }
}

void Watchy::setTime(){

    guiState = APP_STATE;

    RTC.read(currentTime);

    int8_t minute = currentTime.Minute;
    int8_t hour = currentTime.Hour;
    int8_t day = currentTime.Day;
    int8_t month = currentTime.Month;
    int8_t year = currentTime.Year + YEAR_OFFSET - 2000;

    int8_t setIndex = SET_HOUR;

    int16_t  x1, y1;
    uint16_t w, h;
    int8_t blink = 0;

    pinMode(DOWN_BTN_PIN, INPUT);
    pinMode(UP_BTN_PIN, INPUT);
    pinMode(MENU_BTN_PIN, INPUT);  
    pinMode(BACK_BTN_PIN, INPUT);  

    display.init(0, true); //_initial_refresh to false to prevent full update on init
    display.setFullWindow();

    while(1){

    if(digitalRead(MENU_BTN_PIN) == 1){
        setIndex++;
        if(setIndex > SET_DAY){
        break;
        }
    }
    if(digitalRead(BACK_BTN_PIN) == 1){
        if(setIndex != SET_HOUR){
        setIndex--;
        }
    }      

    blink = 1 - blink;

    if(digitalRead(DOWN_BTN_PIN) == 1){
        blink = 1;
        switch(setIndex){
        case SET_HOUR:
            hour == 23 ? (hour = 0) : hour++;
            break;
        case SET_MINUTE:
            minute == 59 ? (minute = 0) : minute++;
            break;
        case SET_YEAR:
            year == 99 ? (year = 20) : year++;
            break;
        case SET_MONTH:
            month == 12 ? (month = 1) : month++;
            break;
        case SET_DAY:
            day == 31 ? (day = 1) : day++;
            break;                         
        default:
            break;
        }      
    }

    if(digitalRead(UP_BTN_PIN) == 1){
        blink = 1;
        switch(setIndex){
        case SET_HOUR:
            hour == 0 ? (hour = 23) : hour--;
            break;
        case SET_MINUTE:
            minute == 0 ? (minute = 59) : minute--;
            break;
        case SET_YEAR:
            year == 20 ? (year = 99) : year--;
            break;
        case SET_MONTH:
            month == 1 ? (month = 12) : month--;
            break;
        case SET_DAY:
            day == 1 ? (day = 31) : day--;
            break;          
        default:
            break;
        }   
    }    

    display.fillScreen(GxEPD_BLACK);
    display.setTextColor(GxEPD_WHITE);
    display.setFont(&DSEG7_Classic_Bold_53);

    display.setCursor(5, 80);
    if(setIndex == SET_HOUR){//blink hour digits
        display.setTextColor(blink ? GxEPD_WHITE : GxEPD_BLACK);
    }
    if(hour < 10){
        display.print("0");      
    }
    display.print(hour);

    display.setTextColor(GxEPD_WHITE);
    display.print(":");

    display.setCursor(108, 80);
    if(setIndex == SET_MINUTE){//blink minute digits
        display.setTextColor(blink ? GxEPD_WHITE : GxEPD_BLACK);
    }
    if(minute < 10){
        display.print("0");      
    }
    display.print(minute);

    display.setTextColor(GxEPD_WHITE);

    display.setFont(&FreeMonoBold9pt7b);
    display.setCursor(45, 150);
    if(setIndex == SET_YEAR){//blink minute digits
        display.setTextColor(blink ? GxEPD_WHITE : GxEPD_BLACK);
    }    
    display.print(2000+year);

    display.setTextColor(GxEPD_WHITE);
    display.print("/");

    if(setIndex == SET_MONTH){//blink minute digits
        display.setTextColor(blink ? GxEPD_WHITE : GxEPD_BLACK);
    }   
    if(month < 10){
        display.print("0");      
    }     
    display.print(month);

    display.setTextColor(GxEPD_WHITE);
    display.print("/");

    if(setIndex == SET_DAY){//blink minute digits
        display.setTextColor(blink ? GxEPD_WHITE : GxEPD_BLACK);
    }       
    if(day < 10){
        display.print("0");      
    }     
    display.print(day); 
    display.display(true); //partial refresh
    }

    display.hibernate();

    const time_t FUDGE(10);//fudge factor to allow for upload time, etc. (seconds, YMMV)
    tmElements_t tm;
    tm.Month = month;
    tm.Day = day;
    tm.Year = year + 2000 - YEAR_OFFSET;//offset from 1970, since year is stored in uint8_t
    tm.Hour = hour;
    tm.Minute = minute;
    tm.Second = 0;

    time_t t = makeTime(tm) + FUDGE;
    RTC.set(t);

    showMenu(menuIndex, false);

}

void Watchy::showAccelerometer(){
    display.init(0, true); //_initial_refresh to false to prevent full update on init
    display.setFullWindow();
    display.fillScreen(GxEPD_BLACK);
    display.setFont(&FreeMonoBold9pt7b);
    display.setTextColor(GxEPD_WHITE);

    Accel acc;

    long previousMillis = 0;
    long interval = 200;  

    guiState = APP_STATE;

    pinMode(BACK_BTN_PIN, INPUT);

    while(1){

    unsigned long currentMillis = millis();

    if(digitalRead(BACK_BTN_PIN) == 1){
        break;
    }

    if(currentMillis - previousMillis > interval){
        previousMillis = currentMillis;
        // Get acceleration data
        bool res = sensor.getAccel(acc);
        uint8_t direction = sensor.getDirection();
        display.setFullWindow();
        display.fillScreen(GxEPD_BLACK);      
        display.setCursor(0, 30);
        if(res == false) {
            display.println("getAccel FAIL");
        }else{
        display.print("  X:"); display.println(acc.x);
        display.print("  Y:"); display.println(acc.y);
        display.print("  Z:"); display.println(acc.z);

        display.setCursor(30, 130);
        switch(direction){
            case DIRECTION_DISP_DOWN:
                display.println("FACE DOWN");
                break;
            case DIRECTION_DISP_UP:
                display.println("FACE UP");
                break;
            case DIRECTION_BOTTOM_EDGE:
                display.println("BOTTOM EDGE");
                break;
            case DIRECTION_TOP_EDGE:
                display.println("TOP EDGE");
                break;
            case DIRECTION_RIGHT_EDGE:
                display.println("RIGHT EDGE");
                break;
            case DIRECTION_LEFT_EDGE:
                display.println("LEFT EDGE");
                break;
            default:
                display.println("ERROR!!!");
                break;
        }

        }
        display.display(true); //full refresh
    }
    }

    showMenu(menuIndex, false);
}

void Watchy::showWatchFace(bool partialRefresh){
  display.init(0, false); //_initial_refresh to false to prevent full update on init
  display.setFullWindow();
  drawWatchFace();
  display.display(partialRefresh); //partial refresh
  display.hibernate();
  guiState = WATCHFACE_STATE;
}

void Watchy::drawWatchFace(){
    int x = 100;
    int y = 125;
    
    int16_t x1, y1;
    uint16_t w, h;

    String displayTime;

    display.setFont(&MADE_Sunflower_PERSONAL_USE39pt7b);
    display.setTextWrap(false);

    if (steps_index == 0) {
        displayTime = "NEW";
    } else {
        displayTime = String(1000 - steps_index);
    }  

    display.getTextBounds(displayTime, x, y, &x1, &y1, &w, &h);
    display.setCursor(x - w / 2, y);
    display.print(displayTime); 
}

weatherData Watchy::getWeatherData(){

    weatherData currentWeather;

    if(connectWiFi()){//Use Weather API for live data if WiFi is connected
        HTTPClient http;
        http.setConnectTimeout(3000);//3 second max timeout
        String weatherQueryURL = String(OPENWEATHERMAP_URL) + String(CITY_NAME) + String(",") + String(COUNTRY_CODE) + String("&units=") + String(TEMP_UNIT) + String("&appid=") + String(OPENWEATHERMAP_APIKEY);
        http.begin(weatherQueryURL.c_str());
        int httpResponseCode = http.GET();
        if(httpResponseCode == 200) {
            String payload = http.getString();
            JSONVar responseObject = JSON.parse(payload);
            currentWeather.temperature = int(responseObject["main"]["temp"]);
            currentWeather.weatherConditionCode = int(responseObject["weather"][0]["id"]);            
        }else{
            //http error
        }
        http.end();
        //turn off radios
        WiFi.mode(WIFI_OFF);
        btStop();
    }else{//No WiFi, use RTC Temperature
        uint8_t temperature = RTC.temperature() / 4; //celsius
        if(TEMP_UNIT == "imperial"){
            temperature = temperature * 9. / 5. + 32.; //fahrenheit
        }
        currentWeather.temperature = temperature;
        currentWeather.weatherConditionCode = 800;
    } 
    return currentWeather;
}

float Watchy::getBatteryVoltage(){
    return analogRead(ADC_PIN) / 4096.0 * 7.23;
}

uint16_t Watchy::_readRegister(uint8_t address, uint8_t reg, uint8_t *data, uint16_t len)
{
    Wire.beginTransmission(address);
    Wire.write(reg);
    Wire.endTransmission();
    Wire.requestFrom((uint8_t)address, (uint8_t)len);
    uint8_t i = 0;
    while (Wire.available()) {
        data[i++] = Wire.read();
    }
    return 0;
}

uint16_t Watchy::_writeRegister(uint8_t address, uint8_t reg, uint8_t *data, uint16_t len)
{
    Wire.beginTransmission(address);
    Wire.write(reg);
    Wire.write(data, len);
    return (0 !=  Wire.endTransmission());
}

void Watchy::_bmaConfig(){
 
    if (sensor.begin(_readRegister, _writeRegister, delay) == false) {
        //fail to init BMA
        return;
    }

    // Accel parameter structure
    Acfg cfg;
    /*!
        Output data rate in Hz, Optional parameters:
            - BMA4_OUTPUT_DATA_RATE_0_78HZ
            - BMA4_OUTPUT_DATA_RATE_1_56HZ
            - BMA4_OUTPUT_DATA_RATE_3_12HZ
            - BMA4_OUTPUT_DATA_RATE_6_25HZ
            - BMA4_OUTPUT_DATA_RATE_12_5HZ
            - BMA4_OUTPUT_DATA_RATE_25HZ
            - BMA4_OUTPUT_DATA_RATE_50HZ
            - BMA4_OUTPUT_DATA_RATE_100HZ
            - BMA4_OUTPUT_DATA_RATE_200HZ
            - BMA4_OUTPUT_DATA_RATE_400HZ
            - BMA4_OUTPUT_DATA_RATE_800HZ
            - BMA4_OUTPUT_DATA_RATE_1600HZ
    */
    cfg.odr = BMA4_OUTPUT_DATA_RATE_100HZ;
    /*!
        G-range, Optional parameters:
            - BMA4_ACCEL_RANGE_2G
            - BMA4_ACCEL_RANGE_4G
            - BMA4_ACCEL_RANGE_8G
            - BMA4_ACCEL_RANGE_16G
    */
    cfg.range = BMA4_ACCEL_RANGE_2G;
    /*!
        Bandwidth parameter, determines filter configuration, Optional parameters:
            - BMA4_ACCEL_OSR4_AVG1
            - BMA4_ACCEL_OSR2_AVG2
            - BMA4_ACCEL_NORMAL_AVG4
            - BMA4_ACCEL_CIC_AVG8
            - BMA4_ACCEL_RES_AVG16
            - BMA4_ACCEL_RES_AVG32
            - BMA4_ACCEL_RES_AVG64
            - BMA4_ACCEL_RES_AVG128
    */
    cfg.bandwidth = BMA4_ACCEL_NORMAL_AVG4;

    /*! Filter performance mode , Optional parameters:
        - BMA4_CIC_AVG_MODE
        - BMA4_CONTINUOUS_MODE
    */
    cfg.perf_mode = BMA4_CONTINUOUS_MODE;

    // Configure the BMA423 accelerometer
    sensor.setAccelConfig(cfg);

    // Enable BMA423 accelerometer
    // Warning : Need to use feature, you must first enable the accelerometer
    // Warning : Need to use feature, you must first enable the accelerometer
    sensor.enableAccel();

    struct bma4_int_pin_config config ;
    config.edge_ctrl = BMA4_LEVEL_TRIGGER;
    config.lvl = BMA4_ACTIVE_HIGH;
    config.od = BMA4_PUSH_PULL;
    config.output_en = BMA4_OUTPUT_ENABLE;
    config.input_en = BMA4_INPUT_DISABLE;
    // The correct trigger interrupt needs to be configured as needed
    sensor.setINTPinConfig(config, BMA4_INTR1_MAP);

    struct bma423_axes_remap remap_data;
    remap_data.x_axis = 1;
    remap_data.x_axis_sign = 0;
    remap_data.y_axis = 0;
    remap_data.y_axis_sign = 0;
    remap_data.z_axis  = 2;
    remap_data.z_axis_sign  = 0;
    // Need to raise the wrist function, need to set the correct axis
    sensor.setRemapAxes(&remap_data);

    // Enable BMA423 isStepCounter feature
    sensor.enableFeature(BMA423_STEP_CNTR, true);
    // Enable BMA423 isTilt feature
    sensor.enableFeature(BMA423_TILT, true);
    // Enable BMA423 isDoubleClick feature
    sensor.enableFeature(BMA423_WAKEUP, true);

    // Reset steps
    sensor.resetStepCounter();

    // Turn on feature interrupt
    sensor.enableStepCountInterrupt();
    sensor.enableTiltInterrupt();
    // It corresponds to isDoubleClick interrupt
    sensor.enableWakeupInterrupt();  
}

void Watchy::setupWifi(){
  WiFiManager wifiManager;
  wifiManager.resetSettings();
  wifiManager.setTimeout(WIFI_AP_TIMEOUT);
  wifiManager.setAPCallback(_configModeCallback);
  if(!wifiManager.autoConnect(WIFI_AP_SSID)) {//WiFi setup failed
    display.init(0, false); //_initial_refresh to false to prevent full update on init
    display.setFullWindow();
    display.fillScreen(GxEPD_BLACK);
    display.setFont(&FreeMonoBold9pt7b);
    display.setTextColor(GxEPD_WHITE);
    display.setCursor(0, 30);
    display.println("Setup failed &");
    display.println("timed out!");
    display.display(false); //full refresh
    display.hibernate();
  }else{
    display.init(0, false);//_initial_refresh to false to prevent full update on init
    display.setFullWindow();
    display.fillScreen(GxEPD_BLACK);
    display.setFont(&FreeMonoBold9pt7b);
    display.setTextColor(GxEPD_WHITE);
    display.println("Connected to");
    display.println(WiFi.SSID());
    display.display(false);//full refresh
    display.hibernate();
  }
  //turn off radios
  WiFi.mode(WIFI_OFF);
  btStop();

  guiState = APP_STATE;  
}

void Watchy::_configModeCallback (WiFiManager *myWiFiManager) {
  display.init(0, false); //_initial_refresh to false to prevent full update on init
  display.setFullWindow();
  display.fillScreen(GxEPD_BLACK);
  display.setFont(&FreeMonoBold9pt7b);
  display.setTextColor(GxEPD_WHITE);
  display.setCursor(0, 30);
  display.println("Connect to");
  display.print("SSID: ");
  display.println(WIFI_AP_SSID);
  display.print("IP: ");
  display.println(WiFi.softAPIP());
  display.display(false); //full refresh
  display.hibernate();
}

bool Watchy::connectWiFi(){
    if(WL_CONNECT_FAILED == WiFi.begin()){//WiFi not setup, you can also use hard coded credentials with WiFi.begin(SSID,PASS);
        WIFI_CONFIGURED = false;
    }else{
        if(WL_CONNECTED == WiFi.waitForConnectResult()){//attempt to connect for 10s
            WIFI_CONFIGURED = true;
        }else{//connection failed, time out
            WIFI_CONFIGURED = false;
            //turn off radios
            WiFi.mode(WIFI_OFF);
            btStop();
        }
    }
    return WIFI_CONFIGURED;
}

void Watchy::showUpdateFW(){
    display.init(0, false); //_initial_refresh to false to prevent full update on init
    display.setFullWindow();
    display.fillScreen(GxEPD_BLACK);
    display.setFont(&FreeMonoBold9pt7b);
    display.setTextColor(GxEPD_WHITE);
    display.setCursor(0, 30);
    display.println("Please Visit");
    display.println("watchy.sqfmi.com");
    display.println("with a Bluetooth");
    display.println("enabled device");
    display.println(" ");
    display.println("Press menu button");
    display.println("again when ready");
    display.println(" ");
    display.println("Keep USB powered");
    display.display(false); //full refresh
    display.hibernate();

    guiState = FW_UPDATE_STATE;  
}

void Watchy::updateFWBegin(){
    display.init(0, false); //_initial_refresh to false to prevent full update on init
    display.setFullWindow();
    display.fillScreen(GxEPD_BLACK);
    display.setFont(&FreeMonoBold9pt7b);
    display.setTextColor(GxEPD_WHITE);
    display.setCursor(0, 30);
    display.println("Bluetooth Started");
    display.println(" ");
    display.println("Watchy BLE OTA");
    display.println(" ");
    display.println("Waiting for");
    display.println("connection...");
    display.display(false); //full refresh

    BLE BT;
    BT.begin("Watchy BLE OTA");
    int prevStatus = -1;
    int currentStatus;

    while(1){
    currentStatus = BT.updateStatus();
    if(prevStatus != currentStatus || prevStatus == 1){
        if(currentStatus == 0){
        display.setFullWindow();
        display.fillScreen(GxEPD_BLACK);
        display.setFont(&FreeMonoBold9pt7b);
        display.setTextColor(GxEPD_WHITE);
        display.setCursor(0, 30);
        display.println("BLE Connected!");
        display.println(" ");
        display.println("Waiting for");
        display.println("upload...");
        display.display(false); //full refresh
        }
        if(currentStatus == 1){
        display.setFullWindow();
        display.fillScreen(GxEPD_BLACK);
        display.setFont(&FreeMonoBold9pt7b);
        display.setTextColor(GxEPD_WHITE);
        display.setCursor(0, 30);
        display.println("Downloading");
        display.println("firmware:");
        display.println(" ");
        display.print(BT.howManyBytes());
        display.println(" bytes");
        display.display(true); //partial refresh        
        }
        if(currentStatus == 2){
        display.setFullWindow();
        display.fillScreen(GxEPD_BLACK);
        display.setFont(&FreeMonoBold9pt7b);
        display.setTextColor(GxEPD_WHITE);
        display.setCursor(0, 30);
        display.println("Download");
        display.println("completed!");
        display.println(" ");
        display.println("Rebooting...");
        display.display(false); //full refresh

        delay(2000);
        esp_restart();           
        }
        if(currentStatus == 4){
        display.setFullWindow();
        display.fillScreen(GxEPD_BLACK);
        display.setFont(&FreeMonoBold9pt7b);
        display.setTextColor(GxEPD_WHITE);
        display.setCursor(0, 30);
        display.println("BLE Disconnected!");
        display.println(" ");
        display.println("exiting...");
        display.display(false); //full refresh
        delay(1000);
        break;
        }
        prevStatus = currentStatus;
    }
    delay(100);
    }

    //turn off radios
    WiFi.mode(WIFI_OFF);
    btStop();
    showMenu(menuIndex, false);
}

void Watchy::temps(){
    String seconds;
    String minutes;
    String hours;

    String curr_time;

    String next_step;

    int sets;
    int setm;

    RTC.read(currentTime);

    seconds = String(currentTime.Second);
    minutes = String(currentTime.Minute);
    hours = String(currentTime.Hour);

    if (currentTime.Second < 10) {
        seconds = 0 + seconds;
    }

    if (currentTime.Minute < 10) {
        minutes = 0 + minutes;
    }

    curr_time = hours + minutes + seconds;

    for (int x = 0; x < 1000; x++) {
        if (curr_time.toInt() < steps[x]) {
            next_step = String(steps[x]);
            steps_index = x;
            break;
        }
    }

    if (next_step.length() == 3) {
        sets = (next_step.substring(1,3)).toInt();
        setm = (next_step.substring(0,1)).toInt();
        } else if (next_step.length() == 4) {
        sets = (next_step.substring(2,4)).toInt();
        setm = (next_step.substring(0,2)).toInt();
        } else if (next_step.length() == 5) {
        sets = (next_step.substring(3,5)).toInt();
        setm = (next_step.substring(1,3)).toInt();
        } else {
        sets = (next_step.substring(4,6)).toInt();
        setm = (next_step.substring(2,4)).toInt();
    }

    RTC.setAlarm(ALM1_MATCH_MINUTES, sets, setm, 0, 0); //alarm wakes up Watchy every minute
}

// time_t compileTime()
// {   
//     const time_t FUDGE(10);    //fudge factor to allow for upload time, etc. (seconds, YMMV)
//     const char *compDate = __DATE__, *compTime = __TIME__, *months = "JanFebMarAprMayJunJulAugSepOctNovDec";
//     char compMon[3], *m;

//     strncpy(compMon, compDate, 3);
//     compMon[3] = '\0';
//     m = strstr(months, compMon);

//     tmElements_t tm;
//     tm.Month = ((m - months) / 3 + 1);
//     tm.Day = atoi(compDate + 4);
//     tm.Year = atoi(compDate + 7) - YEAR_OFFSET; // offset from 1970, since year is stored in uint8_t
//     tm.Hour = atoi(compTime);
//     tm.Minute = atoi(compTime + 3);
//     tm.Second = atoi(compTime + 6);

//     time_t t = makeTime(tm);
//     return t + FUDGE;        //add fudge factor to allow for compile time
// }