-
Notifications
You must be signed in to change notification settings - Fork 228
/
main.cpp
4586 lines (4347 loc) · 242 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
//***************************************************************************************************
//* ESP32_Radio V2 -- Webradio receiver for ESP32, VS1053 MP3 module and optional display. *
//* By Ed Smallenburg. *
//***************************************************************************************************
// ESP32 libraries used: See platformio.ini
// A library for the VS1053 (for ESP32) is not available (or not easy to find). Therefore
// a class for this module is derived from the maniacbug library and integrated in this sketch.
// The Helix codecs for MP3 and AAC are taken from Wolle (schreibfaul1), see:
// https://github.com/schreibfaul1/ESP32-audioI2S
//
// See http://www.internet-radio.com for suitable stations. Add the stations of your choice
// to the preferences through the webinterface.
// You may also use the "search" page of the webinterface to find stations.
//
// Brief description of the program:
// First a suitable WiFi network is found and a connection is made.
// Then a connection will be made to a shoutcast server. The server starts with some
// info in the header in readable ascii, ending with a double CRLF, like:
// icy-name:Classic Rock Florida - SHE Radio
// icy-genre:Classic Rock 60s 70s 80s Oldies Miami South Florida
// icy-url:http://www.ClassicRockFLorida.com
// content-type:audio/mpeg
// icy-pub:1
// icy-metaint:32768 - Metadata after 32768 bytes of MP3-data
// icy-br:128 - in kb/sec (for Ogg this is like "icy-br=Quality 2"
//
// After de double CRLF is received, the server starts sending mp3- or Ogg-data. For mp3, this
// data may contain metadata (non mp3) after every "metaint" mp3 bytes.
// The metadata is empty in most cases, but if any is available the content will be
// presented on the TFT.
// Pushing an input button causes the player to execute a programmable command.
//
// The display used is a Chinese 1.8 color TFT module 128 x 160 pixels.
// Now there is room for 26 characters per line and 16 lines.
// Software will work without installing the display.
// Other displays are also supported. See documentation.
// For configuration of the WiFi network(s): see the global data section further on.
//
// The VSPI interface is used for VS1053, TFT and SD.
//
// Wiring. Note that this is just an example. Pins (except 18, 19 and 23 of the SPI interface)
// can be configured in the config page of the web interface.
//
// ESP32dev Signal Wired to LCD Wired to VS1053 AI Audio board Wired to the rest
// -------- ------ -------------- ------------------- --------------- ------------------------
// GPIO32 - pin 1 XDCS I2C Clock
// GPIO33 - - I2C Data
// GPIO5 - pin 2 XCS KEY 6 -
// GPIO4 - pin 4 DREQ AMPLIFIER_ENABLE -
// GPIO2 pin 3 D/C or A0 - SPI_MISO -
// GPIO16 RXD2 - - TX of NEXTION (if in use)
// GPIO17 TXD2 - - RX of NEXTION (if in use)
// GPIO18 SCK pin 5 CLK or SCK pin 5 SCK KEY 5 -
// GPIO19 MISO - pin 7 MISO KEY 3 -
// GPIO23 MOSI pin 4 DIN or SDA pin 6 MOSI KEY 4 -
// GPIO15 pin 2 CS - SPI_MOSI -
// GPIO3 RXD0 - - Reserved serial input
// GPIO1 TXD0 - - Reserved serial output
// GPIO34 - - - SD detect Optional pull-up resistor
// GPIO35 - - - Infrared receiver VS1838B
// GPIO25 - - - I2S DSIN Rotary encoder CLK
// GPIO26 - - - I2S LRC Rotary encoder DT
// GPIO27 - - - I2S BCLK Rotary encoder SW
// GPIO13 - - - SD card CS -
// GPIO14 - - - SPI_SCK -
// GPIO36 - - - KEY 1 -
// GPIO13 - - - KEY 2 -
// GPIO19 - - - KEY 3 -
// GPIO23 - - - KEY 4 -
// GPIO18 - - - KEY 5 -
// GPIO05 - - - KEY 6 -
// ------- ------ --------------- ------------------- ----------------
// GND - pin 8 GND pin 8 GND Power supply GND
// VCC 5 V - pin 7 BL - Power supply
// VCC 5 V - pin 6 VCC pin 9 5V Power supply
// EN - pin 1 RST pin 3 XRST -
//
// History:
// Date Author Remarks
// ---------- -- ------------------------------------------------------------------
// 06-08-2021, ES: Copy from version 1.
// 06-08-2021, ES: Use SPIFFS and Async webserver.
// 23-08-2021, ES: Version with software MP3/AAC decoders.
// 05-10-2021, ES: Fixed internal DAC output, fixed OTA update.
// 06-10-2021, ES: Fixed AP mode.
// 10-02-2022, ES: Included ST7789 display.
// 11-02-2022, ES: SD card implementation.
// 26-03-2022, ES: Fixed NEXTION bug.
// 12-04-2022, ES: Fixed dataqueue bug (NEXT function).
// 13-04-2022, ES: Fixed redirect bug (preset was reset), fixed playlist.
// 14-04-2022, ES: Added posibility for a fixed WiFi network.
// 15-04-2022, ES: Redesigned station selection.
// 25-04-2022, ES: Support for WT32-ETH01 (wired Ethernet).
// 13-05-2022, ES: Correction I2S settings.
// 15-05-2022, ES: Correction mp3 list for web interface.
// 17-11-2022, ES: Support of AI Audio kit V2.1.
// 22-11-2022, ES: Fixed memory leak.
// 28-04-2023, ES: Correct "Request station:port failed!"
// 10-05-2023, ES: SD card files stored on the SDcard.
// 19-05-2023, ES: Mute and unmute with 2 buttons or commands.
// 22-05-2023, ES: Use internal mutex for SPI bus.
// 16-06-2023, ES: Add sleep commmeand.
// 09-10-2023, ES: Reduce GPIO errors by checking GPIO pins.
// 14-12-2023, ES: Add mqtt trigger to refresh all items.
// 16-01-2024, ES: Disable brownout.
// 16-02-2024, ES: SPDIFF output (experimental).
// 19-02-2024, ES: Fixed mono stream, correct handling of reset command.
//
// Define the version number, the format used is the HTTP standard.
#define VERSION "Wed, 06 Mar 2024 16:00:00 GMT"
//
#include <Arduino.h> // Standard include for Platformio Arduino projects
#include "soc/soc.h" // For brown-out detector setting
#include "soc/rtc_cntl_reg.h" // For brown-out detector settingtest
//#include <esp_log.h>
#include <WiFi.h>
#include "config.h" // Specify display type, decoder type
#include <nvs.h> // Access to NVS
#include <PubSubClient.h> // MTTQ access
#ifdef ETHERNET
#include <ETH.h> // Definitions for Ethernet controller
//#include <AsyncWebServer_WT32_ETH01.h>
#define ETH_CLK_MODE ETH_CLOCK_GPIO0_IN // External clock from crystal oscillator
#define ETH_TYPE ETH_PHY_LAN8720 // Type of controller
#define ETH_ADDR 1 // I2C address of Ethernet PHY
#else
#include <WiFiMulti.h> // Handle multiple WiFi networks
WiFiMulti wifiMulti ; // Object for WiFiMulti
#endif
#include <ESPAsyncWebServer.h> // For Async Web server
#include <ESPmDNS.h> // For multicast DNS
#include <time.h> // Time functions
#include <SPI.h> // For SPI handling
#ifdef ENABLEOTA
#include <ArduinoOTA.h> // Over the air updates
#endif
#include <freertos/queue.h> // FreeRtos queue support
#include <freertos/task.h> // FreeRtos task handling
#include <esp_task_wdt.h>
#include <driver/adc.h>
#include <base64.h> // For Basic authentication
#include <SPIFFS.h> // Filesystem
#include "utils.h" // Some handy utilities
#if defined(DEC_HELIX_SPDIF) || defined(DEC_HELIX_INT) || defined(DEC_HELIX_AI)
#define DEC_HELIX
#endif
#if defined(DEC_HELIX_AI) // AI Audio kit board?
#include <AC101.h>
#define GPIO_PA_EN 21 // GPIO for enabling amplifier
AC101 dac ; // AC101 controls
#endif
#if defined(DEC_HELIX)
#include <driver/i2s.h> // Driver for I2S output
#include "mp3_decoder.h" // Yes, include libhelix_HMP3DECODER
#include "aac_decoder.h" // and libhelix_HAACDECODER
#include "helixfuncs.h" // Helix functions
#else
#include "VS1053.h" // Driver for VS1053
#endif
#define MAXKEYS 200 // Max. number of NVS keys in table
#define FSIF true // Format SPIFFS if not existing
#define QSIZ 400 // Number of entries in the MP3 stream queue
#define NVSBUFSIZE 150 // Max size of a string in NVS
// Access point name if connection to WiFi network fails. Also the hostname for WiFi and OTA.
// Note that the password of an AP must be at least as long as 8 characters.
// Also used for other naming.
#ifndef NAME // Name may be defined in config.h
#define NAME "ESP32-Radio"
#endif
#define MAXPRESETS 200 // Max number of presets in preferences
#define MAXMQTTCONNECTS 5 // Maximum number of MQTT reconnects before give-up
#define METASIZ 1024 // Size of metaline buffer
#define BL_TIME 45 // Time-out [sec] for blanking TFT display (BL pin)
//
// Subscription topics for MQTT. The topic will be pefixed by "PREFIX/", where PREFIX is replaced
// by the the mqttprefix in the preferences. The next definition will yield the topic
// "ESP32Radio/command" if mqttprefix is "ESP32Radio".
#define MQTT_SUBTOPIC "command" // Command to receive from MQTT
//
#define heapspace heap_caps_get_largest_free_block ( MALLOC_CAP_8BIT )
//**************************************************************************************************
// Forward declaration and prototypes of various functions. *
//**************************************************************************************************
void tftlog ( const char *str, bool newline = false ) ;
bool showstreamtitle ( const char* ml, bool full = false ) ;
void handlebyte_ch ( uint8_t b ) ;
void handleCmd() ;
const char* analyzeCmd ( const char* str ) ;
const char* analyzeCmd ( const char* par, const char* val ) ;
void chomp ( String &str ) ;
String nvsgetstr ( const char* key ) ;
bool nvssearch ( const char* key ) ;
void sdfuncs() ;
void stop_mp3client () ;
void tftset ( uint16_t inx, const char *str ) ;
void tftset ( uint16_t inx, String& str ) ;
void playtask ( void* parameter ) ; // Task to play the stream on VS1053 or HELIX decoder
void displayinfo ( uint16_t inx ) ;
void gettime() ;
void reservepin ( int8_t rpinnr ) ;
uint32_t ssconv ( const uint8_t* bytes ) ;
void scan_content_length ( const char* metalinebf ) ;
void handle_notfound ( AsyncWebServerRequest *request ) ;
void handle_getprefs ( AsyncWebServerRequest *request ) ;
void handle_saveprefs ( AsyncWebServerRequest *request ) ;
void handle_getdefs ( AsyncWebServerRequest *request ) ;
void handle_settings ( AsyncWebServerRequest *request ) ;
void handle_mp3list ( AsyncWebServerRequest *request ) ;
void handle_reset ( AsyncWebServerRequest *request ) ;
bool readhostfrompref ( int16_t preset, String* host, String* hsym = NULL ) ;
//**************************************************************************************************
// Several structs and enums. *
//**************************************************************************************************
//
enum qdata_type { QDATA, QSTARTSONG, QSTOPSONG, // datatyp in qdata_struct,
QSTOPTASK } ;
struct qdata_struct // Data in queue for playtask (dataqueue)
{
qdata_type datatyp ; // Identifier
__attribute__((aligned(4))) uint8_t buf[32] ; // Buffer for chunk of mp3 data
} ;
struct ini_struct
{
String mqttbroker ; // The name of the MQTT broker server
String mqttprefix ; // Prefix to use for topics
uint16_t mqttport ; // Port, default 1883
String mqttuser ; // User for MQTT authentication
String mqttpasswd ; // Password for MQTT authentication
uint8_t reqvol ; // Requested volume
uint8_t rtone[4] ; // Requested bass/treble settings
String clk_server ; // Server to be used for time of day clock
int8_t clk_offset ; // Offset in hours with respect to UTC
int8_t clk_dst ; // Number of hours shift during DST
int8_t ir_pin ; // GPIO connected to output of IR decoder
int8_t enc_clk_pin ; // GPIO connected to CLK of rotary encoder
int8_t enc_dt_pin ; // GPIO connected to DT of rotary encoder
int8_t enc_sw_pin ; // GPIO connected to SW of rotary encoder / ZIPPY B5
int8_t enc_up_pin ; // GPIO connected to UP of ZIPPY B5 side switch
int8_t enc_dwn_pin ; // GPIO connected to DOWN of ZIPPY B5 side switch
int8_t tft_cs_pin ; // GPIO connected to CS of TFT screen
int8_t tft_dc_pin ; // GPIO connected to D/C or A0 of TFT screen
int8_t tft_scl_pin ; // GPIO connected to SCL of i2c TFT screen
int8_t tft_sda_pin ; // GPIO connected to SDA of I2C TFT screen
int8_t tft_bl_pin ; // GPIO to activate BL of display
int8_t tft_blx_pin ; // GPIO to activate BL of display (inversed logic)
int8_t nxt_rx_pin ; // GPIO for input from NEXTION
int8_t nxt_tx_pin ; // GPIO for output to NEXTION
int8_t sd_cs_pin ; // GPIO connected to CS of SD card
int8_t sd_detect_pin ; // GPIO connected to SC card detect (LOW is inserted)
int8_t vs_cs_pin ; // GPIO connected to CS of VS1053
int8_t vs_dcs_pin ; // GPIO connected to DCS of VS1053
int8_t vs_dreq_pin ; // GPIO connected to DREQ of VS1053
int8_t shutdown_pin ; // GPIO to shut down the amplifier
int8_t shutdownx_pin ; // GPIO to shut down the amplifier (inversed logic)
int8_t spi_sck_pin ; // GPIO connected to SPI SCK pin
int8_t spi_miso_pin ; // GPIO connected to SPI MISO pin
int8_t spi_mosi_pin ; // GPIO connected to SPI MOSI pin
int8_t i2s_bck_pin ; // GPIO Pin number for I2S "BCK"
int8_t i2s_lck_pin ; // GPIO Pin number for I2S "L(R)CK"
int8_t i2s_din_pin ; // GPIO Pin number for I2S "DIN"
int8_t i2s_spdif_pin ; // GPIO Pin number for SPDIF output
int8_t eth_mdc_pin ; // GPIO Pin number for Ethernet controller MDC
int8_t eth_mdio_pin ; // GPIO Pin number for Ethernet controller MDIO
int8_t eth_power_pin ; // GPIO Pin number for Ethernet controller POWER
uint16_t bat0 ; // ADC value for 0 percent battery charge
uint16_t bat100 ; // ADC value for 100 percent battery charge
} ;
struct WifiInfo_t // For list with WiFi info
{
char * ssid ; // SSID for an entry
char * passphrase ; // Passphrase for an entry
} ;
// Preset info
enum station_state_t { ST_PRESET, ST_REDIRECT, // Possible preset status
ST_PLAYLIST, ST_STATION } ;
struct preset_info_t
{
int16_t preset ; // Preset to play
int16_t highest_preset ; // Highest possible preset
station_state_t station_state ; // Station state
int16_t playlistnr ; // Index in playlist
int16_t highest_playlistnr ; // Highest possible preset
String playlisthost ; // Host with playlist
String host ; // Resulting host
String hsym ; // Symbolic name (comment after name)
} ;
const char* TAG = "main" ; // For debug lines
//**************************************************************************************************
// Global data section. *
//**************************************************************************************************
// There is a block ini-data that contains some configuration. Configuration data is *
// saved in the preferences by the webinterface. On restart the new data will *
// de read from these preferences. *
// Items in ini_block can be changed by commands from webserver/MQTT/Serial. *
//**************************************************************************************************
enum datamode_t { INIT = 0x1, HEADER = 0x2, DATA = 0x4, // State for datastream
METADATA = 0x8, PLAYLISTINIT = 0x10,
PLAYLISTHEADER = 0x20, PLAYLISTDATA = 0x40,
STOPREQD = 0x80, STOPPED = 0x100
} ;
// Global variables
preset_info_t presetinfo ; // Info about the current or new station
ini_struct ini_block ; // Holds configurable data
AsyncWebServer cmdserver ( 80 ) ; // Instance of embedded webserver, port 80
AsyncClient* mp3client = NULL ; // An instance of the mp3 client
WiFiClient wmqttclient ; // An instance for mqtt
PubSubClient mqttclient ( wmqttclient ) ; // Client for MQTT subscriber
TaskHandle_t maintask ; // Taskhandle for main task
TaskHandle_t xplaytask ; // Task handle for playtask
TaskHandle_t xsdtask ; // Task handle for SD task
hw_timer_t* timer = NULL ; // For timer
char timetxt[9] ; // Converted timeinfo
const qdata_struct stopcmd = {QSTOPSONG} ; // Command for radio/SD
const qdata_struct startcmd = {QSTARTSONG} ; // Command for radio/SD
QueueHandle_t radioqueue = 0 ; // Queue for icecast commands
QueueHandle_t dataqueue = 0 ; // Queue for mp3 datastream
QueueHandle_t sdqueue = 0 ; // For commands to sdfuncs
qdata_struct outchunk ; // Data to queue
qdata_struct inchunk ; // Data from queue
uint8_t* outqp = outchunk.buf ; // Pointer to buffer in outchunk
uint32_t totalcount = 0 ; // Counter mp3 data
datamode_t datamode ; // State of datastream
int metacount ; // Number of bytes in metadata
int datacount ; // Counter databytes before metadata
RTC_NOINIT_ATTR char metalinebf[METASIZ + 1] ; // Buffer for metaline/ID3 tags
RTC_NOINIT_ATTR char cmd[130] ; // Command from MQTT or Serial
int16_t metalinebfx ; // Index for metalinebf
String icystreamtitle ; // Streamtitle from metadata
String icyname ; // Icecast station name
String audio_ct ; // Content-type, like "audio/aacp"
String ipaddress ; // Own IP-address
int bitrate ; // Bitrate in kb/sec
int mbitrate ; // Measured bitrate
int metaint = 0 ; // Number of databytes between metadata
bool reqtone = false ; // New tone setting requested
bool muteflag = false ; // Mute output
bool resetreq = false ; // Request to reset the ESP32
bool testreq = false ; // Request to print test info
bool sleepreq = false ; // Request for deep sleep
bool eth_connected = false ; // Ethernet connected or not
bool NetworkFound = false ; // True if WiFi network connected
bool mqtt_on = false ; // MQTT in use
uint16_t mqttcount = 0 ; // Counter MAXMQTTCONNECTS
int8_t playingstat = 0 ; // 1 if radio is playing (for MQTT)
int16_t playlist_num = 0 ; // Nonzero for selection from playlist
bool chunked = false ; // Station provides chunked transfer
int chunkcount = 0 ; // Counter for chunked transfer
uint16_t ir_value = 0 ; // IR code
uint32_t ir_0 = 550 ; // Average duration of an IR short pulse
uint32_t ir_1 = 1650 ; // Average duration of an IR long pulse
struct tm timeinfo ; // Will be filled by NTP server
bool time_req = false ; // Set time requested
uint16_t adcvalraw ; // ADC value (raw)
uint16_t adcval ; // ADC value (battery voltage, averaged)
uint32_t clength ; // Content length found in http header
uint16_t bltimer = 0 ; // Backlight time-out counter
bool dsp_ok = false ; // Display okay or not
int ir_intcount = 0 ; // For test IR interrupts
bool spftrigger = false ; // To trigger execution of special functions
const char* fixedwifi = "" ; // Used for FIXEDWIFI option
File SPIFFSfile ; /// File handle for SPIFFS file
std::vector<WifiInfo_t> wifilist ; // List with wifi_xx info
// nvs stuff
const esp_partition_t* nvs ; // Pointer to partition struct
esp_err_t nvserr ; // Error code from nvs functions
uint32_t nvshandle = 0 ; // Handle for nvs access
RTC_NOINIT_ATTR char nvskeys[MAXKEYS][NVS_KEY_NAME_MAX_SIZE] ; // Space for NVS keys
// Rotary encoder stuff
#define sv DRAM_ATTR static volatile
sv uint16_t clickcount = 0 ; // Incremented per encoder click
sv int16_t rotationcount = 0 ; // Current position of rotary switch
sv uint16_t enc_inactivity = 0 ; // Time inactive
sv bool singleclick = false ; // True if single click detected
sv bool doubleclick = false ; // True if double click detected
sv bool tripleclick = false ; // True if triple click detected
sv bool longclick = false ; // True if longclick detected
enum enc_menu_t { VOLUME, PRESET, TRACK } ; // State for rotary encoder menu
enc_menu_t enc_menu_mode = VOLUME ; // Default is VOLUME mode
//
struct progpin_struct // For programmable input pins
{
int8_t gpio ; // Pin number
bool reserved ; // Reserved for connected devices
bool avail ; // Pin is available for a command
String command ; // Command to execute when activated
// Example: "uppreset=1"
bool cur ; // Current state, true = HIGH, false = LOW
} ;
progpin_struct progpin[] = // Input pins and programmed function
{
{ 0, false, false, "", false },
//{ 1, true, false, "", false }, // Reserved for TX Serial output
{ 2, false, false, "", false },
//{ 3, true, false, "", false }, // Reserved for RX Serial input
{ 4, false, false, "", false },
{ 5, false, false, "", false },
//{ 6, true, false, "", false }, // Reserved for FLASH SCK
//{ 7, true, false, "", false }, // Reserved for FLASH D0
//{ 8, true, false, "", false }, // Reserved for FLASH D1
//{ 9, true, false, "", false }, // Reserved for FLASH D2
//{ 10, true, false, "", false }, // Reserved for FLASH D3
//{ 11, true, false, "", false }, // Reserved for FLASH CMD
{ 12, false, false, "", false },
{ 13, false, false, "", false },
{ 14, false, false, "", false },
{ 15, false, false, "", false },
{ 16, false, false, "", false }, // May be UART 2 RX for Nextion
{ 17, false, false, "", false }, // May be UART 2 TX for Nextion
{ 18, false, false, "", false }, // Default for SPI CLK
{ 19, false, false, "", false }, // Default for SPI MISO
//{ 20, true, false, "", false }, // Not exposed on DEV board
{ 21, false, false, "", false }, // Also Wire SDA
{ 22, false, false, "", false }, // Also Wire SCL
{ 23, false, false, "", false }, // Default for SPI MOSI
//{ 24, true, false, "", false }, // Not exposed on DEV board
{ 25, false, false, "", false }, // DAC output / I2S output
{ 26, false, false, "", false }, // DAC output / I2S output
{ 27, false, false, "", false }, // I2S output
//{ 28, true, false, "", false }, // Not exposed on DEV board
//{ 29, true, false, "", false }, // Not exposed on DEV board
//{ 30, true, false, "", false }, // Not exposed on DEV board
//{ 31, true, false, "", false }, // Not exposed on DEV board
{ 32, false, false, "", false },
{ 33, false, false, "", false },
{ 34, false, false, "", false }, // Note, no internal pull-up
{ 35, false, false, "", false }, // Note, no internal pull-up
//{ 36, true, false, "", false }, // Reserved for ADC battery level
{ 39, false, false, "", false }, // Note, no internal pull-up
{ -1, false, false, "", false } // End of list
} ;
struct touchpin_struct // For programmable input pins
{
int8_t gpio ; // Pin number GPIO
bool reserved ; // Reserved for connected devices
bool avail ; // Pin is available for a command
String command ; // Command to execute when activated
// Example: "uppreset=1"
bool cur ; // Current state, true = HIGH, false = LOW
int16_t count ; // Counter number of times low level
} ;
touchpin_struct touchpin[] = // Touch pins and programmed function
{
{ 4, false, false, "", false, 0 }, // TOUCH0
{ 0, true, false, "", false, 0 }, // TOUCH1, reserved for BOOT button
{ 2, false, false, "", false, 0 }, // TOUCH2
{ 15, false, false, "", false, 0 }, // TOUCH3
{ 13, false, false, "", false, 0 }, // TOUCH4
{ 12, false, false, "", false, 0 }, // TOUCH5
{ 14, false, false, "", false, 0 }, // TOUCH6
{ 27, false, false, "", false, 0 }, // TOUCH7
{ 33, false, false, "", false, 0 }, // TOUCH8
{ 32, false, false, "", false, 0 }, // TOUCH9
{ -1, false, false, "", false, 0 } // End of list
// End of table
} ;
//**************************************************************************************************
// End of global data section. *
//**************************************************************************************************
//**************************************************************************************************
// M Q T T P U B _ C L A S S *
//**************************************************************************************************
// ID's for the items to publish to MQTT. Is index in amqttpub[]
enum { MQTT_IP, MQTT_ICYNAME, MQTT_STREAMTITLE, MQTT_NOWPLAYING,
MQTT_PRESET, MQTT_VOLUME, MQTT_PLAYING, MQTT_PLAYLISTPOS
} ;
enum { MQSTRING, MQINT8, MQINT16 } ; // Type of variable to publish
class mqttpubc // For MQTT publishing
{
struct mqttpub_struct
{
const char* topic ; // Topic as partial string (without prefix)
uint8_t type ; // Type of payload
void* payload ; // Payload for this topic
bool topictrigger ; // Set to true to trigger MQTT publish
} ;
// Publication topics for MQTT. The topic will be pefixed by "PREFIX/", where PREFIX is replaced
// by the the mqttprefix in the preferences.
protected:
mqttpub_struct amqttpub[9] = // Definitions of various MQTT topic to publish
{ // Index is equal to enum above
{ "ip", MQSTRING, &ipaddress, false }, // Definition for MQTT_IP
{ "icy/name", MQSTRING, &icyname, false }, // Definition for MQTT_ICYNAME
{ "icy/streamtitle", MQSTRING, &icystreamtitle, false }, // Definition for MQTT_STREAMTITLE
{ "nowplaying", MQSTRING, &ipaddress, false }, // Definition for MQTT_NOWPLAYING
{ "preset" , MQINT8, &presetinfo.preset, false }, // Definition for MQTT_PRESET
{ "volume" , MQINT8, &ini_block.reqvol, false }, // Definition for MQTT_VOLUME
{ "playing", MQINT8, &playingstat, false }, // Definition for MQTT_PLAYING
{ "playlist/pos", MQINT16, &presetinfo.playlistnr, false }, // Definition for MQTT_PLAYLISTPOS
{ NULL, 0, NULL, false } // End of definitions
} ;
public:
void trigger ( uint8_t item ) ; // Trigger publishing for one item
void triggerall () ; // Trigger all items
void publishtopic() ; // Publish triggerer items
} ;
//**************************************************************************************************
// MQTTPUB class implementation. *
//**************************************************************************************************
//**************************************************************************************************
// T R I G G E R *
//**************************************************************************************************
// Set request for an item to publish to MQTT. *
//**************************************************************************************************
void mqttpubc::trigger ( uint8_t item ) // Trigger publishig for one item
{
amqttpub[item].topictrigger = true ; // Request re-publish for an item
}
//**************************************************************************************************
// T R I G G E R A L L *
//**************************************************************************************************
// Set request for all items to publish to MQTT. *
//**************************************************************************************************
void mqttpubc::triggerall() // Trigger publishig for one item
{
int item = 0 ; // Item to refresh
while ( amqttpub[item].topic ) // Cycle through the list of items
{
trigger ( item++ ) ; // Trigger this item and select next
}
}
//**************************************************************************************************
// P U B L I S H T O P I C *
//**************************************************************************************************
// Publish a topic to MQTT broker. *
//**************************************************************************************************
void mqttpubc::publishtopic()
{
int i = 0 ; // Loop control
char topic[80] ; // Topic to send
const char* payload ; // Points to payload
char intvar[10] ; // Space for integer parameter
while ( amqttpub[i].topic )
{
if ( amqttpub[i].topictrigger ) // Topic ready to send?
{
amqttpub[i].topictrigger = false ; // Success or not: clear trigger
sprintf ( topic, "%s/%s", ini_block.mqttprefix.c_str(),
amqttpub[i].topic ) ; // Add prefix to topic
switch ( amqttpub[i].type ) // Select conversion method
{
case MQSTRING :
payload = ((String*)amqttpub[i].payload)->c_str() ;
//payload = pstr->c_str() ; // Get pointer to payload
break ;
case MQINT8 :
sprintf ( intvar, "%d",
*(int8_t*)amqttpub[i].payload ) ; // Convert to array of char
payload = intvar ; // Point to this array
break ;
case MQINT16 :
sprintf ( intvar, "%d",
*(int16_t*)amqttpub[i].payload ) ; // Convert to array of char
payload = intvar ; // Point to this array
break ;
default :
continue ; // Unknown data type
}
ESP_LOGI ( TAG, "Publish to topic %s : %s", // Show for debug
topic, payload ) ;
if ( !mqttclient.publish ( topic, payload ) ) // Publish!
{
ESP_LOGE ( TAG, "MQTT publish failed!" ) ; // Failed
}
return ; // Do the rest later
}
i++ ; // Next entry
}
}
mqttpubc mqttpub ; // Instance for mqttpubc
//
// Include software for the right display
#ifdef BLUETFT
#include "bluetft.h" // For ILI9163C or ST7735S 128x160 display
#endif
#ifdef ST7789
#include "ST7789.h" // For ST7789 240x240 display
#endif
#ifdef ILI9341
#include "ILI9341.h" // For ILI9341 320x240 display
#endif
#ifdef OLED1306
#include "oled.h" // For OLED I2C SD1306 64x128 display
#endif
#ifdef OLED1309
#include "oled.h" // For OLED I2C SD1309 64x128 display
#endif
#ifdef OLED1106
#include "oled.h" // For OLED I2C SH1106 64x128 display
#endif
#ifdef LCD1602I2C
#include "LCD1602.h" // For LCD 1602 display (I2C)
#endif
#ifdef LCD2004I2C
#include "LCD2004.h" // For LCD 2004 display (I2C)
#endif
#ifdef DUMMYTFT
#include "dummytft.h" // For Dummy display
#endif
#ifdef NEXTION
#include "NEXTION.h" // For NEXTION display
#endif
// Include software for SD card. Will include dummy if "SDCARD" is not defined
#include "SDcard.h" // For SD card interface
//**************************************************************************************************
// M Y Q U E U E S E N D *
//**************************************************************************************************
// Send to queue if existing. *
//**************************************************************************************************
void myQueueSend ( QueueHandle_t q, const void* msg, int waittime = 0 )
{
if ( q ) // Check if we have a legal queue
{
xQueueSend ( q, msg, waittime ) ; // Queue okay, send to it
}
}
//**************************************************************************************************
// B L S E T *
//**************************************************************************************************
// Enable or disable the TFT backlight if configured. *
// May be called from interrupt level. *
//**************************************************************************************************
void IRAM_ATTR blset ( bool enable )
{
if ( ini_block.tft_bl_pin >= 0 ) // Backlight for TFT control?
{
digitalWrite ( ini_block.tft_bl_pin, enable ) ; // Enable/disable backlight
}
if ( ini_block.tft_blx_pin >= 0 ) // Backlight for TFT (inversed logic) control?
{
digitalWrite ( ini_block.tft_blx_pin, !enable ) ; // Enable/disable backlight
}
if ( enable )
{
bltimer = 0 ; // Reset counter backlight time-out
}
}
//**************************************************************************************************
// N V S O P E N *
//**************************************************************************************************
// Open Preferences with my-app namespace. Each application module, library, etc. *
// has to use namespace name to prevent key name collisions. We will open storage in *
// RW-mode (second parameter has to be false). *
//**************************************************************************************************
void nvsopen()
{
if ( ! nvshandle ) // Opened already?
{
nvserr = nvs_open ( NAME, NVS_READWRITE, &nvshandle ) ; // No, open nvs
if ( nvserr )
{
ESP_LOGE ( TAG, "nvs_open failed!" ) ;
}
}
}
//**************************************************************************************************
// N V S C L E A R *
//**************************************************************************************************
// Clear all preferences. *
//**************************************************************************************************
esp_err_t nvsclear()
{
nvsopen() ; // Be sure to open nvs
return nvs_erase_all ( nvshandle ) ; // Clear all keys
}
//**************************************************************************************************
// N V S G E T S T R *
//**************************************************************************************************
// Read a string from nvs. *
//**************************************************************************************************
String nvsgetstr ( const char* key )
{
static char nvs_buf[NVSBUFSIZE] ; // Buffer for contents
size_t len = NVSBUFSIZE ; // Max length of the string, later real length
nvsopen() ; // Be sure to open nvs
nvs_buf[0] = '\0' ; // Return empty string on error
nvserr = nvs_get_str ( nvshandle, key, nvs_buf, &len ) ;
if ( nvserr )
{
ESP_LOGE ( TAG, "nvs_get_str failed %X for key %s, keylen is %d, len is %d!",
nvserr, key, strlen ( key), len ) ;
ESP_LOGE ( TAG, "Contents: %s", nvs_buf ) ;
}
return String ( nvs_buf ) ;
}
//**************************************************************************************************
// N V S S E T S T R *
//**************************************************************************************************
// Put a key/value pair in nvs. Length is limited to allow easy read-back. *
// No writing if no change. *
//**************************************************************************************************
esp_err_t nvssetstr ( const char* key, String val )
{
String curcont ; // Current contents
bool wflag = true ; // Assume update or new key
//ESP_LOGI ( TAG, "Setstring for %s: %s", key, val.c_str() ) ;
if ( val.length() >= NVSBUFSIZE ) // Limit length of string to store
{
ESP_LOGE ( TAG, "nvssetstr length failed!" ) ;
return ESP_ERR_NVS_NOT_ENOUGH_SPACE ;
}
if ( nvssearch ( key ) ) // Already in nvs?
{
curcont = nvsgetstr ( key ) ; // Read current value
wflag = ( curcont != val ) ; // Value change?
}
if ( wflag ) // Update or new?
{
//ESP_LOGI ( TAG, "nvssetstr update value" ) ;
nvserr = nvs_set_str ( nvshandle, key, val.c_str() ) ; // Store key and value
if ( nvserr ) // Check error
{
ESP_LOGE ( TAG, "nvssetstr failed!" ) ;
}
}
return nvserr ;
}
//**************************************************************************************************
// N V S S E A R C H *
//**************************************************************************************************
// Check if key exists in nvs. *
//**************************************************************************************************
bool nvssearch ( const char* key )
{
size_t len = NVSBUFSIZE ; // Length of the string
nvsopen() ; // Be sure to open nvs
nvserr = nvs_get_str ( nvshandle, key, NULL, &len ) ; // Get length of contents
return ( nvserr == ESP_OK ) ; // Return true if found
}
//**************************************************************************************************
// Q U E U E T O P T *
//**************************************************************************************************
// Queue a special function for the play task. *
// These are high priority messages like stop or start. So we make sure the message fits. *
//**************************************************************************************************
void queueToPt ( qdata_type func )
{
qdata_struct specchunk ; // Special function to queue
while ( xQueueReceive ( dataqueue, &specchunk, 0 ) ) ; // Empty the queue
specchunk.datatyp = func ; // Put function in datatyp
xQueueSendToFront ( dataqueue, &specchunk, 200 ) ; // Send to queue (First Out)
vTaskDelay ( 1 ) ; // Give Play task time to react
}
//**************************************************************************************************
// T F T S E T *
//**************************************************************************************************
// Request to display a segment on TFT. Version for char* and String parameter. *
//**************************************************************************************************
void tftset ( uint16_t inx, const char *str )
{
if ( inx < TFTSECS ) // Segment available on display
{
if ( str ) // String specified?
{
tftdata[inx].str = String ( str ) ; // Yes, set string
}
tftdata[inx].update_req = true ; // and request flag
}
}
void tftset ( uint16_t inx, String& str )
{
if ( inx < TFTSECS ) // Segment available on display
{
tftdata[inx].str = str ; // Set string
tftdata[inx].update_req = true ; // and request flag
}
}
//**************************************************************************************************
// U P D A T E N R *
//**************************************************************************************************
// Used by nextPreset because update for preset and playlist number is about the same. *
// Modify the pnr, handle over- and underflow. handle relative setting. *
//**************************************************************************************************
bool updateNr ( int16_t* pnr, int16_t maxnr, int16_t nr, bool relative )
{
bool res = true ; // Assume positive result
//ESP_LOGI ( TAG, "updateNr %d <= %d to %d, relative is %d",
// *pnr, maxnr, nr, relative ) ;
if ( relative ) // Relative to pnr?
{
*pnr += nr ; // Yes, compute new pnr
}
else
{
*pnr = nr ; // Not relative, set direct pnr
}
if ( *pnr < 0 ) // Check result
{
res = false ; // Negative result, set bad result
*pnr = maxnr ; // and wrap
}
if ( *pnr > maxnr ) // Check if result beyond max
{
res = false ; // Too high, set bad result
*pnr = 0 ; // and wrap
}
//ESP_LOGI ( TAG, "updateNr result is %d", *pnr ) ;
return res ; // Return the result
}
//**************************************************************************************************
// N E X T P R E S E T *
//**************************************************************************************************
// Set the preset for the next station. May be relative. *
//**************************************************************************************************
bool nextPreset ( int16_t pnr, bool relative = false )
{
//ESP_LOGI ( TAG, "nextpreset called with pnr = %d", pnr ) ;
if ( ( presetinfo.station_state == ST_STATION ) || // In station mode?
( presetinfo.station_state == ST_REDIRECT ) ) // or redirect mode?
{
presetinfo.station_state = ST_PRESET ; // No "next" in station/redirect mode
}
if ( presetinfo.station_state == ST_PLAYLIST ) // In playlist mode?
{
if ( ! updateNr ( &presetinfo.playlistnr, // Yes, next index possible?
presetinfo.highest_playlistnr,
pnr, relative ) )
{
presetinfo.station_state = ST_PRESET ; // No, end playlist mode
}
}
if ( presetinfo.station_state == ST_PRESET ) // In preset mode?
{
updateNr ( &presetinfo.preset, // Select next preset
presetinfo.highest_preset,
pnr, relative ) ;
if ( ! readhostfrompref ( presetinfo.preset, // Set host
&presetinfo.host,
&presetinfo.hsym ) )
{
return false ;
}
ESP_LOGI ( TAG, "nextPreset is %d", presetinfo.preset ) ;
}
return true ;
}
//**************************************************************************************************
// T I M E R 1 0 S E C *
//**************************************************************************************************
// Extra watchdog. Called every 10 seconds. *
// If totalcount has not been changed, there is a problem and playing will stop. *
// Note that calling timely procedures within this routine or in called functions will *
// cause a crash! *
//**************************************************************************************************
void IRAM_ATTR timer10sec()
{
static uint32_t oldtotalcount = 7321 ; // Needed for change detection
static uint8_t morethanonce = 0 ; // Counter for succesive fails
uint32_t bytesplayed ; // Bytes send to MP3 converter
if ( datamode & ( INIT | HEADER | DATA | // Test op playing
METADATA | PLAYLISTINIT |
PLAYLISTHEADER |
PLAYLISTDATA ) )
{
bytesplayed = totalcount - oldtotalcount ; // Number of bytes played in the 10 seconds
oldtotalcount = totalcount ; // Save for comparison in next cycle
if ( bytesplayed == 0 ) // Still playing?
{
if ( morethanonce > 10 ) // No! Happened too many times?
{
resetreq = true ; // Yes, restart
}
//if ( datamode & ( PLAYLISTDATA | // In playlist mode?
// PLAYLISTINIT |
// PLAYLISTHEADER ) )
//{
// playlist_num = 0 ; // Yes, end of playlist
//}
//if ( ( morethanonce > 0 ) || // Happened more than once?
// ( playlist_num > 0 ) ) // Or playlist active?
if ( morethanonce > 0 ) // Happened more than once?
{
datamode = STOPREQD ; // Stop player
}
morethanonce++ ; // Count the fails
}
else
{
// // Data has been send to MP3 decoder
// Bitrate in kbits/s is bytesplayed / 10 / 1000 * 8
mbitrate = ( bytesplayed + 625 ) / 1250 ; // Measured bitrate, rounded
morethanonce = 0 ; // Data seen, reset failcounter
}
}
}
//**************************************************************************************************
// T I M E R 1 0 0 *
//**************************************************************************************************
// Called every 100 msec on interrupt level, so must be in IRAM and no lengthy operations *
// allowed. *
//**************************************************************************************************
void IRAM_ATTR timer100()
{
sv int16_t count10sec = 0 ; // Counter for activatie 10 seconds process
sv int16_t eqcount = 0 ; // Counter for equal number of clicks
sv int16_t oldclickcount = 0 ; // To detect difference
spftrigger = true ; // Activate spfuncs
if ( ++count10sec == 100 ) // 10 seconds passed?
{
timer10sec() ; // Yes, do 10 second procedure
count10sec = 0 ; // Reset count
}
if ( ( count10sec % 10 ) == 0 ) // One second over?
{
if ( ++timeinfo.tm_sec >= 60 ) // Yes, update number of seconds
{
timeinfo.tm_sec = 0 ; // Wrap after 60 seconds
if ( ++timeinfo.tm_min >= 60 )
{
timeinfo.tm_min = 0 ; // Wrap after 60 minutes
if ( ++timeinfo.tm_hour >= 24 )
{
timeinfo.tm_hour = 0 ; // Wrap after 24 hours
}
}
}
time_req = true ; // Yes, show current time request
if ( ++bltimer == BL_TIME ) // Time to blank the TFT screen?
{
bltimer = 0 ; // Yes, reset counter
blset ( false ) ; // Disable TFT (backlight)
}
}
// Handle rotary encoder. Inactivity counter will be reset by encoder interrupt
if ( enc_inactivity < 36000 ) // Count inactivity time, but limit to 36000
{
enc_inactivity++ ;
}
// Now detection of single/double click of rotary encoder switch or ZIPPY B5
if ( clickcount ) // Any click?
{
if ( oldclickcount == clickcount ) // Yes, stable situation?