-
Notifications
You must be signed in to change notification settings - Fork 223
Expand file tree
/
Copy pathbl.cpp
More file actions
2149 lines (1913 loc) · 70.7 KB
/
Copy pathbl.cpp
File metadata and controls
2149 lines (1913 loc) · 70.7 KB
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
#include <Arduino.h>
#include <bl.h>
#include <types.h>
#include <ArduinoLog.h>
#include <WifiCaptive.h>
#include <pins.h>
#include <config.h>
#include <HTTPClient.h>
#include <WiFiClientSecure.h>
#include <display.h>
#include <stdlib.h>
#include <ESPAsyncWebServer.h>
#include <AsyncTCP.h>
#include <ImageData.h>
#include <Preferences.h>
#include <cstdint>
#include <png.h>
#include <bmp.h>
#include <Update.h>
#include <math.h>
#include <filesystem.h>
#include "trmnl_log.h"
#include <stored_logs.h>
#include <button.h>
#include "api-client/submit_log.h"
#include <special_function.h>
#include <api_response_parsing.h>
#include "logging_parcers.h"
#include <SPIFFS.h>
#include "http_client.h"
#include <api-client/display.h>
#include "driver/gpio.h"
bool pref_clear = false;
String new_filename = "";
uint8_t *buffer = nullptr;
uint8_t *decodedPng = nullptr;
char filename[1024]; // image URL
char binUrl[1024]; // update URL
char log_array[1024]; // log
char message_buffer[128]; // message to show on the screen
uint32_t time_since_sleep;
image_err_e png_res = PNG_DECODE_ERR;
bmp_err_e bmp_res = BMP_NOT_BMP;
bool status = false; // need to download a new image
bool update_firmware = false; // need to download a new firmware
bool reset_firmware = false; // need to reset credentials
bool send_log = false; // need to send logs
bool double_click = false;
bool log_retry = false; // need to log connection retry
esp_sleep_wakeup_cause_t wakeup_reason = ESP_SLEEP_WAKEUP_UNDEFINED; // wake-up reason
MSG current_msg = NONE;
SPECIAL_FUNCTION special_function = SF_NONE;
RTC_DATA_ATTR uint8_t need_to_refresh_display = 1;
Preferences preferences;
static https_request_err_e downloadAndShow(); // download and show the image
static https_request_err_e handleApiDisplayResponse(ApiDisplayResponse &apiResponse);
static void getDeviceCredentials(); // receiveing API key and Friendly ID
static void resetDeviceCredentials(void); // reset device credentials API key, Friendly ID, Wi-Fi SSID and password
static void checkAndPerformFirmwareUpdate(void); // OTA update
static void goToSleep(void); // sleep preparing
static bool setClock(void); // clock synchronization
static float readBatteryVoltage(void); // battery voltage reading
static void log_POST(char *log_buffer, size_t size); // log sending
static void checkLogNotes(void);
static void writeSpecialFunction(SPECIAL_FUNCTION function);
static void writeImageToFile(const char *name, uint8_t *in_buffer, size_t size);
static uint32_t getTime(void);
static void showMessageWithLogo(MSG message_type);
static void showMessageWithLogo(MSG message_type, String friendly_id, bool id, const char *fw_version, String message);
static void showMessageWithLogo(MSG message_type, const ApiSetupResponse &apiResponse);
static void wifiErrorDeepSleep();
static uint8_t *storedLogoOrDefault(void);
static bool saveCurrentFileName(String &name);
static bool checkCurrentFileName(String &newName);
static DeviceStatusStamp getDeviceStatusStamp();
bool SerializeJsonLog(DeviceStatusStamp device_status_stamp, time_t timestamp, int codeline, const char *source_file, char *log_message, uint32_t log_id);
int submitLog(const char *format, time_t time, int line, const char *file, ...);
#define submit_log(format, ...) submitLog(format, getTime(), __LINE__, __FILE__, ##__VA_ARGS__);
void wait_for_serial()
{
#ifdef WAIT_FOR_SERIAL
for (int i = 10; i > 0 && !Serial; i--)
{
Log_info("## Waiting for serial.. %d", i);
delay(1000);
}
#endif
}
/**
* @brief Function to init business logic module
* @param none
* @return none
*/
void bl_init(void)
{
Serial.begin(115200);
Log.begin(LOG_LEVEL_VERBOSE, &Serial);
Log_info("BL init success");
Log_info("Firmware version %d.%d.%d", FW_MAJOR_VERSION, FW_MINOR_VERSION, FW_PATCH_VERSION);
pins_init();
wakeup_reason = esp_sleep_get_wakeup_cause();
Log.info("%s [%d]: preferences start\r\n", __FILE__, __LINE__);
bool res = preferences.begin("data", false);
if (res)
{
Log.info("%s [%d]: preferences init success\r\n", __FILE__, __LINE__);
if (pref_clear)
{
res = preferences.clear(); // if needed to clear the saved data
if (res)
Log.info("%s [%d]: preferences cleared success\r\n", __FILE__, __LINE__);
else
Log_fatal("preferences clearing error");
}
}
else
{
Log.fatal("%s [%d]: preferences init failed\r\n", __FILE__, __LINE__);
ESP.restart();
}
Log.info("%s [%d]: preferences end\r\n", __FILE__, __LINE__);
if (wakeup_reason == ESP_SLEEP_WAKEUP_GPIO)
{
auto button = read_button_presses();
wait_for_serial();
Log_info("GPIO wakeup (%d) -> button was read (%s)", wakeup_reason, ButtonPressResultNames[button]);
switch (button)
{
case LongPress:
Log_info("WiFi reset");
WifiCaptivePortal.resetSettings();
break;
case DoubleClick:
double_click = true;
break;
case NoAction:
break;
}
Log_info("button handling end");
}
else
{
wait_for_serial();
Log_info("Non-GPIO wakeup (%d) -> didn't read buttons", wakeup_reason);
}
if (double_click)
{ // special function reading
if (preferences.isKey(PREFERENCES_SF_KEY))
{
Log.info("%s [%d]: SF saved. Reading...\r\n", __FILE__, __LINE__);
special_function = (SPECIAL_FUNCTION)preferences.getUInt(PREFERENCES_SF_KEY, 0);
Log.info("%s [%d]: Read special function - %d\r\n", __FILE__, __LINE__, special_function);
switch (special_function)
{
case SF_IDENTIFY:
{
Log.info("%s [%d]: Identify special function...It will be handled while API ping...\r\n", __FILE__, __LINE__);
}
break;
case SF_SLEEP:
{
Log.info("%s [%d]: Sleep special function...\r\n", __FILE__, __LINE__);
// still in progress
}
break;
case SF_ADD_WIFI:
{
Log.info("%s [%d]: Add WiFi function...\r\n", __FILE__, __LINE__);
WifiCaptivePortal.startPortal();
}
break;
case SF_RESTART_PLAYLIST:
{
Log.info("%s [%d]: Identify special function...It will be handled while API ping...\r\n", __FILE__, __LINE__);
}
break;
case SF_REWIND:
{
Log.info("%s [%d]: Rewind special function...\r\n", __FILE__, __LINE__);
}
break;
case SF_SEND_TO_ME:
{
Log.info("%s [%d]: Send to me special function...It will be handled while API ping...\r\n", __FILE__, __LINE__);
}
break;
default:
break;
}
}
else
{
Log_error("SF not saved");
}
}
// EPD init
// EPD clear
Log.info("%s [%d]: Display init\r\n", __FILE__, __LINE__);
display_init();
if (wakeup_reason != ESP_SLEEP_WAKEUP_TIMER)
{
Log.info("%s [%d]: Display TRMNL logo start\r\n", __FILE__, __LINE__);
buffer = (uint8_t *)malloc(DEFAULT_IMAGE_SIZE);
display_show_image(storedLogoOrDefault(), false, false);
free(buffer);
buffer = nullptr;
need_to_refresh_display = 1;
preferences.putBool(PREFERENCES_DEVICE_REGISTERED_KEY, false);
Log.info("%s [%d]: Display TRMNL logo end\r\n", __FILE__, __LINE__);
preferences.putString(PREFERENCES_FILENAME_KEY, "");
}
// Mount SPIFFS
filesystem_init();
WiFi.mode(WIFI_STA); // explicitly set mode, esp defaults to STA+AP
if (WifiCaptivePortal.isSaved())
{
// WiFi saved, connection
Log.info("%s [%d]: WiFi saved\r\n", __FILE__, __LINE__);
int connection_res = WifiCaptivePortal.autoConnect();
Log.info("%s [%d]: Connection result: %d, WiFI Status: %d\r\n", __FILE__, __LINE__, connection_res, WiFi.status());
// Check if connected
if (connection_res)
{
String ip = String(WiFi.localIP());
Log.info("%s [%d]:wifi_connection [DEBUG]: Connected: %s\r\n", __FILE__, __LINE__, ip.c_str());
preferences.putInt(PREFERENCES_CONNECT_WIFI_RETRY_COUNT, 1);
}
else
{
Log.fatal("%s [%d]: Connection failed! WL Status: %d\r\n", __FILE__, __LINE__, WiFi.status());
if (current_msg != WIFI_FAILED)
{
showMessageWithLogo(WIFI_FAILED);
current_msg = WIFI_FAILED;
}
submit_log("wifi connection failed, current WL Status: %d", WiFi.status());
// Go to deep sleep
wifiErrorDeepSleep();
}
}
else
{
// WiFi credentials are not saved - start captive portal
Log.info("%s [%d]: WiFi NOT saved\r\n", __FILE__, __LINE__);
char fw_version[20];
sprintf(fw_version, "%d.%d.%d", FW_MAJOR_VERSION, FW_MINOR_VERSION, FW_PATCH_VERSION);
String fw = fw_version;
Log.info("%s [%d]: FW version %s\r\n", __FILE__, __LINE__, fw_version);
showMessageWithLogo(WIFI_CONNECT, "", false, fw.c_str(), "");
WifiCaptivePortal.setResetSettingsCallback(resetDeviceCredentials);
res = WifiCaptivePortal.startPortal();
if (!res)
{
Log.error("%s [%d]: Failed to connect or hit timeout\r\n", __FILE__, __LINE__);
WiFi.disconnect(true);
showMessageWithLogo(WIFI_FAILED);
submit_log("connection to the new WiFi failed");
// Go to deep sleep
wifiErrorDeepSleep();
}
Log.info("%s [%d]: WiFi connected\r\n", __FILE__, __LINE__);
preferences.putInt(PREFERENCES_CONNECT_WIFI_RETRY_COUNT, 1);
}
// clock synchronization
if (setClock())
{
time_since_sleep = preferences.getUInt(PREFERENCES_LAST_SLEEP_TIME, 0);
time_since_sleep = time_since_sleep ? getTime() - time_since_sleep : 0; // may be can be used even if no sync
}
else
{
time_since_sleep = 0;
Log.info("%s [%d]: Time wasn't synced.\r\n", __FILE__, __LINE__);
}
Log.info("%s [%d]: Time since last sleep: %d\r\n", __FILE__, __LINE__, time_since_sleep);
if (!preferences.isKey(PREFERENCES_API_KEY) || !preferences.isKey(PREFERENCES_FRIENDLY_ID))
{
Log.info("%s [%d]: API key or friendly ID not saved\r\n", __FILE__, __LINE__);
// lets get the api key and friendly ID
getDeviceCredentials();
}
else
{
Log.info("%s [%d]: API key and friendly ID saved\r\n", __FILE__, __LINE__);
}
log_retry = true;
// OTA checking, image checking and drawing
https_request_err_e request_result = downloadAndShow();
Log.info("%s [%d]: request result - %d\r\n", __FILE__, __LINE__, request_result);
if (!preferences.isKey(PREFERENCES_CONNECT_API_RETRY_COUNT))
{
preferences.putInt(PREFERENCES_CONNECT_API_RETRY_COUNT, 1);
}
if (request_result != HTTPS_SUCCESS && request_result != HTTPS_NO_ERR && request_result != HTTPS_NO_REGISTER && request_result != HTTPS_RESET && request_result != HTTPS_PLUGIN_NOT_ATTACHED)
{
uint8_t retries = preferences.getInt(PREFERENCES_CONNECT_API_RETRY_COUNT);
switch (retries)
{
case 1:
Log.info("%s [%d]: retry: %d - time to sleep: %d\r\n", __FILE__, __LINE__, retries, API_CONNECT_RETRY_TIME::API_FIRST_RETRY);
res = preferences.putUInt(PREFERENCES_SLEEP_TIME_KEY, API_CONNECT_RETRY_TIME::API_FIRST_RETRY);
preferences.putInt(PREFERENCES_CONNECT_API_RETRY_COUNT, ++retries);
display_sleep();
goToSleep();
break;
case 2:
Log.info("%s [%d]: retry:%d - time to sleep: %d\r\n", __FILE__, __LINE__, retries, API_CONNECT_RETRY_TIME::API_SECOND_RETRY);
res = preferences.putUInt(PREFERENCES_SLEEP_TIME_KEY, API_CONNECT_RETRY_TIME::API_SECOND_RETRY);
preferences.putInt(PREFERENCES_CONNECT_API_RETRY_COUNT, ++retries);
display_sleep();
goToSleep();
break;
case 3:
Log.info("%s [%d]: retry:%d - time to sleep: %d\r\n", __FILE__, __LINE__, retries, API_CONNECT_RETRY_TIME::API_THIRD_RETRY);
res = preferences.putUInt(PREFERENCES_SLEEP_TIME_KEY, API_CONNECT_RETRY_TIME::API_THIRD_RETRY);
preferences.putInt(PREFERENCES_CONNECT_API_RETRY_COUNT, ++retries);
display_sleep();
goToSleep();
break;
default:
Log.info("%s [%d]: Max retries done. Time to sleep: %d\r\n", __FILE__, __LINE__, SLEEP_TIME_TO_SLEEP);
preferences.putUInt(PREFERENCES_SLEEP_TIME_KEY, SLEEP_TIME_TO_SLEEP);
preferences.putInt(PREFERENCES_CONNECT_API_RETRY_COUNT, ++retries);
break;
}
}
else
{
Log.info("%s [%d]: Connection done successfully. Retries counter reset.\r\n", __FILE__, __LINE__);
preferences.putInt(PREFERENCES_CONNECT_API_RETRY_COUNT, 1);
}
if (request_result == HTTPS_NO_REGISTER && need_to_refresh_display == 1)
{
// show the image
String friendly_id = preferences.getString(PREFERENCES_FRIENDLY_ID, PREFERENCES_FRIENDLY_ID_DEFAULT);
showMessageWithLogo(FRIENDLY_ID, friendly_id, true, "", String(message_buffer));
need_to_refresh_display = 0;
}
// reset checking
if (request_result == HTTPS_RESET)
{
Log.info("%s [%d]: Device reseting...\r\n", __FILE__, __LINE__);
resetDeviceCredentials();
}
// OTA update checking
if (update_firmware)
{
checkAndPerformFirmwareUpdate();
}
// error handling
switch (request_result)
{
case HTTPS_REQUEST_FAILED:
{
if (WiFi.RSSI() > WIFI_CONNECTION_RSSI)
{
showMessageWithLogo(API_ERROR);
}
else
{
showMessageWithLogo(WIFI_WEAK);
}
}
break;
case HTTPS_RESPONSE_CODE_INVALID:
{
showMessageWithLogo(WIFI_INTERNAL_ERROR);
}
break;
case HTTPS_UNABLE_TO_CONNECT:
{
if (WiFi.RSSI() > WIFI_CONNECTION_RSSI)
{
showMessageWithLogo(API_ERROR);
}
else
{
showMessageWithLogo(WIFI_WEAK);
}
}
break;
case HTTPS_WRONG_IMAGE_FORMAT:
{
showMessageWithLogo(BMP_FORMAT_ERROR);
}
break;
case HTTPS_WRONG_IMAGE_SIZE:
{
if (WiFi.RSSI() > WIFI_CONNECTION_RSSI)
{
showMessageWithLogo(API_SIZE_ERROR);
}
else
{
showMessageWithLogo(WIFI_WEAK);
}
}
break;
case HTTPS_CLIENT_FAILED:
{
showMessageWithLogo(WIFI_INTERNAL_ERROR);
}
break;
case HTTPS_PLUGIN_NOT_ATTACHED:
{
if (preferences.getInt(PREFERENCES_SLEEP_TIME_KEY, 0) != SLEEP_TIME_WHILE_PLUGIN_NOT_ATTACHED)
{
Log.info("%s [%d]: write new refresh rate: %d\r\n", __FILE__, __LINE__, SLEEP_TIME_WHILE_PLUGIN_NOT_ATTACHED);
size_t result = preferences.putUInt(PREFERENCES_SLEEP_TIME_KEY, SLEEP_TIME_WHILE_PLUGIN_NOT_ATTACHED);
Log.info("%s [%d]: written new refresh rate: %d\r\n", __FILE__, __LINE__, SLEEP_TIME_WHILE_PLUGIN_NOT_ATTACHED);
}
}
break;
default:
break;
}
if (request_result != HTTPS_NO_ERR && request_result != HTTPS_PLUGIN_NOT_ATTACHED)
{
checkLogNotes();
}
// display go to sleep
display_sleep();
if (!update_firmware)
goToSleep();
else
ESP.restart();
}
/**
* @brief Function to process business logic module
* @param none
* @return none
*/
void bl_process(void)
{
}
ApiDisplayInputs loadApiDisplayInputs(Preferences &preferences)
{
ApiDisplayInputs inputs;
inputs.baseUrl = preferences.getString(PREFERENCES_API_URL, API_BASE_URL);
if (preferences.isKey(PREFERENCES_API_KEY))
{
inputs.apiKey = preferences.getString(PREFERENCES_API_KEY, PREFERENCES_API_KEY_DEFAULT);
Log.info("%s [%d]: %s key exists. Value - %s\r\n", __FILE__, __LINE__, PREFERENCES_API_KEY, inputs.apiKey.c_str());
}
else
{
Log.error("%s [%d]: %s key not exists.\r\n", __FILE__, __LINE__, PREFERENCES_API_KEY);
}
if (preferences.isKey(PREFERENCES_FRIENDLY_ID))
{
inputs.friendlyId = preferences.getString(PREFERENCES_FRIENDLY_ID, PREFERENCES_FRIENDLY_ID_DEFAULT);
Log.info("%s [%d]: %s key exists. Value - %s\r\n", __FILE__, __LINE__, PREFERENCES_FRIENDLY_ID, inputs.friendlyId);
}
else
{
Log.error("%s [%d]: %s key not exists.\r\n", __FILE__, __LINE__, PREFERENCES_FRIENDLY_ID);
}
inputs.refreshRate = SLEEP_TIME_TO_SLEEP;
if (preferences.isKey(PREFERENCES_SLEEP_TIME_KEY))
{
inputs.refreshRate = preferences.getUInt(PREFERENCES_SLEEP_TIME_KEY, SLEEP_TIME_TO_SLEEP);
Log.info("%s [%d]: %s key exists. Value - %d\r\n", __FILE__, __LINE__, PREFERENCES_SLEEP_TIME_KEY, inputs.refreshRate);
}
else
{
Log.error("%s [%d]: %s key not exists.\r\n", __FILE__, __LINE__, PREFERENCES_SLEEP_TIME_KEY);
}
inputs.macAddress = WiFi.macAddress();
inputs.batteryVoltage = readBatteryVoltage();
inputs.firmwareVersion = String(FW_MAJOR_VERSION) + "." +
String(FW_MINOR_VERSION) + "." +
String(FW_PATCH_VERSION);
inputs.rssi = WiFi.RSSI();
inputs.displayWidth = display_width();
inputs.displayHeight = display_height();
inputs.specialFunction = special_function;
return inputs;
}
/**
* @brief Function to ping server and download and show the image if all is OK
* @param url Server URL address
* @return https_request_err_e error code
*/
static https_request_err_e downloadAndShow()
{
IPAddress serverIP;
String apiHostname = preferences.getString(PREFERENCES_API_URL, API_BASE_URL);
apiHostname.replace("https://", "");
apiHostname.replace("http://", "");
apiHostname.replace("/", "");
for (int attempt = 1; attempt <= 5; ++attempt)
{
if (WiFi.hostByName(apiHostname.c_str(), serverIP) == 1)
{
Log.info("%s [%d]: Hostname resolved to %s on attempt %d\r\n", __FILE__, __LINE__, serverIP.toString().c_str(), attempt);
break;
}
else
{
Log.error("%s [%d]: Failed to resolve hostname on attempt %d\r\n", __FILE__, __LINE__, attempt);
if (attempt == 5)
{
submit_log("Failed to resolve hostname after 5 attempts, continuing...");
}
delay(2000);
}
}
auto apiDisplayInputs = loadApiDisplayInputs(preferences);
auto apiDisplayResult = fetchApiDisplay(apiDisplayInputs);
if (apiDisplayResult.error != HTTPS_NO_ERR)
{
Log.error("%s [%d]: Error fetching API display: %d, detail: %s\r\n", __FILE__, __LINE__, apiDisplayResult.error, apiDisplayResult.error_detail.c_str());
submit_log("Error fetching API display: %d, detail: %s", apiDisplayResult.error, apiDisplayResult.error_detail.c_str());
return apiDisplayResult.error;
}
handleApiDisplayResponse(apiDisplayResult.response);
https_request_err_e result = HTTPS_NO_ERR;
WiFiClientSecure *secureClient = new WiFiClientSecure;
secureClient->setInsecure();
WiFiClient *insecureClient = new WiFiClient;
bool isHttps = true;
if (apiDisplayInputs.baseUrl.indexOf("https://") == -1)
{
isHttps = false;
}
// define client depending on the isHttps variable
WiFiClient *client = isHttps ? secureClient : insecureClient;
if (!client)
{
Log.error("%s [%d]: Unable to create client\r\n", __FILE__, __LINE__);
return HTTPS_UNABLE_TO_CONNECT;
}
{ // Add a scoping block for HTTPClient https to make sure it is destroyed before WiFiClientSecure *client is
HTTPClient https;
if (status && !update_firmware && !reset_firmware)
{
status = false;
// The timeout will be zero if no value was returned, and in that case we just use the default timeout.
// Otherwise, we set the requested timeout.
uint32_t requestedTimeout = apiDisplayResult.response.image_url_timeout;
if (requestedTimeout > 0)
{
// Convert from seconds to milliseconds.
// A uint32_t should be large enough not to worry about overflow for any reasonable timeout.
requestedTimeout *= MS_TO_S_FACTOR;
if (requestedTimeout > UINT16_MAX)
{
// To avoid surprising behaviour if the server returned a timeout of more than 65 seconds
// we will send a log message back to the server and truncate the timeout to the maximum.
submit_log("Requested image URL timeout too large (%d ms). Using maximum of %d ms.", requestedTimeout, UINT16_MAX);
https.setTimeout(UINT16_MAX);
}
else
{
https.setTimeout(uint16_t(requestedTimeout));
}
}
Log.info("%s [%d]: [HTTPS] Request to %s\r\n", __FILE__, __LINE__, filename);
client = strstr(filename, "https://") == nullptr ? insecureClient : secureClient;
if (!https.begin(*client, filename)) // HTTPS
{
Log.error("%s [%d]: unable to connect\r\n", __FILE__, __LINE__);
submit_log("unable to connect to the API");
return HTTPS_UNABLE_TO_CONNECT;
}
const char *headers[] = {"Content-Type"};
https.collectHeaders(headers, 1);
Log.info("%s [%d]: [HTTPS] GET..\r\n", __FILE__, __LINE__);
Log.info("%s [%d]: RSSI: %d\r\n", __FILE__, __LINE__, WiFi.RSSI());
// start connection and send HTTP header
int httpCode = https.GET();
int content_size = https.getSize();
// httpCode will be negative on error
if (httpCode < 0)
{
Log.error("%s [%d]: [HTTPS] GET... failed, error: %d (%s)\r\n", __FILE__, __LINE__, httpCode, https.errorToString(httpCode).c_str());
submit_log("HTTP Client failed with error: %s", https.errorToString(httpCode).c_str());
return HTTPS_REQUEST_FAILED;
}
// HTTP header has been send and Server response header has been handled
Log.error("%s [%d]: [HTTPS] GET... code: %d\r\n", __FILE__, __LINE__, httpCode);
Log.info("%s [%d]: RSSI: %d\r\n", __FILE__, __LINE__, WiFi.RSSI());
// file found at server
if (httpCode != HTTP_CODE_OK && httpCode != HTTP_CODE_MOVED_PERMANENTLY)
{
Log.error("%s [%d]: [HTTPS] GET... failed, code: %d (%s)\r\n", __FILE__, __LINE__, httpCode, https.errorToString(httpCode).c_str());
submit_log("HTTPS returned code is not OK. Code: %d", httpCode);
return HTTPS_REQUEST_FAILED;
}
Log.info("%s [%d]: Content size: %d\r\n", __FILE__, __LINE__, https.getSize());
uint32_t counter = 0;
if (content_size > DISPLAY_BMP_IMAGE_SIZE)
{
Log.error("%s [%d]: Receiving failed. Bad file size\r\n", __FILE__, __LINE__);
submit_log("HTTPS request error. Returned code - %d, available bytes - %d, received bytes - %d", httpCode, https.getSize(), counter);
return HTTPS_REQUEST_FAILED;
}
WiFiClient *stream = https.getStreamPtr();
Log.info("%s [%d]: RSSI: %d\r\n", __FILE__, __LINE__, WiFi.RSSI());
Log.info("%s [%d]: Stream timeout: %d\r\n", __FILE__, __LINE__, stream->getTimeout());
Log.info("%s [%d]: Stream available: %d\r\n", __FILE__, __LINE__, stream->available());
uint32_t timer = millis();
while (stream->available() < 4000 && millis() - timer < 1000)
;
Log.info("%s [%d]: Stream available: %d\r\n", __FILE__, __LINE__, stream->available());
bool isPNG = https.header("Content-Type") == "image/png";
int iteration_counter = 0;
unsigned long download_start = millis();
Log.info("%s [%d]: Starting a download at: %d\r\n", __FILE__, __LINE__, getTime());
heap_caps_check_integrity_all(true);
buffer = (uint8_t *)malloc(content_size);
int counter2 = content_size;
while (counter != content_size && millis() - download_start < 10000)
{
if (stream->available())
{
Log.info("%s [%d]: Downloading... Available bytes: %d\r\n", __FILE__, __LINE__, stream->available());
counter += stream->readBytes(buffer + counter, counter2 -= counter);
if (counter >= 2)
{
if (buffer[0] == 'B' && buffer[1] == 'M')
{
isPNG = false;
Log.info("BMP file detected");
}
}
iteration_counter++;
}
delay(10);
}
Log.info("%s [%d]: Ending a download at: %d, in %d iterations\r\n", __FILE__, __LINE__, getTime(), iteration_counter);
if (counter != content_size)
{
Log.error("%s [%d]: Receiving failed. Read: %d\r\n", __FILE__, __LINE__, counter);
// display_show_msg(const_cast<uint8_t *>(default_icon), API_SIZE_ERROR);
submit_log("HTTPS request error. Returned code - %d, available bytes - %d, received bytes - %d in %d iterations", httpCode, https.getSize(), counter, iteration_counter);
return HTTPS_WRONG_IMAGE_SIZE;
}
Log.info("%s [%d]: Received successfully\r\n", __FILE__, __LINE__);
bool bmp_rename = false;
if (filesystem_file_exists("/current.bmp") || filesystem_file_exists("/current.png"))
{
filesystem_file_delete("/last.bmp");
filesystem_file_delete("/last.png");
filesystem_file_rename("/current.png", "/last.png");
filesystem_file_rename("/current.bmp", "/last.bmp");
}
bool image_reverse = false;
if (isPNG)
{
writeImageToFile("/current.png", buffer, content_size);
delay(100);
free(buffer);
buffer = nullptr;
Log.info("%s [%d]: Decoding png\r\n", __FILE__, __LINE__);
png_res = decodePNG("/current.png", decodedPng);
}
else
{
bmp_res = parseBMPHeader(buffer, image_reverse);
Log.info("%s [%d]: BMP Parsing result: %d\r\n", __FILE__, __LINE__, bmp_res);
}
Serial.println();
String error = "";
uint8_t *imagePointer = (decodedPng == nullptr) ? buffer : decodedPng;
bool lastImageExists = filesystem_file_exists("/last.bmp") || filesystem_file_exists("/last.png");
switch (png_res)
{
case PNG_NO_ERR:
{
Log.info("Free heap at before display - %d", ESP.getMaxAllocHeap());
display_show_image(imagePointer, image_reverse, isPNG);
// Using filename from API response
new_filename = apiDisplayResult.response.filename;
// Print the extracted string
Log.info("%s [%d]: New filename - %s\r\n", __FILE__, __LINE__, new_filename.c_str());
bool res = saveCurrentFileName(new_filename);
if (res)
Log.info("%s [%d]: New filename saved\r\n", __FILE__, __LINE__);
else
Log.error("%s [%d]: New image name saving error!", __FILE__, __LINE__);
if (result != HTTPS_PLUGIN_NOT_ATTACHED)
result = HTTPS_SUCCESS;
}
break;
case PNG_WRONG_FORMAT:
{
error = "Wrong image format. Did not pass signature check";
}
break;
case PNG_BAD_SIZE:
{
error = "IMAGE width, height or size are invalid";
}
break;
case PNG_DECODE_ERR:
{
error = "could not decode png image";
}
break;
case PNG_MALLOC_FAILED:
{
error = "could not allocate memory for png image decoder";
}
break;
default:
break;
}
switch (bmp_res)
{
case BMP_NO_ERR:
{
if (!filesystem_file_exists("/current.png"))
{
writeImageToFile("/current.bmp", buffer, content_size);
}
Log.info("Free heap at before display - %d", ESP.getMaxAllocHeap());
display_show_image(imagePointer, image_reverse, isPNG);
// Using filename from API response
new_filename = apiDisplayResult.response.filename;
// Print the extracted string
Log.info("%s [%d]: New filename - %s\r\n", __FILE__, __LINE__, new_filename.c_str());
bool res = saveCurrentFileName(new_filename);
if (res)
Log.info("%s [%d]: New filename saved\r\n", __FILE__, __LINE__);
else
Log.error("%s [%d]: New image name saving error!", __FILE__, __LINE__);
if (result != HTTPS_PLUGIN_NOT_ATTACHED)
result = HTTPS_SUCCESS;
}
break;
case BMP_FORMAT_ERROR:
{
error = "First two header bytes are invalid!";
}
break;
case BMP_BAD_SIZE:
{
error = "BMP width, height or size are invalid";
}
break;
case BMP_COLOR_SCHEME_FAILED:
{
error = "BMP color scheme is invalid";
}
break;
case BMP_INVALID_OFFSET:
{
error = "BMP header offset is invalid";
}
break;
default:
break;
}
if (isPNG && png_res != PNG_NO_ERR)
{
filesystem_file_delete("/current.png");
submit_log("error parsing image file - %s", error.c_str());
return HTTPS_WRONG_IMAGE_FORMAT;
}
}
}
if (send_log)
{
send_log = false;
}
Log.info("%s [%d]: Returned result - %d\r\n", __FILE__, __LINE__, result);
return result;
}
https_request_err_e handleApiDisplayResponse(ApiDisplayResponse &apiResponse)
{
https_request_err_e result = HTTPS_NO_ERR;
if (special_function == SF_NONE)
{
uint64_t request_status = apiResponse.status;
Log.info("%s [%d]: status: %d\r\n", __FILE__, __LINE__, request_status);
switch (request_status)
{
case 0:
{
String image_url = apiResponse.image_url;
update_firmware = apiResponse.update_firmware;
String firmware_url = apiResponse.firmware_url;
uint64_t rate = apiResponse.refresh_rate;
reset_firmware = apiResponse.reset_firmware;
bool sleep_5_seconds = false;
writeSpecialFunction(apiResponse.special_function);
if (update_firmware)
{
Log.info("%s [%d]: update firmware. Check URL\r\n", __FILE__, __LINE__);
if (firmware_url.length() == 0)
{
Log.error("%s [%d]: Empty URL\r\n", __FILE__, __LINE__);
update_firmware = false;
}
}
if (image_url.length() > 0)
{
Log.info("%s [%d]: image_url: %s\r\n", __FILE__, __LINE__, image_url.c_str());
Log.info("%s [%d]: image url end with: %d\r\n", __FILE__, __LINE__, image_url.endsWith("/setup-logo.bmp"));
image_url.toCharArray(filename, image_url.length() + 1);
// check if plugin is applied
bool flag = preferences.getBool(PREFERENCES_DEVICE_REGISTERED_KEY, false);
Log.info("%s [%d]: flag: %d\r\n", __FILE__, __LINE__, flag);
if (apiResponse.filename == "empty_state")
{
Log.info("%s [%d]: End with empty_state\r\n", __FILE__, __LINE__);
if (!flag)
{
// draw received logo
status = true;
// set flag to true
if (preferences.getBool(PREFERENCES_DEVICE_REGISTERED_KEY, false) != true) // check the flag to avoid the re-writing
{
bool res = preferences.putBool(PREFERENCES_DEVICE_REGISTERED_KEY, true);
if (res)
Log.info("%s [%d]: Flag written true successfully\r\n", __FILE__, __LINE__);
else
Log.error("%s [%d]: FLag writing failed\r\n", __FILE__, __LINE__);
}
}
else
{
// don't draw received logo
status = false;
}
// sleep 5 seconds
sleep_5_seconds = true;
}
else
{
Log.info("%s [%d]: End with NO empty_state\r\n", __FILE__, __LINE__);
if (flag)
{
if (preferences.getBool(PREFERENCES_DEVICE_REGISTERED_KEY, false) != false) // check the flag to avoid the re-writing
{
bool res = preferences.putBool(PREFERENCES_DEVICE_REGISTERED_KEY, false);
if (res)
Log.info("%s [%d]: Flag written false successfully\r\n", __FILE__, __LINE__);
else
Log.error("%s [%d]: FLag writing failed\r\n", __FILE__, __LINE__);
}
}
// Using filename from API response
new_filename = apiResponse.filename;
// Print the extracted string
Log.info("%s [%d]: New filename - %s\r\n", __FILE__, __LINE__, new_filename.c_str());
if (!checkCurrentFileName(new_filename))
{
Log.info("%s [%d]: New image. Show it.\r\n", __FILE__, __LINE__);
status = true;
}
else
{
Log.info("%s [%d]: Old image. No needed to show it.\r\n", __FILE__, __LINE__);
status = false;
result = HTTPS_SUCCESS;
}
}
}
Log.info("%s [%d]: update_firmware: %d\r\n", __FILE__, __LINE__, update_firmware);
if (firmware_url.length() > 0)
{
Log.info("%s [%d]: firmware_url: %s\r\n", __FILE__, __LINE__, firmware_url.c_str());
firmware_url.toCharArray(binUrl, firmware_url.length() + 1);
}
Log.info("%s [%d]: refresh_rate: %d\r\n", __FILE__, __LINE__, rate);
if (rate != preferences.getUInt(PREFERENCES_SLEEP_TIME_KEY, SLEEP_TIME_TO_SLEEP))
{
Log.info("%s [%d]: write new refresh rate: %d\r\n", __FILE__, __LINE__, rate);
size_t result = preferences.putUInt(PREFERENCES_SLEEP_TIME_KEY, rate);
Log.info("%s [%d]: written new refresh rate: %d\r\n", __FILE__, __LINE__, result);
}
if (reset_firmware)
{
Log.info("%s [%d]: Reset status is true\r\n", __FILE__, __LINE__);