-
Notifications
You must be signed in to change notification settings - Fork 70
/
main.cpp
1237 lines (1138 loc) · 48.3 KB
/
main.cpp
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
/**
* @file main
*
*/
/*********************
* INCLUDES
*********************/
#define _DEFAULT_SOURCE /* needed for usleep() */
#include <stdlib.h>
#include <unistd.h>
#define SDL_MAIN_HANDLED /*To fix SDL's "undefined reference to WinMain" issue*/
#include <SDL2/SDL.h>
#include "lvgl/lvgl.h"
//#include "lvgl/examples/lv_examples.h"
//#include "lv_demos/lv_demo.h"
#include "lv_drivers/display/monitor.h"
#include "lv_drivers/indev/mouse.h"
#include "lv_drivers/indev/keyboard.h"
#include "lv_drivers/indev/mousewheel.h"
# // be sure to get the sim headers for SimpleWeatherService.h
#include "host/ble_gatt.h"
#include "host/ble_uuid.h"
// get PineTime header
#include "displayapp/InfiniTimeTheme.h"
#include <drivers/Hrs3300.h>
#include <drivers/Bma421.h>
#include "BootloaderVersion.h"
#include "components/battery/BatteryController.h"
#include "components/ble/BleController.h"
#include "components/ble/NotificationManager.h"
#include "components/brightness/BrightnessController.h"
#include "components/motor/MotorController.h"
#include "components/datetime/DateTimeController.h"
#include "components/heartrate/HeartRateController.h"
#include "components/fs/FS.h"
#include "drivers/Spi.h"
#include "drivers/SpiMaster.h"
#include "drivers/SpiNorFlash.h"
#include "drivers/St7789.h"
#include "drivers/TwiMaster.h"
#include "drivers/Cst816s.h"
#include "drivers/PinMap.h"
#include "systemtask/SystemTask.h"
#include "drivers/PinMap.h"
#include "touchhandler/TouchHandler.h"
#include "buttonhandler/ButtonHandler.h"
// get the simulator-headers
#include "displayapp/DisplayApp.h"
#include "displayapp/LittleVgl.h"
#include <nrfx_gpiote.h>
#include <hal/nrf_gpio.h>
#include <mdk/nrf52.h> // initialize NRF_WDT and NRF_POWER
#include <iostream>
#include <typeinfo>
#include <algorithm>
#include <array>
#include <vector>
#include <span>
#include <cmath> // std::pow
// additional includes for 'saveScreenshot()' function
#include <iomanip> // put_time
#include <sstream>
#include <chrono>
#include <ctime> // localtime
#if defined(WITH_PNG)
#include <png.h>
#endif
#include <gif.h>
#include "img/sim_background.h" // provides variable SIM_BACKGROUND
/*********************
* DEFINES
*********************/
/**********************
* TYPEDEFS
**********************/
// copied from lv_drivers/display/monitor.c to get the SDL_Window for the InfiniTime screen
extern "C"
{
typedef struct {
SDL_Window * window;
SDL_Renderer * renderer;
SDL_Texture * texture;
volatile bool sdl_refr_qry;
#if MONITOR_DOUBLE_BUFFERED
uint32_t * tft_fb_act;
#else
uint32_t tft_fb[LV_HOR_RES_MAX * LV_VER_RES_MAX];
#endif
}monitor_t;
extern monitor_t monitor;
}
void saveScreenshot()
{
auto now = std::chrono::system_clock::now();
auto in_time_t = std::chrono::system_clock::to_time_t(now);
// timestamped png filename
std::stringstream ss;
ss << "InfiniSim_" << std::put_time(std::localtime(&in_time_t), "%F_%H%M%S");
std::string screenshot_filename_base = ss.str();
// TODO: use std::format once we have C++20 and new enough GCC 13
//std::string screenshot_filename_base = std::format("InfiniSim_%F_%H%M%S", std::chrono::floor<std::chrono::seconds>(now));
//std::string screenshot_filename_base = "InfiniSim";
const int width = 240;
const int height = 240;
auto renderer = monitor.renderer;
#if defined(WITH_PNG)
std::string screenshot_filename = screenshot_filename_base + ".png";
FILE * fp2 = fopen(screenshot_filename.c_str(), "wb");
if (!fp2) {
// dealing with error
return;
}
// 1. Create png struct pointer
png_structp png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
if (!png_ptr){
// dealing with error
}
png_infop info_ptr = png_create_info_struct(png_ptr);
if (!info_ptr) {
png_destroy_write_struct(&png_ptr, (png_infopp)NULL);
// dealing with error
}
int bit_depth = 8;
png_init_io(png_ptr, fp2);
png_set_IHDR(png_ptr, info_ptr, width, height, bit_depth, \
PNG_COLOR_TYPE_RGBA, PNG_INTERLACE_NONE, \
PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT);
// 3. Convert 1d array to 2d array to be suitable for png struct
// I assumed the original array is 1d
std::array<png_bytep, 240> row_pointers;
//png_bytepp row_pointers = (png_bytepp)png_malloc(png_ptr, sizeof(png_bytep) * height);
for (int i = 0; i < height; i++) {
row_pointers[i] = (png_bytep)png_malloc(png_ptr, width*4);
}
constexpr size_t zoom = MONITOR_ZOOM;
const Uint32 format = SDL_PIXELFORMAT_RGBA8888;
SDL_Surface *surface = SDL_CreateRGBSurfaceWithFormat(0, width*zoom, height*zoom, 32, format);
SDL_RenderReadPixels(renderer, NULL, format, surface->pixels, surface->pitch);
png_bytep pixels = (png_bytep)surface->pixels;
for (int hi = 0; hi < height; hi++) {
for (int wi = 0; wi < width; wi++) {
int c = wi * 4;
row_pointers.at(hi)[wi*4+0] = pixels[hi*surface->pitch*zoom + wi*4*zoom + 3]; // red
row_pointers.at(hi)[wi*4+1] = pixels[hi*surface->pitch*zoom + wi*4*zoom + 2]; // greeen
row_pointers.at(hi)[wi*4+2] = pixels[hi*surface->pitch*zoom + wi*4*zoom + 1]; // blue
row_pointers.at(hi)[wi*4+3] = 255; // alpha
}
}
// 4. Write png file
png_write_info(png_ptr, info_ptr);
png_write_image(png_ptr, row_pointers.data());
png_write_end(png_ptr, info_ptr);
png_destroy_write_struct(&png_ptr, &info_ptr);
fclose(fp2);
SDL_FreeSurface(surface);
#else
std::string screenshot_filename = screenshot_filename_base + ".bmp";
const Uint32 format = SDL_PIXELFORMAT_RGB888;
SDL_Surface *surface = SDL_CreateRGBSurfaceWithFormat(0, width, height, 24, format);
SDL_RenderReadPixels(renderer, NULL, format, surface->pixels, surface->pitch);
SDL_SaveBMP(surface, screenshot_filename.c_str());
SDL_FreeSurface(surface);
#endif
std::cout << "InfiniSim: Screenshot created: " << screenshot_filename << std::endl;
}
class GifManager
{
private:
GifWriter writer = {};
std::chrono::system_clock::time_point last_frame;
bool in_progress = false;
static constexpr uint32_t delay_ds = 100/20; // in 1/100 s, so 1 ds = 10 ms
static constexpr int sdl_width = 240;
static constexpr int sdl_height = 240;
public:
GifManager()
{}
~GifManager()
{
if (in_progress) {
close();
}
}
bool is_in_progress() const
{
return in_progress;
}
void create_new()
{
assert(!in_progress);
auto now = std::chrono::system_clock::now();
auto in_time_t = std::chrono::system_clock::to_time_t(now);
// timestamped png filename
std::stringstream ss;
ss << "InfiniSim_" << std::put_time(std::localtime(&in_time_t), "%F_%H%M%S");
std::string screenshot_filename_base = ss.str();
// TODO: use std::format once we have C++20 and new enough GCC 13
//std::string screenshot_filename_base = std::format("InfiniSim_%F_%H%M%S", std::chrono::floor<std::chrono::seconds>(now));
std::string screenshot_filename = screenshot_filename_base + ".gif";
std::cout << "InfiniSim: Screen-capture started: " << screenshot_filename << std::endl;
GifBegin( &writer, screenshot_filename.c_str(), sdl_width, sdl_height, delay_ds, 8, true );
in_progress = true;
write_frame(true);
}
void write_frame(bool force = false)
{
assert(in_progress);
auto now = std::chrono::system_clock::now();
if (force || ((now - last_frame) > std::chrono::milliseconds(delay_ds*10)) )
{
last_frame = std::chrono::system_clock::now();
auto renderer = monitor.renderer;
constexpr size_t zoom = MONITOR_ZOOM;
const Uint32 format = SDL_PIXELFORMAT_RGBA8888;
SDL_Surface *surface = SDL_CreateRGBSurfaceWithFormat(0, sdl_width*zoom, sdl_height*zoom, 32, format);
SDL_RenderReadPixels(renderer, NULL, format, surface->pixels, surface->pitch);
uint8_t *pixels = (uint8_t*) surface->pixels;
std::array<uint8_t, 240*240*4> image;
for (int hi = 0; hi < sdl_height; hi++) {
for (int wi = 0; wi < sdl_width; wi++) {
auto red = pixels[hi*surface->pitch*zoom + wi*4*zoom + 3]; // red
auto green = pixels[hi*surface->pitch*zoom + wi*4*zoom + 2]; // green
auto blue = pixels[hi*surface->pitch*zoom + wi*4*zoom + 1]; // blue
image[(hi * sdl_width + wi)*4 + 0] = red;
image[(hi * sdl_width + wi)*4 + 1] = green;
image[(hi * sdl_width + wi)*4 + 2] = blue;
image[(hi * sdl_width + wi)*4 + 3] = 255; // no alpha
}
}
GifWriteFrame(&writer, image.data(), sdl_width, sdl_height, delay_ds, 8, false);
}
}
void close()
{
assert(in_progress);
in_progress = false;
GifEnd(&writer);
std::cout << "InfiniSim: Screen-capture finished" << std::endl;
}
};
/**********************
* STATIC PROTOTYPES
**********************/
static void hal_init(void);
static int tick_thread(void *data);
/**********************
* STATIC VARIABLES
**********************/
lv_indev_t *kb_indev;
lv_indev_t *mouse_indev = nullptr;
/**********************
* MACROS
**********************/
/**********************
* GLOBAL FUNCTIONS
**********************/
void nrfx_gpiote_evt_handler(nrfx_gpiote_pin_t pin, nrf_gpiote_polarity_t action) {}
/*********************
* DEFINES
*********************/
/**********************
* TYPEDEFS
**********************/
/**********************
* VARIABLES
**********************/
/**********************
* STATIC PROTOTYPES
**********************/
/**********************
* GLOBAL FUNCTIONS
**********************/
constexpr NRF_TWIM_Type *NRF_TWIM1 = nullptr;
static constexpr uint8_t touchPanelTwiAddress = 0x15;
static constexpr uint8_t motionSensorTwiAddress = 0x18;
static constexpr uint8_t heartRateSensorTwiAddress = 0x44;
Pinetime::Drivers::SpiMaster spi {Pinetime::Drivers::SpiMaster::SpiModule::SPI0,
{Pinetime::Drivers::SpiMaster::BitOrder::Msb_Lsb,
Pinetime::Drivers::SpiMaster::Modes::Mode3,
Pinetime::Drivers::SpiMaster::Frequencies::Freq8Mhz,
Pinetime::PinMap::SpiSck,
Pinetime::PinMap::SpiMosi,
Pinetime::PinMap::SpiMiso}};
Pinetime::Drivers::Spi lcdSpi {spi, Pinetime::PinMap::SpiLcdCsn};
Pinetime::Drivers::St7789 lcd {lcdSpi, Pinetime::PinMap::LcdDataCommand, Pinetime::PinMap::LcdReset};
Pinetime::Drivers::Spi flashSpi {spi, Pinetime::PinMap::SpiFlashCsn};
Pinetime::Drivers::SpiNorFlash spiNorFlash {"spiNorFlash.raw"};
// The TWI device should work @ up to 400Khz but there is a HW bug which prevent it from
// respecting correct timings. According to erratas heet, this magic value makes it run
// at ~390Khz with correct timings.
static constexpr uint32_t MaxTwiFrequencyWithoutHardwareBug {0x06200000};
Pinetime::Drivers::TwiMaster twiMaster {NRF_TWIM1, MaxTwiFrequencyWithoutHardwareBug, Pinetime::PinMap::TwiSda, Pinetime::PinMap::TwiScl};
Pinetime::Drivers::Cst816S touchPanel; // {twiMaster, touchPanelTwiAddress};
//#ifdef PINETIME_IS_RECOVERY
// #include "displayapp/DummyLittleVgl.h"
// #include "displayapp/DisplayAppRecovery.h"
//#else
// #include "displayapp/LittleVgl.h"
// #include "displayapp/DisplayApp.h"
//#endif
Pinetime::Drivers::Bma421 motionSensor {twiMaster, motionSensorTwiAddress};
Pinetime::Drivers::Hrs3300 heartRateSensor {twiMaster, heartRateSensorTwiAddress};
TimerHandle_t debounceTimer;
TimerHandle_t debounceChargeTimer;
Pinetime::Controllers::Battery batteryController;
Pinetime::Controllers::Ble bleController;
Pinetime::Controllers::HeartRateController heartRateController;
Pinetime::Applications::HeartRateTask heartRateApp(heartRateSensor, heartRateController);
Pinetime::Controllers::FS fs {spiNorFlash};
Pinetime::Controllers::Settings settingsController {fs};
Pinetime::Controllers::MotorController motorController {};
Pinetime::Controllers::DateTime dateTimeController {settingsController};
Pinetime::Drivers::Watchdog watchdog;
Pinetime::Controllers::NotificationManager notificationManager;
Pinetime::Controllers::MotionController motionController;
#if defined(INFINITIME_TIMERCONTROLLER)
Pinetime::Controllers::TimerController timerController;
#endif
#if defined(ALARMCONTROLLER_NEEDS_FS)
Pinetime::Controllers::AlarmController alarmController {dateTimeController, fs};
#else
Pinetime::Controllers::AlarmController alarmController {dateTimeController};
#endif
Pinetime::Controllers::TouchHandler touchHandler;
Pinetime::Controllers::ButtonHandler buttonHandler;
Pinetime::Controllers::BrightnessController brightnessController {};
Pinetime::Applications::DisplayApp displayApp(lcd,
touchPanel,
batteryController,
bleController,
dateTimeController,
watchdog,
notificationManager,
heartRateController,
settingsController,
motorController,
motionController,
#if defined(INFINITIME_TIMERCONTROLLER)
timerController,
#endif
alarmController,
brightnessController,
touchHandler,
fs,
spiNorFlash);
Pinetime::System::SystemTask systemTask(spi,
spiNorFlash,
twiMaster,
touchPanel,
batteryController,
bleController,
dateTimeController,
#if defined(INFINITIME_TIMERCONTROLLER)
timerController,
#endif
alarmController,
watchdog,
notificationManager,
heartRateSensor,
motionController,
motionSensor,
settingsController,
heartRateController,
displayApp,
heartRateApp,
fs,
touchHandler,
buttonHandler);
// variable used in SystemTask.cpp Work loop
std::chrono::time_point<std::chrono::system_clock, std::chrono::nanoseconds> NoInit_BackUpTime;
class Framework {
public:
// Contructor which initialize the parameters.
Framework(bool visible_, int height_, int width_) :
visible(visible_), height(height_), width(width_)
{
if (visible) {
//SDL_Init(SDL_INIT_VIDEO); // Initializing SDL as Video
SDL_CreateWindowAndRenderer(width, height, 0, &window, &renderer);
SDL_SetWindowTitle(window, "LV Simulator Status");
{ // move window a bit to the right, to not be over the PineTime Screen
int x,y;
SDL_GetWindowPosition(window, &x, &y);
SDL_SetWindowPosition(window, x+LV_HOR_RES_MAX, y);
}
SDL_SetRenderDrawColor(renderer, 0, 0, 0, 0); // setting draw color
SDL_RenderClear(renderer); // Clear the newly created window
SDL_RenderPresent(renderer); // Reflects the changes done in the
// window.
}
init_NRF_WDT();
init_NRF_POWER();
// Attempt to load background BMP from memory for the status display window
const size_t SIM_BACKGROUND_size = sizeof(SIM_BACKGROUND);
SDL_RWops *rw = SDL_RWFromMem((void*)SIM_BACKGROUND, SIM_BACKGROUND_size);
SDL_Surface* simDisplayBgRaw = SDL_LoadBMP_RW(rw, 1);
if (simDisplayBgRaw == NULL) {
printf("Failed to load sim background image: %s\n", SDL_GetError());
} else {
// convert the loaded image into a texture
simDisplayTexture = SDL_CreateTextureFromSurface(renderer, simDisplayBgRaw);
SDL_FreeSurface(simDisplayBgRaw);
simDisplayBgRaw = NULL;
}
motorController.Init();
settingsController.Init();
printf("initial free_size = %u\n", xPortGetFreeHeapSize());
// update time to current system time once on startup
dateTimeController.SetCurrentTime(std::chrono::system_clock::now());
systemTask.Start();
// initialize the first LVGL screen
//const auto clockface = settingsController.GetClockFace();
//switch_to_screen(1+clockface);
}
// Destructor
~Framework(){
if (simDisplayTexture != NULL) {
SDL_DestroyTexture(simDisplayTexture);
}
SDL_DestroyRenderer(renderer);
SDL_DestroyWindow(window);
SDL_Quit();
}
void draw_circle_red(int center_x, int center_y, int radius_){
SDL_SetRenderDrawColor(renderer, 255, 0, 0, 255);
draw_circle_(center_x, center_y, radius_);
}
void draw_circle_green(int center_x, int center_y, int radius_){
SDL_SetRenderDrawColor(renderer, 0, 255, 0, 255);
draw_circle_(center_x, center_y, radius_);
}
void draw_circle_blue(int center_x, int center_y, int radius_){
SDL_SetRenderDrawColor(renderer, 0, 0, 255, 255);
draw_circle_(center_x, center_y, radius_);
}
void draw_circle_yellow(int center_x, int center_y, int radius_){
SDL_SetRenderDrawColor(renderer, 255, 255, 0, 255);
draw_circle_(center_x, center_y, radius_);
}
void draw_circle_grey(int center_x, int center_y, int radius_){
SDL_SetRenderDrawColor(renderer, 128, 128, 128, 255);
draw_circle_(center_x, center_y, radius_);
}
void draw_circle_white(int center_x, int center_y, int radius_){
SDL_SetRenderDrawColor(renderer, 255, 255, 255, 255);
draw_circle_(center_x, center_y, radius_);
}
void draw_circle_(int center_x, int center_y, int radius_){
// Drawing circle
for(int x=center_x-radius_; x<=center_x+radius_; x++){
for(int y=center_y-radius_; y<=center_y+radius_; y++){
if((std::pow(center_y-y,2)+std::pow(center_x-x,2)) <=
std::pow(radius_,2)){
SDL_RenderDrawPoint(renderer, x, y);
}
}
}
}
void refresh() {
// left edge for all "bubbles" (circles)
constexpr const int bubbleLeftEdge = 65;
// always refresh the LVGL screen
this->refresh_screen();
if (!visible) {
return;
}
SDL_SetRenderDrawColor(renderer, 0, 0, 0, 0);
SDL_RenderClear(renderer);
// Render the background if it was able to be loaded
if (simDisplayTexture != NULL) {
SDL_RenderCopy(renderer, simDisplayTexture, NULL, NULL);
}
{ // motorController.motor_is_running
constexpr const int center_x = bubbleLeftEdge;
constexpr const int center_y = 216;
bool motor_is_running = nrf_gpio_pin_read(Pinetime::PinMap::Motor);
if (motor_is_running) {
draw_circle_red(center_x, center_y, 15);
} else {
draw_circle_grey(center_x, center_y, 15);
}
}
{ // ble.motor_is_running
constexpr const int center_x = bubbleLeftEdge;
constexpr const int center_y = 24;
if (bleController.IsConnected()) {
draw_circle_blue(center_x, center_y, 15);
} else {
draw_circle_grey(center_x, center_y, 15);
}
}
// batteryController.percentRemaining
{
const int center_x = bubbleLeftEdge;
const int center_y = 164;
const int max_bar_length = 150;
const int filled_bar_length = max_bar_length * (batteryController.percentRemaining/100.0);
const int rect_height = 14;
SDL_Rect rect {
.x = center_x - rect_height/2,
.y = center_y,
.w = max_bar_length,
.h = rect_height
};
SDL_SetRenderDrawColor(renderer, 128, 128, 128, 255);
SDL_RenderDrawRect(renderer, &rect);
rect.w = filled_bar_length;
rect.h++;
rect.h-=2;
SDL_SetRenderDrawColor(renderer, 0, 255, 0, 255);
SDL_RenderFillRect(renderer, &rect);
//set color and new x pos, draw again
}
{ // batteryController.isCharging
constexpr const int center_x = bubbleLeftEdge;
constexpr const int center_y = 120;
if (batteryController.isCharging) {
draw_circle_yellow(center_x, center_y, 15);
} else
{
draw_circle_grey(center_x, center_y, 15);
}
}
{ // brightnessController.Level
constexpr const int center_y = 72;
const Pinetime::Controllers::BrightnessController::Levels level = brightnessController.Level();
uint8_t level_idx = 0;
if (level == Pinetime::Controllers::BrightnessController::Levels::Low)
{
level_idx = 1;
} else if (level == Pinetime::Controllers::BrightnessController::Levels::Medium)
{
level_idx = 2;
} else if (level == Pinetime::Controllers::BrightnessController::Levels::High)
{
level_idx = 3;
}
for (uint8_t i=0; i<4; i++) {
const int bubble_size = (i*2) + 5;
const int center_x = bubbleLeftEdge + ((bubble_size+10) * i) - 5;
if (i <= level_idx) {
draw_circle_white(center_x, center_y, bubble_size);
} else {
draw_circle_grey(center_x, center_y, bubble_size);
}
}
}
// Show the change on the screen
SDL_RenderPresent(renderer);
}
// prepared notficitions, one per message category
const std::vector<std::string> notification_messages {
"0category:\nUnknown",
"Lorem ipsum\ndolor sit amet,\nconsectetur adipiscing elit,\n",
"1SimpleAlert",
"sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.",
"2Email:",
"Vitae aliquet nec ullamcorper sit amet.",
"3News:",
"Id\naliquet\nrisus\nfeugiat\nin\nante\nmetus\ndictum\nat.",
"4IncomingCall:",
"Ut porttitor leo a diam sollicitudin.",
"5MissedCall:",
"Ultrices tincidunt arcu non sodales neque sodales ut etiam sit.",
"6Sms:",
"Pellentesque dignissim enim sit amet.",
"7VoiceMail:",
"Urna nec tincidunt praesent semper feugiat nibh sed pulvinar proin.",
"8Schedule:",
"Tellus id interdum velit laoreet id donec ultrices tincidunt.",
"9HighProriotyAlert:",
"Viverra maecenas accumsan lacus vel facilisis volutpat est velit egestas.",
"10InstantMessage:",
"Volutpat consequat mauris nunc congue.",
};
size_t notification_idx = 0; // which message to send next
void send_notification() {
Pinetime::Controllers::NotificationManager::Notification notif;
const std::string &title = notification_messages.at(notification_idx*2);
const std::string &message = notification_messages.at(notification_idx*2+1);
std::copy(title.begin(), title.end(), notif.message.data());
notif.message[title.size()] = '\0'; // title and message is \0 separated
std::copy(message.begin(), message.end(), notif.message.data()+title.size()+1);
notif.message[title.size() + 1 + message.size()] = '\0'; // zero terminate the message
notif.size = title.size() + 1 + message.size();
notif.category = static_cast<Pinetime::Controllers::NotificationManager::Categories>(notification_idx % 11);
notificationManager.Push(std::move(notif));
// send next message the next time
notification_idx++;
if (notification_idx >= notification_messages.size()/2) {
notification_idx = 0;
}
if (settingsController.GetNotificationStatus() == Pinetime::Controllers::Settings::Notification::On)
{
if (screen_off_created) {
// wake up! (deletes screen_off label)
systemTask.PushMessage(Pinetime::System::Messages::GoToRunning);
}
displayApp.PushMessage(Pinetime::Applications::Display::Messages::NewNotification);
}
}
// can't use SDL_PollEvent, as those are fed to lvgl
// implement a non-descructive key-pressed handler (as not consuming SDL_Events)
void handle_keys() {
const Uint8 *state = SDL_GetKeyboardState(NULL);
const bool key_shift = state[SDL_SCANCODE_LSHIFT] || state[SDL_SCANCODE_RSHIFT];
auto debounce = [&] (const char key_low, const char key_capital, const bool scancode, bool &key_handled) {
if (scancode && !key_handled) {
if (key_shift) {
this->handle_key(key_capital);
} else {
this->handle_key(key_low);
}
key_handled = true;
} else if (scancode && key_handled) {
// ignore, already handled
} else {
key_handled = false;
}
};
debounce('r', 'R', state[SDL_SCANCODE_R], key_handled_r);
debounce('n', 'N', state[SDL_SCANCODE_N], key_handled_n);
debounce('m', 'M', state[SDL_SCANCODE_M], key_handled_m);
debounce('b', 'B', state[SDL_SCANCODE_B], key_handled_b);
debounce('v', 'V', state[SDL_SCANCODE_V], key_handled_v);
debounce('c', 'C', state[SDL_SCANCODE_C], key_handled_c);
debounce('l', 'L', state[SDL_SCANCODE_L], key_handled_l);
debounce('p', 'P', state[SDL_SCANCODE_P], key_handled_p);
debounce('s', 'S', state[SDL_SCANCODE_S], key_handled_s);
debounce('h', 'H', state[SDL_SCANCODE_H], key_handled_h);
debounce('i', 'I', state[SDL_SCANCODE_I], key_handled_i);
debounce('w', 'W', state[SDL_SCANCODE_W], key_handled_w);
// screen switcher buttons
debounce('1', '!'+1, state[SDL_SCANCODE_1], key_handled_1);
debounce('2', '!'+2, state[SDL_SCANCODE_2], key_handled_2);
debounce('3', '!'+3, state[SDL_SCANCODE_3], key_handled_3);
debounce('4', '!'+4, state[SDL_SCANCODE_4], key_handled_4);
debounce('5', '!'+5, state[SDL_SCANCODE_5], key_handled_5);
debounce('6', '!'+6, state[SDL_SCANCODE_6], key_handled_6);
debounce('7', '!'+7, state[SDL_SCANCODE_7], key_handled_7);
debounce('8', '!'+8, state[SDL_SCANCODE_8], key_handled_8);
debounce('9', '!'+9, state[SDL_SCANCODE_9], key_handled_9);
debounce('0', '!'+0, state[SDL_SCANCODE_0], key_handled_0);
// direction keys
debounce(':', ':', state[SDL_SCANCODE_UP], key_handled_up);
debounce(';', ';', state[SDL_SCANCODE_DOWN], key_handled_down);
debounce('<', '<', state[SDL_SCANCODE_LEFT], key_handled_left);
debounce('>', '>', state[SDL_SCANCODE_RIGHT], key_handled_right);
}
// inject a swipe gesture to the touch handler and notify displayapp to notice it
void send_gesture(Pinetime::Drivers::Cst816S::Gestures gesture)
{
Pinetime::Drivers::Cst816S::TouchInfos info;
info.isValid = true;
info.touching = true;
info.gesture = gesture;
touchHandler.ProcessTouchInfo(info);
displayApp.PushMessage(Pinetime::Applications::Display::Messages::TouchEvent);
info.touching = false;
info.gesture = Pinetime::Drivers::Cst816S::Gestures::None;
touchHandler.ProcessTouchInfo(info);
}
// modify the simulated controller depending on the pressed key
void handle_key(SDL_Keycode key) {
if (key == 'r') {
motorController.StartRinging();
} else if (key == 'R') {
motorController.StopRinging();
} else if (key == 'm') {
motorController.RunForDuration(100);
} else if (key == 'M') {
motorController.RunForDuration(255);
} else if (key == 'n') {
send_notification();
} else if (key == 'N') {
notificationManager.ClearNewNotificationFlag();
} else if (key == 'b') {
bleController.Connect();
} else if (key == 'B') {
bleController.Disconnect();
} else if (key == 'v') {
if (batteryController.percentRemaining >= 90) {
batteryController.percentRemaining = 100;
} else {
batteryController.percentRemaining += 10;
}
} else if (key == 'V') {
if (batteryController.percentRemaining <= 10) {
batteryController.percentRemaining = 0;
} else {
batteryController.percentRemaining -= 10;
}
} else if (key == 'c') {
batteryController.isCharging = true;
batteryController.isPowerPresent = true;
} else if (key == 'C') {
batteryController.isCharging = false;
batteryController.isPowerPresent = false;
} else if (key == 'l' && !screen_off_created) {
brightnessController.Higher();
} else if (key == 'L' && !screen_off_created) {
brightnessController.Lower();
} else if (key == 'p') {
this->print_memory_usage = true;
} else if (key == 'P') {
this->print_memory_usage = false;
} else if (key == 's') {
motionSensor.steps += 500;
} else if (key == 'S') {
if (motionSensor.steps > 500) {
motionSensor.steps -= 500;
} else {
motionSensor.steps = 0;
}
} else if (key == 'h') {
if (heartRateController.State() == Pinetime::Controllers::HeartRateController::States::Stopped) {
heartRateController.Start();
} else if (heartRateController.State() == Pinetime::Controllers::HeartRateController::States::NotEnoughData) {
heartRateController.Update(Pinetime::Controllers::HeartRateController::States::Running, 10);
} else {
uint8_t heartrate = heartRateController.HeartRate();
heartRateController.Update(Pinetime::Controllers::HeartRateController::States::Running, heartrate + 10);
}
} else if (key == 'H') {
heartRateController.Stop();
} else if (key == 'i') {
saveScreenshot();
} else if (key == 'I') {
if (!gif_manager.is_in_progress())
{
gif_manager.create_new();
} else {
gif_manager.close();
}
} else if (key == 'w') {
generate_weather_data(false);
} else if (key == 'W') {
generate_weather_data(true);
} else if (key >= '0' && key <= '9') {
this->switch_to_screen(key-'0');
} else if (key >= '!'+0 && key <= '!'+9) {
this->switch_to_screen(key-'!'+10);
} else if (key == ':') { // up
send_gesture(Pinetime::Drivers::Cst816S::Gestures::SlideUp);
} else if (key == ';') { // down
send_gesture(Pinetime::Drivers::Cst816S::Gestures::SlideDown);
} else if (key == '<') { // left
send_gesture(Pinetime::Drivers::Cst816S::Gestures::SlideLeft);
} else if (key == '>') { // up
send_gesture(Pinetime::Drivers::Cst816S::Gestures::SlideRight);
}
batteryController.voltage = batteryController.percentRemaining * 50;
}
void write_uint64(std::span<uint8_t> data, uint64_t val)
{
assert(data.size() >= 8);
for (int i=0; i<8; i++)
{
data[i] = (val >> (i*8)) & 0xff;
}
}
void write_int16(std::span<uint8_t> data, int16_t val)
{
assert(data.size() >= 2);
data[0] = val & 0xff;
data[1] = (val >> 8) & 0xff;
}
void set_current_weather(uint64_t timestamp, int16_t temperature, int iconId)
{
std::array<uint8_t, 49> dataBuffer {};
std::span<uint8_t> data(dataBuffer);
os_mbuf buffer;
ble_gatt_access_ctxt ctxt;
ctxt.om = &buffer;
buffer.om_data = dataBuffer.data();
// fill buffer with specified format
int16_t minTemperature = temperature;
int16_t maxTemperature = temperature;
dataBuffer.at(0) = 0; // MessageType::CurrentWeather
dataBuffer.at(1) = 0; // Vesion 0
write_uint64(data.subspan(2), timestamp);
write_int16(data.subspan(10), temperature);
write_int16(data.subspan(12), minTemperature);
write_int16(data.subspan(14), maxTemperature);
dataBuffer.at(48) = static_cast<uint8_t>(iconId);
// send weather to SimpleWeatherService
systemTask.nimble().weather().OnCommand(&ctxt);
}
void set_forecast(
uint64_t timestamp,
std::array<
std::optional<Pinetime::Controllers::SimpleWeatherService::Forecast::Day>,
Pinetime::Controllers::SimpleWeatherService::MaxNbForecastDays> days)
{
std::array<uint8_t, 36> dataBuffer {};
std::span<uint8_t> data(dataBuffer);
os_mbuf buffer;
ble_gatt_access_ctxt ctxt;
ctxt.om = &buffer;
buffer.om_data = dataBuffer.data();
// fill buffer with specified format
dataBuffer.at(0) = 1; // MessageType::Forecast
dataBuffer.at(1) = 0; // Vesion 0
write_uint64(data.subspan(2), timestamp);
dataBuffer.at(10) = static_cast<uint8_t>(days.size());
for (int i = 0; i < days.size(); i++)
{
const std::optional<Pinetime::Controllers::SimpleWeatherService::Forecast::Day> &day = days.at(i);
if (!day.has_value()) {
continue;
}
write_int16(data.subspan(11+(i*5)), day->minTemperature.PreciseCelsius());
write_int16(data.subspan(13+(i*5)), day->maxTemperature.PreciseCelsius());
dataBuffer.at(15+(i*5)) = static_cast<uint8_t>(day->iconId);
}
// send Forecast to SimpleWeatherService
systemTask.nimble().weather().OnCommand(&ctxt);
}
void generate_weather_data(bool clear) {
if (clear) {
set_current_weather(0, 0, 0);
std::array<std::optional<Pinetime::Controllers::SimpleWeatherService::Forecast::Day>, Pinetime::Controllers::SimpleWeatherService::MaxNbForecastDays> days;
set_forecast(0, days);
return;
}
auto timestamp = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
srand((int)timestamp);
// Generate current weather data
int16_t temperature = (rand() % 81 - 40) * 100;
set_current_weather((uint64_t)timestamp, temperature, rand() % 9);
// Generate forecast data
std::array<std::optional<Pinetime::Controllers::SimpleWeatherService::Forecast::Day>, Pinetime::Controllers::SimpleWeatherService::MaxNbForecastDays> days;
for (int i = 0; i < Pinetime::Controllers::SimpleWeatherService::MaxNbForecastDays; i++) {
days[i] = Pinetime::Controllers::SimpleWeatherService::Forecast::Day {
Pinetime::Controllers::SimpleWeatherService::Temperature(temperature - rand() % 10 * 100),
Pinetime::Controllers::SimpleWeatherService::Temperature(temperature + rand() % 10 * 100),
Pinetime::Controllers::SimpleWeatherService::Icons(rand() % 9),
};
}
set_forecast((uint64_t)timestamp, days);
}
void handle_touch_and_button() {
int x, y;
uint32_t buttons = SDL_GetMouseState(&x, &y);
const bool left_click = (buttons & SDL_BUTTON_LMASK) != 0;
const bool right_click = (buttons & SDL_BUTTON_RMASK) != 0;
if (left_click) {
left_release_sent = false;
systemTask.PushMessage(Pinetime::System::Messages::OnTouchEvent);
return;
} else {
if (!left_release_sent) {
left_release_sent = true;
systemTask.PushMessage(Pinetime::System::Messages::OnTouchEvent);
return;
}
}
if (right_click != right_last_state) {
right_last_state =right_click;
systemTask.PushMessage(Pinetime::System::Messages::HandleButtonEvent);
return;
}
}
// helper function to switch between screens
void switch_to_screen(uint8_t screen_idx)
{
if (screen_idx == 1) {
settingsController.SetWatchFace(Pinetime::Applications::WatchFace::Digital);
displayApp.StartApp(Pinetime::Applications::Apps::Clock, Pinetime::Applications::DisplayApp::FullRefreshDirections::None);
}
else if (screen_idx == 2) {
settingsController.SetWatchFace(Pinetime::Applications::WatchFace::Analog);
displayApp.StartApp(Pinetime::Applications::Apps::Clock, Pinetime::Applications::DisplayApp::FullRefreshDirections::None);
}
else if (screen_idx == 3) {
settingsController.SetWatchFace(Pinetime::Applications::WatchFace::PineTimeStyle);
displayApp.StartApp(Pinetime::Applications::Apps::Clock, Pinetime::Applications::DisplayApp::FullRefreshDirections::None);
}
else if (screen_idx == 4) {
displayApp.StartApp(Pinetime::Applications::Apps::Paddle, Pinetime::Applications::DisplayApp::FullRefreshDirections::None);
}
else if (screen_idx == 5) {
displayApp.StartApp(Pinetime::Applications::Apps::Twos, Pinetime::Applications::DisplayApp::FullRefreshDirections::None);
}
else if (screen_idx == 6) {
displayApp.StartApp(Pinetime::Applications::Apps::Metronome, Pinetime::Applications::DisplayApp::FullRefreshDirections::None);
}
else if (screen_idx == 7) {
displayApp.StartApp(Pinetime::Applications::Apps::FirmwareUpdate, Pinetime::Applications::DisplayApp::FullRefreshDirections::None);
}
else if (screen_idx == 8) {
displayApp.StartApp(Pinetime::Applications::Apps::BatteryInfo, Pinetime::Applications::DisplayApp::FullRefreshDirections::None);
}
else if (screen_idx == 9) {
displayApp.StartApp(Pinetime::Applications::Apps::FlashLight, Pinetime::Applications::DisplayApp::FullRefreshDirections::None);
}
else if (screen_idx == 0) {
displayApp.StartApp(Pinetime::Applications::Apps::QuickSettings, Pinetime::Applications::DisplayApp::FullRefreshDirections::None);
}
else if (screen_idx == 11) {
displayApp.StartApp(Pinetime::Applications::Apps::Music, Pinetime::Applications::DisplayApp::FullRefreshDirections::None);
}
else if (screen_idx == 12) {
displayApp.StartApp(Pinetime::Applications::Apps::Paint, Pinetime::Applications::DisplayApp::FullRefreshDirections::None);
}
else if (screen_idx == 13) {
displayApp.StartApp(Pinetime::Applications::Apps::SysInfo, Pinetime::Applications::DisplayApp::FullRefreshDirections::None);
}
else if (screen_idx == 14) {
displayApp.StartApp(Pinetime::Applications::Apps::Steps, Pinetime::Applications::DisplayApp::FullRefreshDirections::None);
}
else if (screen_idx == 15) {
displayApp.StartApp(Pinetime::Applications::Apps::Error, Pinetime::Applications::DisplayApp::FullRefreshDirections::None);
}
else if (screen_idx == 17) {
displayApp.StartApp(Pinetime::Applications::Apps::PassKey, Pinetime::Applications::DisplayApp::FullRefreshDirections::None);
}
else {
std::cout << "unhandled screen_idx: " << int(screen_idx) << std::endl;
}
}
static void screen_off_delete_cb(lv_obj_t *obj, lv_event_t event)
{
if (event == LV_EVENT_DELETE) {
auto* fw = static_cast<Framework*>(obj->user_data);
if (obj == fw->screen_off_bg)
{
// on delete make sure to not double free the screen_off objects
fw->screen_off_created = false;