-
Notifications
You must be signed in to change notification settings - Fork 200
/
Esp_radio.ino
3250 lines (3069 loc) · 152 KB
/
Esp_radio.ino
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//******************************************************************************************
//* Esp_radio -- Webradio receiver for ESP8266, (color) display and VS1053 MP3 module, *
//* by Ed Smallenburg ([email protected]) *
//* With ESP8266 running at 80 MHz, it is capable of handling up to 256 kb bitrate. *
//* With ESP8266 running at 160 MHz, it is capable of handling up to 320 kb bitrate. *
//******************************************************************************************
// ESP8266 libraries used:
// - ESP8266WiFi - Part of ESP8266 Arduino default libraries.
// - SPI - Part of Arduino default libraries.
// - Adafruit_GFX - https://github.com/adafruit/Adafruit-GFX-Library
// - TFT_ILI9163C - https://github.com/sumotoy/TFT_ILI9163C
// - ESPAsyncTCP - https://github.com/me-no-dev/ESPAsyncTCP
// - ESPAsyncWebServer - https://github.com/me-no-dev/ESPAsyncWebServer
// - FS - https://github.com/esp8266/arduino-esp8266fs-plugin/releases/download/0.2.0/ESP8266FS-0.2.0.zip
// - ArduinoOTA - Part of ESP8266 Arduino default libraries.
// - AsyncMqttClient - https://github.com/marvinroger/async-mqtt-client
// - TinyXML - Fork https://github.com/adafruit/TinyXML
//
// A library for the VS1053 (for ESP8266) 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.
//
// Compiling: Set SPIFS to 3 MB. Set IwIP variant to "V1.4 Higher Bandwidth".
// See http://www.internet-radio.com for suitable stations. Add the stations of your choice
// to the .ini-file.
//
// 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 the input button causes the player to select the next preset station present in the .ini file.
//
// The display used is a Chinese 1.8 color TFT module 128 x 160 pixels. The TFT_ILI9163C.h
// file has been changed to reflect this particular module. TFT_ILI9163C.cpp has been
// changed to use the full screenwidth if rotated to mode "3". Now there is room for 26
// characters per line and 16 lines. Software will work without installing the display.
// If no TFT is used, you may use GPIO2 and GPIO15 as control buttons. See definition of "USETFT" below.
// Switches are than programmed as:
// GPIO2 : "Goto station 1"
// GPIO0 : "Next station"
// GPIO15: "Previous station". Note that GPIO15 has to be LOW when starting the ESP8266.
// The button for GPIO15 must therefore be connected to VCC (3.3V) instead of GND.
//
// For configuration of the WiFi network(s): see the global data section further on.
//
// The SPI interface for VS1053 and TFT uses hardware SPI.
//
// Wiring:
// NodeMCU GPIO Pin to program Wired to LCD Wired to VS1053 Wired to rest
// ------- ------ -------------- --------------- ------------------- ---------------------
// D0 GPIO16 16 - pin 1 DCS -
// D1 GPIO5 5 - pin 2 CS LED on nodeMCU
// D2 GPIO4 4 - pin 4 DREQ -
// D3 GPIO0 0 FLASH - - Control button "Next station"
// D4 GPIO2 2 pin 3 (D/C) - (OR)Control button "Station 1"
// D5 GPIO14 14 SCLK pin 5 (CLK) pin 5 SCK -
// D6 GPIO12 12 MISO - pin 7 MISO -
// D7 GPIO13 13 MOSI pin 4 (DIN) pin 6 MOSI -
// D8 GPIO15 15 pin 2 (CS) - (OR)Control button "Previous station"
// D9 GPI03 3 RXD0 - - Reserved serial input
// D10 GPIO1 1 TXD0 - - Reserved serial output
// ------- ------ -------------- --------------- ------------------- ---------------------
// GND - - pin 8 (GND) pin 8 GND Power supply
// VCC 3.3 - - pin 6 (VCC) - LDO 3.3 Volt
// VCC 5 V - - pin 7 (BL) pin 9 5V Power supply
// RST - - pin 1 (RST) pin 3 RESET Reset circuit
//
// The reset circuit is a circuit with 2 diodes to GPIO5 and GPIO16 and a resistor to ground
// (wired OR gate) because there was not a free GPIO output available for this function.
// This circuit is included in the documentation.
// Issues:
// Webserver produces error "LmacRxBlk:1" after some time. After that it will work very slow.
// The program will reset the ESP8266 in such a case. Now we have switched to async webserver,
// the problem still exists, but the program will not crash anymore.
// Upload to ESP8266 not reliable.
//
// 31-03-2016, ES: First set-up.
// 01-04-2016, ES: Detect missing VS1053 at start-up.
// 05-04-2016, ES: Added commands through http server on port 80.
// 14-04-2016, ES: Added icon and switch preset on stream error.
// 18-04-2016, ES: Added SPIFFS for webserver.
// 19-04-2016, ES: Added ringbuffer.
// 20-04-2016, ES: WiFi Passwords through SPIFFS files, enable OTA.
// 21-04-2016, ES: Switch to Async Webserver.
// 27-04-2016, ES: Save settings, so same volume and preset will be used after restart.
// 03-05-2016, ES: Add bass/treble settings (see also new index.html).
// 04-05-2016, ES: Allow stations like "skonto.ls.lv:8002/mp3".
// 06-05-2016, ES: Allow hidden WiFi station if this is the only .pw file.
// 07-05-2016, ES: Added preset selection in webserver.
// 12-05-2016, ES: Added support for Ogg-encoder.
// 13-05-2016, ES: Better Ogg detection.
// 17-05-2016, ES: Analog input for commands, extra buttons if no TFT required.
// 26-05-2016, ES: Fixed BUTTON3 bug (no TFT).
// 27-05-2016, ES: Fixed restore station at restart.
// 04-07-2016, ES: WiFi.disconnect clears old connection now (thanks to Juppit).
// 23-09-2016, ES: Added commands via MQTT and Serial input, Wifi set-up in AP mode.
// 04-10-2016, ES: Configuration in .ini file. No more use of EEPROM and .pw files.
// 11-10-2016, ES: Allow stations that have no bitrate in header like icecast.err.ee/raadio2.mp3.
// 14-10-2016, ES: Updated for async-mqtt-client-master 0.5.0
// 22-10-2016, ES: Correction mute/unmute.
// 15-11-2016, ES: Support for .m3u playlists.
// 22-12-2016, ES: Support for localhost (play from SPIFFS).
// 28-12-2016, ES: Implement "Resume" request.
// 31-12-2016, ES: Allow ContentType "text/css".
// 02-01-2017, ES: Webinterface in PROGMEM.
// 16-01-2017, ES: Correction playlists.
// 17-01-2017, ES: Bugfix config page and playlist.
// 23-01-2017, ES: Bugfix playlist.
// 26-01-2017, ES: Check on wrong icy-metaint.
// 30-01-2017, ES: Allow chunked transfer encoding.
// 01-02-2017, ES: Bugfix file upload.
// 26-04-2017, ES: Better output webinterface on preset change.
// 03-05-2017, ES: Prevent to start inputstream if no network.
// 04-05-2017, ES: Integrate iHeartRadio, thanks to NonaSuomy.
// 09-05-2017, ES: Fixed abs problem.
// 11-05-2017, ES: Convert UTF8 characters before display, thanks to everyb313.
// 24-05-2017, ES: Correction. Do not skip first part of .mp3 file.
// 26-05-2017, ES: Correction playing from .m3u playlist and LC/UC problem.
// 31-05-2017, ES: Volume indicator on TFT.
// 02-02-2018, ES: Force 802.11N connection.
// 18-04-2018, ES: Workaround for not working wifi.connected().
// 05-10-2018, ES: Fixed exception if no network was found.
// 23-04-2018, ES: Check BASS setting.
// 06-07-2021, ES: Switched to LittleFS.
// 06-07-2021, ES: Added SPI RAM (experimental).
// 08-02-2022, ES: Added redirection.
//
// Define the version number, also used for webserver as Last-Modified header:
#define VERSION "Fri, 11 Feb 2022 13:05:00 GMT"
// Experimental SPI-RAM
//#define SPIRAM // Use SPIRAM as ringbuffer. Undefined = do not use
//#define SPIRAMDELAY 100000 // Delay (in bytes) before reading from SPIRAM
// TFT. Define USETFT if required.
#define USETFT
#include <Arduino.h>
#include <ESP8266WiFi.h>
#include <ESPAsyncTCP.h>
#include <ESPAsyncWebServer.h>
#include <AsyncMqttClient.h>
#include <SPI.h>
#if defined ( USETFT )
#include <Adafruit_GFX.h>
#include <TFT_ILI9163C.h>
#endif
#include <Ticker.h>
#include <stdio.h>
#include <string.h>
#include <FS.h>
#include <ArduinoOTA.h>
#include <TinyXML.h>
#include <LittleFS.h>
#ifdef SPIRAM
#include "spiram.hpp"
#endif
extern "C"
{
#include "user_interface.h"
}
// Definitions for 3 control switches on analog input
// You can test the analog input values by holding down the switch and select /?analog=1
// in the web interface. See schematics in the documentation.
// Switches are programmed as "Goto station 1", "Next station" and "Previous station" respectively.
// Set these values to 2000 if not used or tie analog input to ground.
#define NUMANA 3
//#define asw1 252
//#define asw2 334
//#define asw3 499
#define asw1 2000
#define asw2 2000
#define asw3 2000
//
// Color definitions for the TFT screen (if used)
#define BLACK 0x0000
#define BLUE 0xF800
#define RED 0x001F
#define GREEN 0x07E0
#define CYAN GREEN | BLUE
#define MAGENTA RED | BLUE
#define YELLOW RED | GREEN
// Digital I/O used
// Pins for VS1053 module
#define VS1053_CS 5
#define VS1053_DCS 16
#define VS1053_DREQ 4
// Pins CS and DC for TFT module (if used, see definition of "USETFT")
#define TFT_CS 15
#define TFT_DC 2
// Control button (GPIO) for controlling station
#define BUTTON1 2
#define BUTTON2 0
#define BUTTON3 15
// Ringbuffer for smooth playing. 20000 bytes is 160 Kbits, about 1.5 seconds at 128kb bitrate.
// If buffer is too long, the webinterface does not work anymore
#define RINGBFSIZ 18000
// Debug buffer size
#define DEBUG_BUFFER_SIZE 100
// Name of the ini file
#define INIFILENAME "/radio.ini"
// Access point name if connection to WiFi network fails. Also the hostname for WiFi and OTA.
// Not that the password of an AP must be at least as long as 8 characters.
// Also used for other naming.
#define NAME "Esp-radio"
// Maximum number of MQTT reconnects before give-up
#define MAXMQTTCONNECTS 20
//
//******************************************************************************************
// Forward declaration of various functions *
//******************************************************************************************
//void displayinfo ( const char* str, uint16_t pos, uint16_t height, uint16_t color ) ;
void showstreamtitle ( const char* ml, bool full = false ) ;
void handlebyte ( uint8_t b, bool force = false ) ;
void handlebyte_ch ( uint8_t b, bool force = false ) ;
void handleFS ( AsyncWebServerRequest* request ) ;
void handleFSf ( AsyncWebServerRequest* request, const String& filename ) ;
void handleCmd ( AsyncWebServerRequest* request ) ;
void handleFileUpload ( AsyncWebServerRequest* request, String filename,
size_t index, uint8_t* data, size_t len, bool final ) ;
char* dbgprint( const char* format, ... ) ;
char* analyzeCmd ( const char* str ) ;
char* analyzeCmd ( const char* par, const char* val ) ;
String chomp ( String str ) ;
void publishIP() ;
String xmlparse ( String mount ) ;
bool connecttohost() ;
void XML_callback ( uint8_t statusflags, char* tagName, uint16_t tagNameLen,
char* data, uint16_t dataLen ) ;
//
//******************************************************************************************
// Global data section. *
//******************************************************************************************
// There is a block ini-data that contains some configuration. Configuration data is *
// saved in the SPIFFS file radio.ini by the webinterface. On restart the new data will *
// be read from this file. *
// Items in ini_block can be changed by commands from webserver/MQTT/Serial. *
//******************************************************************************************
struct ini_struct
{
String mqttbroker ; // The name of the MQTT broker server
uint16_t mqttport ; // Port, default 1883
String mqttuser ; // User for MQTT authentication
String mqttpasswd ; // Password for MQTT authentication
String mqtttopic ; // Topic to suscribe to
String mqttpubtopic ; // Topic to pubtop (IP will be published)
uint8_t reqvol ; // Requested volume
uint8_t rtone[4] ; // Requested bass/treble settings
int8_t newpreset ; // Requested preset
String ssid ; // SSID of WiFi network to connect to
String passwd ; // Password for WiFi network
} ;
enum datamode_t { INIT = 1, HEADER = 2, DATA = 4,
METADATA = 8, PLAYLISTINIT = 16,
PLAYLISTHEADER = 32, PLAYLISTDATA = 64,
STOPREQD = 128, STOPPED = 256
} ; // State for datastream
// Global variables
int DEBUG = 1 ;
ini_struct ini_block ; // Holds configurable data
WiFiClient *mp3client = NULL ; // An instance of the mp3 client
AsyncWebServer cmdserver ( 80 ) ; // Instance of embedded webserver on port 80
AsyncMqttClient mqttclient ; // Client for MQTT subscriber
IPAddress mqtt_server_IP ; // IP address of MQTT broker
char cmd[130] ; // Command from MQTT or Serial
#if defined ( USETFT )
TFT_ILI9163C tft = TFT_ILI9163C ( TFT_CS, TFT_DC ) ;
#endif
Ticker tckr ; // For timing 100 msec
TinyXML xml; // For XML parser.
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
String metaline ; // Readable line in metadata
String icystreamtitle ; // Streamtitle from metadata
String icyname ; // Icecast station name
int bitrate ; // Bitrate in kb/sec
int metaint = 0 ; // Number of databytes between metadata
int8_t currentpreset = -1 ; // Preset station playing
String host ; // The URL to connect to or file to play
String playlist ; // The URL of the specified playlist
bool xmlreq = false ; // Request for XML parse.
bool hostreq = false ; // Request for new host
bool reqtone = false ; // New tone setting requested
bool muteflag = false ; // Mute output
uint8_t* ringbuf ; // Ringbuffer for VS1053
uint16_t rbwindex = 0 ; // Fill pointer in ringbuffer
uint16_t rbrindex = RINGBFSIZ - 1 ; // Emptypointer in ringbuffer
uint16_t rcount = 0 ; // Nr of bytes/chunks in ringbuffer/SPIRAM
uint16_t analogsw[NUMANA] = { asw1, asw2, asw3 } ; // 3 levels of analog input
uint16_t analogrest ; // Rest value of analog input
bool resetreq = false ; // Request to reset the ESP8266
bool NetworkFound ; // True if WiFi network connected
String networks ; // Found networks
String anetworks ; // Aceptable networks (present in .ini file)
String presetlist ; // List for webserver
uint8_t num_an ; // Number of acceptable networks in .ini file
String testfilename = "" ; // File to test (SPIFFS speed)
uint16_t mqttcount = 0 ; // Counter MAXMQTTCONNECTS
int8_t playlist_num = 0 ; // Nonzero for selection from playlist
File mp3file ; // File containing mp3 on SPIFFS
bool localfile = false ; // Play from local mp3-file or not
bool chunked = false ; // Station provides chunked transfer
int chunkcount = 0 ; // Counter for chunked transfer
uint8_t prcwinx ; // Index in pwchunk (see putring)
uint8_t prcrinx ; // Index in prchunk (see getring)
#ifdef SPIRAM
int32_t spiramdelay = SPIRAMDELAY ; // Delay before reading from SPIRAM
#endif
// XML parse globals.
const char* xmlhost = "playerservices.streamtheworld.com" ;// XML data source
const char* xmlget = "GET /api/livestream" // XML get parameters
"?version=1.5" // API Version of IHeartRadio
"&mount=%sAAC" // MountPoint with Station Callsign
"&lang=en" ; // Language
int xmlport = 80 ; // XML Port
uint8_t xmlbuffer[150] ; // For XML decoding
String xmlOpen ; // Opening XML tag
String xmlTag ; // Current XML tag
String xmlData ; // Data inside tag
String stationServer( "" ) ; // Radio stream server
String stationPort( "" ) ; // Radio stream port
String stationMount( "" ) ; // Radio stream Callsign
//******************************************************************************************
// End of global data section. *
//******************************************************************************************
//******************************************************************************************
// Pages and CSS for the webinterface. *
//******************************************************************************************
#include "about_html.h"
#include "config_html.h"
#include "index_html.h"
#include "radio_css.h"
#include "favicon_ico.h"
//
//******************************************************************************************
// VS1053 stuff. Based on maniacbug library. *
//******************************************************************************************
// VS1053 class definition. *
//******************************************************************************************
class VS1053
{
private:
uint8_t cs_pin ; // Pin where CS line is connected
uint8_t dcs_pin ; // Pin where DCS line is connected
uint8_t dreq_pin ; // Pin where DREQ line is connected
uint8_t curvol ; // Current volume setting 0..100%
const uint8_t vs1053_chunk_size = 32 ;
// SCI Register
const uint8_t SCI_MODE = 0x0 ;
const uint8_t SCI_BASS = 0x2 ;
const uint8_t SCI_CLOCKF = 0x3 ;
const uint8_t SCI_AUDATA = 0x5 ;
const uint8_t SCI_WRAM = 0x6 ;
const uint8_t SCI_WRAMADDR = 0x7 ;
const uint8_t SCI_AIADDR = 0xA ;
const uint8_t SCI_VOL = 0xB ;
const uint8_t SCI_AICTRL0 = 0xC ;
const uint8_t SCI_AICTRL1 = 0xD ;
const uint8_t SCI_num_registers = 0xF ;
// SCI_MODE bits
const uint8_t SM_SDINEW = 11 ; // Bitnumber in SCI_MODE always on
const uint8_t SM_RESET = 2 ; // Bitnumber in SCI_MODE soft reset
const uint8_t SM_CANCEL = 3 ; // Bitnumber in SCI_MODE cancel song
const uint8_t SM_TESTS = 5 ; // Bitnumber in SCI_MODE for tests
const uint8_t SM_LINE1 = 14 ; // Bitnumber in SCI_MODE for Line input
SPISettings VS1053_SPI ; // SPI settings for this slave
uint8_t endFillByte ; // Byte to send when stopping song
protected:
inline void await_data_request() const
{
while ( !digitalRead ( dreq_pin ) )
{
yield() ; // Very short delay
}
}
inline void control_mode_on() const
{
SPI.beginTransaction ( VS1053_SPI ) ; // Prevent other SPI users
digitalWrite ( dcs_pin, HIGH ) ; // Bring slave in control mode
digitalWrite ( cs_pin, LOW ) ;
}
inline void control_mode_off() const
{
digitalWrite ( cs_pin, HIGH ) ; // End control mode
SPI.endTransaction() ; // Allow other SPI users
}
inline void data_mode_on() const
{
SPI.beginTransaction ( VS1053_SPI ) ; // Prevent other SPI users
digitalWrite ( cs_pin, HIGH ) ; // Bring slave in data mode
digitalWrite ( dcs_pin, LOW ) ;
}
inline void data_mode_off() const
{
digitalWrite ( dcs_pin, HIGH ) ; // End data mode
SPI.endTransaction() ; // Allow other SPI users
}
uint16_t read_register ( uint8_t _reg ) const ;
void write_register ( uint8_t _reg, uint16_t _value ) const ;
void sdi_send_buffer ( uint8_t* data, size_t len ) ;
void sdi_send_fillers ( size_t length ) ;
void wram_write ( uint16_t address, uint16_t data ) ;
uint16_t wram_read ( uint16_t address ) ;
public:
// Constructor. Only sets pin values. Doesn't touch the chip. Be sure to call begin()!
VS1053 ( uint8_t _cs_pin, uint8_t _dcs_pin, uint8_t _dreq_pin ) ;
void begin() ; // Begin operation. Sets pins correctly,
// and prepares SPI bus.
void startSong() ; // Prepare to start playing. Call this each
// time a new song starts.
void playChunk ( uint8_t* data, size_t len ) ; // Play a chunk of data. Copies the data to
// the chip. Blocks until complete.
void stopSong() ; // Finish playing a song. Call this after
// the last playChunk call.
void setVolume ( uint8_t vol ) ; // Set the player volume.Level from 0-100,
// higher is louder.
void setTone ( uint8_t* rtone ) ; // Set the player baas/treble, 4 nibbles for
// treble gain/freq and bass gain/freq
uint8_t getVolume() ; // Get the currenet volume setting.
// higher is louder.
void printDetails ( const char *header ) ; // Print configuration details to serial output.
void softReset() ; // Do a soft reset
bool testComm ( const char *header ) ; // Test communication with module
inline bool data_request() const
{
return ( digitalRead ( dreq_pin ) == HIGH ) ;
}
void AdjustRate ( long ppm2 ) ; // Fine tune the datarate
} ;
//******************************************************************************************
// VS1053 class implementation. *
//******************************************************************************************
VS1053::VS1053 ( uint8_t _cs_pin, uint8_t _dcs_pin, uint8_t _dreq_pin ) :
cs_pin(_cs_pin), dcs_pin(_dcs_pin), dreq_pin(_dreq_pin)
{
}
uint16_t VS1053::read_register ( uint8_t _reg ) const
{
uint16_t result ;
control_mode_on() ;
SPI.write ( 3 ) ; // Read operation
SPI.write ( _reg ) ; // Register to write (0..0xF)
// Note: transfer16 does not seem to work
result = ( SPI.transfer ( 0xFF ) << 8 ) | // Read 16 bits data
( SPI.transfer ( 0xFF ) ) ;
await_data_request() ; // Wait for DREQ to be HIGH again
control_mode_off() ;
return result ;
}
void VS1053::write_register ( uint8_t _reg, uint16_t _value ) const
{
control_mode_on( );
SPI.write ( 2 ) ; // Write operation
SPI.write ( _reg ) ; // Register to write (0..0xF)
SPI.write16 ( _value ) ; // Send 16 bits data
await_data_request() ;
control_mode_off() ;
}
void VS1053::sdi_send_buffer ( uint8_t* data, size_t len )
{
size_t chunk_length ; // Length of chunk 32 byte or shorter
data_mode_on() ;
while ( len ) // More to do?
{
await_data_request() ; // Wait for space available
chunk_length = len ;
if ( len > vs1053_chunk_size )
{
chunk_length = vs1053_chunk_size ;
}
len -= chunk_length ;
SPI.writeBytes ( data, chunk_length ) ;
data += chunk_length ;
}
data_mode_off() ;
}
void VS1053::sdi_send_fillers ( size_t len )
{
size_t chunk_length ; // Length of chunk 32 byte or shorter
data_mode_on() ;
while ( len ) // More to do?
{
await_data_request() ; // Wait for space available
chunk_length = len ;
if ( len > vs1053_chunk_size )
{
chunk_length = vs1053_chunk_size ;
}
len -= chunk_length ;
while ( chunk_length-- )
{
SPI.write ( endFillByte ) ;
}
}
data_mode_off();
}
void VS1053::wram_write ( uint16_t address, uint16_t data )
{
write_register ( SCI_WRAMADDR, address ) ;
write_register ( SCI_WRAM, data ) ;
}
uint16_t VS1053::wram_read ( uint16_t address )
{
write_register ( SCI_WRAMADDR, address ) ; // Start reading from WRAM
return read_register ( SCI_WRAM ) ; // Read back result
}
bool VS1053::testComm ( const char *header )
{
// Test the communication with the VS1053 module. The result wille be returned.
// If DREQ is low, there is problably no VS1053 connected. Pull the line HIGH
// in order to prevent an endless loop waiting for this signal. The rest of the
// software will still work, but readbacks from VS1053 will fail.
int i ; // Loop control
uint16_t r1, r2, cnt = 0 ;
uint16_t delta = 300 ; // 3 for fast SPI
if ( !digitalRead ( dreq_pin ) )
{
dbgprint ( "VS1053 not properly installed!" ) ;
// Allow testing without the VS1053 module
pinMode ( dreq_pin, INPUT_PULLUP ) ; // DREQ is now input with pull-up
return false ; // Return bad result
}
// Further TESTING. Check if SCI bus can write and read without errors.
// We will use the volume setting for this.
// Will give warnings on serial output if DEBUG is active.
// A maximum of 20 errors will be reported.
if ( strstr ( header, "Fast" ) )
{
delta = 3 ; // Fast SPI, more loops
}
dbgprint ( header ) ; // Show a header
for ( i = 0 ; ( i < 0xFFFF ) && ( cnt < 20 ) ; i += delta )
{
write_register ( SCI_VOL, i ) ; // Write data to SCI_VOL
r1 = read_register ( SCI_VOL ) ; // Read back for the first time
r2 = read_register ( SCI_VOL ) ; // Read back a second time
if ( r1 != r2 || i != r1 || i != r2 ) // Check for 2 equal reads
{
dbgprint ( "VS1053 error retry SB:%04X R1:%04X R2:%04X", i, r1, r2 ) ;
cnt++ ;
delay ( 10 ) ;
}
yield() ; // Allow ESP firmware to do some bookkeeping
}
return ( cnt == 0 ) ; // Return the result
}
void VS1053::begin()
{
pinMode ( dreq_pin, INPUT ) ; // DREQ is an input
pinMode ( cs_pin, OUTPUT ) ; // The SCI and SDI signals
pinMode ( dcs_pin, OUTPUT ) ;
digitalWrite ( dcs_pin, HIGH ) ; // Start HIGH for SCI en SDI
digitalWrite ( cs_pin, HIGH ) ;
delay ( 100 ) ;
dbgprint ( "Reset VS1053..." ) ;
digitalWrite ( dcs_pin, LOW ) ; // Low & Low will bring reset pin low
digitalWrite ( cs_pin, LOW ) ;
delay ( 2000 ) ;
dbgprint ( "End reset VS1053..." ) ;
digitalWrite ( dcs_pin, HIGH ) ; // Back to normal again
digitalWrite ( cs_pin, HIGH ) ;
delay ( 500 ) ;
// Init SPI in slow mode ( 0.2 MHz )
VS1053_SPI = SPISettings ( 200000, MSBFIRST, SPI_MODE0 ) ;
//printDetails ( "Right after reset/startup" ) ;
delay ( 20 ) ;
//printDetails ( "20 msec after reset" ) ;
testComm ( "Slow SPI,Testing VS1053 read/write registers..." ) ;
// Most VS1053 modules will start up in midi mode. The result is that there is no audio
// when playing MP3. You can modify the board, but there is a more elegant way:
wram_write ( 0xC017, 3 ) ; // GPIO DDR = 3
wram_write ( 0xC019, 0 ) ; // GPIO ODATA = 0
delay ( 100 ) ;
//printDetails ( "After test loop" ) ;
softReset() ; // Do a soft reset
// Switch on the analog parts
write_register ( SCI_AUDATA, 44100 + 1 ) ; // 44.1kHz + stereo
// The next clocksetting allows SPI clocking at 5 MHz, 4 MHz is safe then.
write_register ( SCI_CLOCKF, 6 << 12 ) ; // Normal clock settings multiplyer 3.0 = 12.2 MHz
//SPI Clock to 4 MHz. Now you can set high speed SPI clock.
VS1053_SPI = SPISettings ( 4000000, MSBFIRST, SPI_MODE0 ) ;
write_register ( SCI_MODE, _BV ( SM_SDINEW ) | _BV ( SM_LINE1 ) ) ;
testComm ( "Fast SPI, Testing VS1053 read/write registers again..." ) ;
delay ( 10 ) ;
await_data_request() ;
endFillByte = wram_read ( 0x1E06 ) & 0xFF ;
dbgprint ( "endFillByte is %X", endFillByte ) ;
//printDetails ( "After last clocksetting" ) ;
delay ( 100 ) ;
}
void VS1053::setVolume ( uint8_t vol )
{
// Set volume. Both left and right.
// Input value is 0..100. 100 is the loudest.
// Clicking reduced by using 0xf8 to 0x00 as limits.
uint16_t value ; // Value to send to SCI_VOL
if ( vol != curvol )
{
curvol = vol ; // Save for later use
value = map ( vol, 0, 100, 0xF8, 0x00 ) ; // 0..100% to one channel
value = ( value << 8 ) | value ;
write_register ( SCI_VOL, value ) ; // Volume left and right
}
}
void VS1053::setTone ( uint8_t *rtone ) // Set bass/treble (4 nibbles)
{
// Set tone characteristics. See documentation for the 4 nibbles.
uint16_t value = 0 ; // Value to send to SCI_BASS
int i ; // Loop control
for ( i = 0 ; i < 4 ; i++ )
{
value = ( value << 4 ) | rtone[i] ; // Shift next nibble in
}
write_register ( SCI_BASS, value ) ; // Tone settings
value = read_register ( SCI_BASS ) ; // Read back
dbgprint ( "BASS settings is %04X", value ) ; // Print for TEST
}
uint8_t VS1053::getVolume() // Get the currenet volume setting.
{
return curvol ;
}
void VS1053::startSong()
{
sdi_send_fillers ( 10 ) ;
}
void VS1053::playChunk ( uint8_t* data, size_t len )
{
sdi_send_buffer ( data, len ) ;
}
void VS1053::stopSong()
{
uint16_t modereg ; // Read from mode register
int i ; // Loop control
sdi_send_fillers ( 2052 ) ;
delay ( 10 ) ;
write_register ( SCI_MODE, _BV ( SM_SDINEW ) | _BV ( SM_CANCEL ) ) ;
for ( i = 0 ; i < 200 ; i++ )
{
sdi_send_fillers ( 32 ) ;
modereg = read_register ( SCI_MODE ) ; // Read status
if ( ( modereg & _BV ( SM_CANCEL ) ) == 0 )
{
sdi_send_fillers ( 2052 ) ;
dbgprint ( "Song stopped correctly after %d msec", i * 10 ) ;
return ;
}
delay ( 10 ) ;
}
printDetails ( "Song stopped incorrectly!" ) ;
}
void VS1053::softReset()
{
write_register ( SCI_MODE, _BV ( SM_SDINEW ) | _BV ( SM_RESET ) ) ;
delay ( 10 ) ;
await_data_request() ;
}
void VS1053::printDetails ( const char *header )
{
uint16_t regbuf[16] ;
uint8_t i ;
dbgprint ( header ) ;
dbgprint ( "REG Contents" ) ;
dbgprint ( "--- -----" ) ;
for ( i = 0 ; i <= SCI_num_registers ; i++ )
{
regbuf[i] = read_register ( i ) ;
}
for ( i = 0 ; i <= SCI_num_registers ; i++ )
{
delay ( 5 ) ;
dbgprint ( "%3X - %5X", i, regbuf[i] ) ;
}
}
void VS1053::AdjustRate ( long ppm2 )
{
write_register ( SCI_WRAMADDR, 0x1e07 ) ;
write_register ( SCI_WRAM, ppm2 ) ;
write_register ( SCI_WRAM, ppm2 >> 16 ) ;
// oldClock4KHz = 0 forces adjustment calculation when rate checked.
write_register ( SCI_WRAMADDR, 0x5b1c ) ;
write_register ( SCI_WRAM, 0 ) ;
// Write to AUDATA or CLOCKF checks rate and recalculates adjustment.
write_register ( SCI_AUDATA, read_register ( SCI_AUDATA ) ) ;
}
// The object for the MP3 player
VS1053 vs1053player ( VS1053_CS, VS1053_DCS, VS1053_DREQ ) ;
//******************************************************************************************
// End VS1053 stuff. *
//******************************************************************************************
//******************************************************************************************
// Ringbuffer (fifo) routines. *
//******************************************************************************************
//******************************************************************************************
// R I N G S P A C E *
//******************************************************************************************
inline bool ringspace()
{
#ifdef SPIRAM
return spaceAvailable() ; // True if at least 1 chunk available
#else
return ( rcount < RINGBFSIZ ) ; // True is at least one byte of free space is available
#endif
}
//******************************************************************************************
// R I N G A V A I L *
//******************************************************************************************
inline uint16_t ringavail()
{
#ifdef SPIRAM
return dataAvailable() ; // Return number of chunks filled
#else
return rcount ; // Return number of bytes available
#endif
}
//******************************************************************************************
// P U T R I N G *
//******************************************************************************************
// No check on available space. See ringspace() *
//******************************************************************************************
void putring ( uint8_t b ) // Put one byte in the ringbuffer
{
#ifdef SPIRAM
static uint8_t pwchunk[32] ; // Buffer for one chunk
pwchunk[prcwinx++] = b ; // Store in local chunk
if ( prcwinx == sizeof(pwchunk) ) // Chunk full?
{
bufferWrite ( pwchunk ) ; // Yes, store in SPI RAM
prcwinx = 0 ; // Index to begin of chunk
}
#else
*(ringbuf + rbwindex) = b ; // Put byte in ringbuffer
if ( ++rbwindex == RINGBFSIZ ) // Increment pointer and
{
rbwindex = 0 ; // wrap at end
}
rcount++ ; // Count number of bytes in the
#endif
}
//******************************************************************************************
// G E T R I N G *
//******************************************************************************************
// Assume there is always something in the bufferpace. See ringavail(). *
//******************************************************************************************
uint8_t getring()
{
#ifdef SPIRAM
static uint8_t prchunk[32] ; // Buffer for one chunk
if ( prcrinx >= sizeof(prchunk) ) // End of buffer reached?
{
prcrinx = 0 ; // Yes, reset index to begin of buffer
bufferRead ( prchunk ) ; // And read new buffer
}
return ( prchunk[prcrinx++] ) ;
#else
if ( ++rbrindex == RINGBFSIZ ) // Increment pointer and
{
rbrindex = 0 ; // wrap at end
}
rcount-- ; // Count is now one less
return *(ringbuf + rbrindex) ; // return the oldest byte
#endif
}
//******************************************************************************************
// E M P T Y R I N G *
//******************************************************************************************
void emptyring()
{
rbwindex = 0 ; // Reset ringbuffer administration
rbrindex = RINGBFSIZ - 1 ;
rcount = 0 ;
prcwinx = 0 ;
prcrinx = 32 ; // Set buffer to empty
}
//******************************************************************************************
// U T F 8 A S C I I *
//******************************************************************************************
// UTF8-Decoder: convert UTF8-string to extended ASCII. *
// Convert a single Character from UTF8 to Extended ASCII. *
// Return "0" if a byte has to be ignored. *
//******************************************************************************************
byte utf8ascii ( byte ascii )
{
static const byte lut_C3[] =
{ "AAAAAAACEEEEIIIIDNOOOOO#0UUUU###aaaaaaaceeeeiiiidnooooo##uuuuyyy" } ;
static byte c1 ; // Last character buffer
byte res = 0 ; // Result, default 0
if ( ascii <= 0x7F ) // Standard ASCII-set 0..0x7F handling
{
c1 = 0 ;
res = ascii ; // Return unmodified
}
else
{
switch ( c1 ) // Conversion depending on first UTF8-character
{
case 0xC2: res = '~' ;
break ;
case 0xC3: res = lut_C3[ascii-128] ;
break ;
case 0x82: if ( ascii == 0xAC )
{
res = 'E' ; // Special case Euro-symbol
}
}
c1 = ascii ; // Remember actual character
}
return res ; // Otherwise: return zero, if character has to be ignored
}
//******************************************************************************************
// U T F 8 A S C I I *
//******************************************************************************************
// In Place conversion UTF8-string to Extended ASCII (ASCII is shorter!). *
//******************************************************************************************
void utf8ascii ( char* s )
{
int i, k = 0 ; // Indexes for in en out string
char c ;
for ( i = 0 ; s[i] ; i++ ) // For every input character
{
c = utf8ascii ( s[i] ) ; // Translate if necessary
if ( c ) // Good translation?
{
s[k++] = c ; // Yes, put in output string
}
}
s[k] = 0 ; // Take care of delimeter
}
//******************************************************************************************
// D B G P R I N T *
//******************************************************************************************
// Send a line of info to serial output. Works like vsprintf(), but checks the BEDUg flag.*
// Print only if DEBUG flag is true. Always returns the the formatted string. *
//******************************************************************************************
char* dbgprint ( const char* format, ... )
{
static char sbuf[DEBUG_BUFFER_SIZE] ; // For debug lines
va_list varArgs ; // For variable number of params
va_start ( varArgs, format ) ; // Prepare parameters
vsnprintf ( sbuf, sizeof(sbuf), format, varArgs ) ; // Format the message
va_end ( varArgs ) ; // End of using parameters
if ( DEBUG ) // DEBUG on?
{
Serial.print ( "D: " ) ; // Yes, print prefix
Serial.println ( sbuf ) ; // and the info
}
return sbuf ; // Return stored string
}
//******************************************************************************************
// G E T E N C R Y P T I O N T Y P E *
//******************************************************************************************
// Read the encryption type of the network and return as a 4 byte name *
//*********************4********************************************************************
const char* getEncryptionType ( int thisType )
{
switch (thisType)
{
case ENC_TYPE_WEP:
return "WEP " ;
case ENC_TYPE_TKIP:
return "WPA " ;
case ENC_TYPE_CCMP:
return "WPA2" ;
case ENC_TYPE_NONE:
return "None" ;
case ENC_TYPE_AUTO:
return "Auto" ;
}
return "????" ;
}
//******************************************************************************************
// L I S T N E T W O R K S *
//******************************************************************************************
// List the available networks and select the strongest. *
// Acceptable networks are those who have an entry in "anetworks". *
// SSIDs of available networks will be saved for use in webinterface. *
//******************************************************************************************
void listNetworks()
{
int maxsig = -1000 ; // Used for searching strongest WiFi signal
int newstrength ;
byte encryption ; // TKIP(WPA)=2, WEP=5, CCMP(WPA)=4, NONE=7, AUTO=8
const char* acceptable ; // Netwerk is acceptable for connection
int i ; // Loop control
String sassid ; // Search string in anetworks
ini_block.ssid = String ( "none" ) ; // No selceted network yet
// scan for nearby networks:
dbgprint ( "* Scan Networks *" ) ;
int numSsid = WiFi.scanNetworks() ;
if ( numSsid == -1 )
{
dbgprint ( "Couldn't get a wifi connection" ) ;
return ;
}
// print the list of networks seen:
dbgprint ( "Number of available networks: %d",
numSsid ) ;
// Print the network number and name for each network found and
// find the strongest acceptable network
for ( i = 0 ; i < numSsid ; i++ )
{
acceptable = "" ; // Assume not acceptable
newstrength = WiFi.RSSI ( i ) ; // Get the signal strenght
sassid = WiFi.SSID ( i ) + String ( "|" ) ; // For search string
if ( anetworks.indexOf ( sassid ) >= 0 ) // Is this SSID acceptable?
{
acceptable = "Acceptable" ;
if ( newstrength > maxsig ) // This is a better Wifi
{
maxsig = newstrength ;
ini_block.ssid = WiFi.SSID ( i ) ; // Remember SSID name
}
}
encryption = WiFi.encryptionType ( i ) ;
dbgprint ( "%2d - %-25s Signal: %3d dBm Encryption %4s %s",
i + 1, WiFi.SSID ( i ).c_str(), WiFi.RSSI ( i ),
getEncryptionType ( encryption ),
acceptable ) ;
// Remember this network for later use
networks += WiFi.SSID ( i ) + String ( "|" ) ;
}