Bonsoir Al1fch, bonsoir Henri,
La fonction nextStream ne mets pas à jour le fichier config.json dans l'état actuel du sketch.
J'avais pensé le faire mais est ce que réécrire dans la mémoire SPIFFs à chaque fois que l'on change de station ne va pas la détruire à terme (peut-être est-ce au bout de nombreuses écritures!)?
J'étais en train de lire le tuto de Henri et j'avoue qu'il va me falloir du temps si je veux le mettre en oeuvre. A ce sujet, j'utilise déjà les interruptions pour les rotary encoder, avec : <ESP32Encoder.h>. Pas sur que je puisse en utiliser une autre?
Ci dessous mon sketch qui demande encore à être optimisé et quelque peu mis en ordre mais qui fonctionne en l'état. Je n'ai pas modifié le fichier config.ino ni le webserver.ino
//
// ESP32 WebRadio
//
// Released under GNU General Public License v3.0
//
// Compile with DOIT ESP32 WebKit v1 and burn /data directory into SPIFFS (1M)
//https://github.com/michelep/ESP32_WebRadio
//
//
// Display 160x128
// +-------------------------------------------+ _yHeader=0
// | Header | _hHeader=20px
// +-------------------------------------------+ _yName=20
// | |
// | StationName | _hName=35px
// | |
// +-------------------------------------------+ _yTitle=55
// | |
// | StreamTitle | _hTitle=63px
// | |
// +-------------------------------------------+ _yFooter=116
// | Footer | _hFooter=12px
// +-------------------------------------------+ 128
// 160
// system libraries
#include <WiFi.h>
#include <ESPmDNS.h>
#include <WiFiClient.h>
#include <WiFiUdp.h>
#include <ESPmDNS.h>
#include <ArduinoOTA.h>
#include "time.h"
#include <SPI.h>
#include <Adafruit_GFX.h>
#include <Adafruit_ST7735.h>
#include <Fonts/Org_01.h>
#include "Audio.h"
#include <ESP32Encoder.h>
#include <AsyncTCP.h>
#include <ESPAsyncWebServer.h>
#include <ArduinoJson.h>
#include <FS.h>
#include "SPIFFS.h"
#include "soc/soc.h" //disable brownour problems
#include "soc/rtc_cntl_reg.h" //disable brownour problems
// Digital I/O used
#define I2S_DOUT 26
#define I2S_BCLK 27
#define I2S_LRC 25
#define TFT_DC 2
#define TFT_RST 4 // Or set to -1 and connect to Arduino RESET pin
#define TFT_CS 15
ESP32Encoder encoder;
ESP32Encoder encoder2;
Audio audio;
//global variables
int32_t countVol = encoder.getCount();
int32_t oldCountVol;
int32_t countStreams = encoder2.getCount();
int32_t oldCountStreams;
String streamTitle;
String oldStreamTitle;
boolean f_1sec = false; // flag is set every second
boolean f_1min = false; // flag is set every minute
boolean f_has_ST = false; // has StreamTitle?
String _station = "", _stationname = "";
String _title = "";
uint8_t _commercial_dur = 0; // duration of advertising
static int last; // millis counter
bool streamIsValid = false;
bool streamChanged = true;
bool streamIsPaused = false;
bool streamIsPlaying = false;
bool deviceIsOTA = false;
// display layout
const uint16_t _width = 160; // Display Width
const uint16_t _height = 128; // Display Height
const uint16_t _yHeader = 0; // yPos Header
const uint16_t _hHeader = 20; // height Header
const uint16_t _yName = _yHeader + _hHeader; // yPos StationName
const uint16_t _hName = 35; // height Stationname
const uint16_t _yTitle = _yName + _hName; // yPos StreamTitle
const uint16_t _hTitle = 63; // height StreamTitle
const uint16_t _yFooter = _yTitle + _hTitle; // yPos Footer
const uint16_t _hFooter = 10; // height Footer
const uint16_t _yVolBar = _yFooter; // yPos VolumeBar
const uint16_t _hVolBar = 5; // height VolumeBar
const uint16_t _wLogo = 96; // width Logo
const uint16_t _hLogo = 96; // height Logo
// Color definitions for the TFT screen
// TFT has bits 6 bits (0..5) for RED, 6 bits (6..11) for GREEN and 4 bits (12..15) for BLUE.
#define BLACK ST7735_BLACK
#define BLUE ST7735_BLUE
#define RED ST7735_RED
#define GREEN ST7735_GREEN
#define CYAN GREEN | BLUE
#define MAGENTA RED | BLUE
#define YELLOW RED | GREEN
#define WHITE RED | BLUE | GREEN
//objects
Adafruit_ST7735 tft = Adafruit_ST7735(TFT_CS, TFT_DC, TFT_RST);
AsyncWebServer server(80);
#define MAX_VOLUME 21
#define MIN_VOLUME 0
#define __DEBUG__
// Firmware data
const char BUILD[] = __DATE__ " " __TIME__;
#define FW_NAME "esp32-webradio"
#define FW_VERSION "0.0.6"
// Icons
#define audio_icon_width 5
#define audio_icon_height 10
static const uint8_t PROGMEM audio_icon_bits[] = {
0x10, 0x18, 0x1c, 0x1f, 0x1f, 0x1f, 0x1f, 0x1c, 0x18, 0x10
};
#define wifi_icon_width 8
#define wifi_icon_height 8
static const uint8_t PROGMEM wifi_icon_bits[] = {
0x00, 0x1f, 0x20, 0x4e, 0x50, 0x56, 0x56, 0x40
};
// Format SPIFFS if mount failed
#define FORMAT_SPIFFS_IF_FAILED 1
// Config
struct Config {
// WiFi config
char wifi_essid[24];
// char wifi_password[16];
char wifi_password[24];
// NTP Config
char ntp_server[16];
int8_t ntp_timezone;
// Host config
char hostname[16];
bool ota_enable;
char ota_password[8];
// Radio podcast
int8_t stream_id;
int8_t stream_count;
char stream_url[64];
int8_t volume;
// Display config
int8_t contrast;
};
#define CONFIG_FILE "/config.json"
File configFile;
Config config; // Global config object
// JSON file contains an array of streams URL
#define DB_FILE "/streams.json"
DynamicJsonDocument env(256);
// Esternal procedures definition
bool loadConfigFile();
void initWebServer();
void printStreamsDB();
bool getStreamURL(uint8_t);
// ************************************
// DEBUG_PRINT() and DEBUG_PRINTLN()
//
// send message to Serial
// ************************************
void DEBUG_PRINT(String message) {
#ifdef __DEBUG__
Serial.print(message);
#endif
}
void DEBUG_PRINTLN(String message) {
#ifdef __DEBUG__
Serial.println(message);
#endif
}
//**************************************************************************************************
// T I M E R *
//**************************************************************************************************
void timer1sec() {
static volatile uint8_t sec = 0;
f_1sec = true;
sec++;
//log_i("sec=%i", sec);
if (sec == 60) {
sec = 0;
f_1min = true;
}
}
//**************************************************************************************************
// D I S P L A Y *
//**************************************************************************************************
inline void clearHeader() {
tft.fillRect(0, _yHeader, _width, _hHeader, BLACK); // y 0...19
}
inline void clearStation() {
tft.fillRect(0, _yName, _width, _hName, BLACK); // y 20...119
}
inline void clearTitle() {
tft.fillRect(0, _yTitle, _width, _hTitle, BLACK); // y 120...219
}
inline void clearFooter() {
tft.fillRect(0, _yFooter, _width, _hFooter, BLACK); // y 220...239
}
inline void clearDisplay() {
tft.fillScreen(BLACK); // y 0...239
}
inline uint16_t txtlen(String str) {
uint16_t len = 0;
for (int i = 0; i < str.length(); i++) if (str[i] <= 0xC2) len++;
return len;
}
void display_info(const char *str, int ypos, int height, uint16_t color, uint16_t indent) {
tft.fillRect(0, ypos, tft.width(), height, BLACK); // Clear the space for new info
tft.setTextColor(color); // Set the requested color
tft.setCursor(indent, ypos); // Prepare to show the info
tft.print(str); // Show the string
}
void showStation(String ST) {
tft.drawLine(0, _yName, 160, _yName, YELLOW);
_station = (ST.c_str());
_station = _station.substring(0,25);
//display_info("Station :", _yName, _hName, YELLOW, 0);
//display_info(ST.c_str(), _yName + 15, _hName, CYAN, 0);
display_info(_station.c_str(), _yName + 12, _hName, CYAN, 0);
}
void showStreamTitle(String ST) {
ST.trim(); // remove all leading or trailing whitespaces
ST.replace(" | ", "\n"); // some stations use pipe as \n or
ST.replace("| ", "\n"); // or
ST.replace("|", "\n");
// if(txtlen(ST) > 4) f_has_ST=true; else f_has_ST=false;
String fullStreamTitle = (ST.c_str());
int index = fullStreamTitle.indexOf('-');
String singer = fullStreamTitle.substring(0, index - 1);
singer = singer.substring(0,24);
String titre = fullStreamTitle.substring(index + 2);
//display_info("Singer and Title :", _yTitle, _hTitle, YELLOW, 0);
tft.drawLine(0, _yTitle, 160, _yTitle, YELLOW);
display_info(singer.c_str(), _yTitle + 10, _hTitle, GREEN, 0);
display_info(titre.c_str(), _yTitle + 25, _hTitle, CYAN, 0);
// display_info(ST.c_str(), _yTitle + 15, _hTitle, CYAN, 0);
showVolumeBar();
}
inline void updateTime() {
clearHeader();
tft.setCursor(2, 6);
tft.print("FM");
tft.setCursor(125, 6);
struct tm timeinfo;
if (!getLocalTime(&timeinfo)) {
DEBUG_PRINTLN("[TIME] Failed to obtain time");
} else {
tft.println(&timeinfo, "%H:%M");
}
}
inline void showVolumeBar() {
clearFooter();
tft.drawLine(0, _yVolBar-3, 160, _yVolBar-3, YELLOW);
tft.drawXBitmap(2, _yVolBar, audio_icon_bits, audio_icon_width, audio_icon_height, 0xff);
uint8_t volume = map(config.volume, 0, 22, 0, 72);
tft.drawRect(10, _yVolBar, 72, 10, RED);
tft.fillRect(10, _yVolBar, volume, 10, RED);
}
//#define DISPLAY_BL 27
//#define DISPLAY_BL_DEFAULT 100 // Backlight LEDs PWM duty-cycle
// ************************************
// connectToWifi()
//
// connect to configured WiFi network
// ************************************
bool connectToWifi() {
uint8_t timeout = 0;
if (strlen(config.wifi_essid) > 0) {
DEBUG_PRINT("[INIT] Connecting to " + String(config.wifi_essid) + "...");
WiFi.begin(config.wifi_essid, config.wifi_password);
while ((WiFi.status() != WL_CONNECTED) && (timeout < 10)) {
delay(250);
timeout++;
}
if (WiFi.status() == WL_CONNECTED) {
DEBUG_PRINTLN("CONNECTED. IP:" + WiFi.localIP().toString() + " GW:" + WiFi.gatewayIP().toString());
env["ip"] = WiFi.localIP().toString();
if (MDNS.begin(config.hostname)) {
DEBUG_PRINTLN("[INIT] MDNS responder started: " + String(config.hostname));
// Add service to MDNS-SD
MDNS.addService("http", "tcp", 80);
}
configTime(config.ntp_timezone * 3600, config.ntp_timezone * 3600, config.ntp_server);
return true;
} else {
DEBUG_PRINTLN("[ERROR] Failed to connect to WiFi");
return false;
}
} else {
DEBUG_PRINTLN("[ERROR] Please configure Wifi");
return false;
}
}
//
// high priority audioTask on CORE0
//
void audioTask(void *pvParameters) {
while (1) {
if (!streamIsPaused) {
if (streamChanged) {
playStream(config.stream_id);
streamChanged = false;
}
audio.loop();
streamIsPlaying = audio.isRunning();
}
}
}
//**************************************************************************************************
// S E T U P *
//**************************************************************************************************
void setup() {
Serial.begin(115200);
Serial.setDebugOutput(true);
Serial.println();
Serial.println();
Serial.println();
Serial.print("ESP32 SDK: ");
Serial.println(ESP.getSdkVersion());
Serial.println();
Serial.print(FW_NAME);
Serial.print(" ");
Serial.print(FW_VERSION);
Serial.print(" ");
Serial.println(BUILD);
delay(1000);
ESP32Encoder::useInternalWeakPullResistors = UP;
encoder.attachSingleEdge (35, 34);
encoder2.attachSingleEdge (17, 16);
encoder.setCount(2);
encoder2.setCount(0);
oldCountStreams = -1;
// Initialize SPIFFS
DEBUG_PRINT("[INIT] Initializing SPIFFS...");
if (!SPIFFS.begin()) {
DEBUG_PRINTLN("[ERROR] SPIFFS mount failed. Try formatting...");
if (SPIFFS.format()) {
DEBUG_PRINTLN("[INIT] SPIFFS initialized successfully");
} else {
DEBUG_PRINTLN("[FATAL] SPIFFS fatal error");
ESP.restart();
}
} else {
DEBUG_PRINTLN("OK");
}
// Load configuration
loadConfigFile();
// Initialize DISPLAY
DEBUG_PRINT("[INIT] Initialize display...");
tft.initR(INITR_BLACKTAB); // Init ST7735S chip, black tab
DEBUG_PRINT("[INIT] ST7735 initialised");
//Serial.println("ST7735 initialised");
tft.setRotation(1);
clearHeader();
updateTime();
// Connect to WiFi network
connectToWifi();
// Initialize Web Server
initWebServer();
// Initialize OTA
if (config.ota_enable) {
DEBUG_PRINT("[INIT] Initialize OTA...");
// ArduinoOTA.setPort(3232);
//ArduinoOTA.setHostname(config.hostname);
ArduinoOTA.setHostname("esp32 - webradio");
ArduinoOTA
.onStart([]() {
String type;
if (ArduinoOTA.getCommand() == U_FLASH)
type = "sketch";
else // U_SPIFFS
type = "filesystem";
Serial.println("Start updating " + type);
deviceIsOTA = true;
streamIsPaused = true;
})
.onEnd([]() {
Serial.println("\nEnd");
deviceIsOTA = false;
streamIsPaused = false;
})
.onProgress([](unsigned int progress, unsigned int total) {
Serial.printf("Progress: % u % % \r", (progress / (total / 100)));
clearDisplay();
tft.setCursor(2, 30);
tft.printf("Progress: % u % % \r", (progress / (total / 100)));
})
.onError([](ota_error_t error) {
Serial.printf("Error[ % u]: ", error);
if (error == OTA_AUTH_ERROR) Serial.println("Auth Failed");
else if (error == OTA_BEGIN_ERROR) Serial.println("Begin Failed");
else if (error == OTA_CONNECT_ERROR) Serial.println("Connect Failed");
else if (error == OTA_RECEIVE_ERROR) Serial.println("Receive Failed");
else if (error == OTA_END_ERROR) Serial.println("End Failed");
deviceIsOTA = false;
});
ArduinoOTA.begin();
DEBUG_PRINTLN("OK");
}
//
DEBUG_PRINT("[INIT] Initialize audio...");
env["volume"] = config.volume;
audio.setPinout(I2S_BCLK, I2S_LRC, I2S_DOUT);
audio.setVolume(env["volume"].as<int>());
DEBUG_PRINTLN("OK");
//
printStreamsDB();
// let's fly!
DEBUG_PRINTLN("[INIT] Ready: let's fly!");
env["status"] = "Ready";
// Launch audioTask on CORE0 with high priority
disableCore0WDT(); // Disable watchdog on CORE0
xTaskCreatePinnedToCore(
audioTask, /* Function to implement the task */
"audioTask", /* Name of the task */
10000, /* Stack size in words */
NULL, /* Task input parameter */
15, /* Priority of the task */
NULL, /* Task handle. */
0); /* Core where the task should run */
}
//************************************* End SETUP ***************************************
String zeroPadding(int digit) {
if (digit < 10) {
return String("0" + String(digit));
}
return String(digit);
}
void updateDisplay() {
// Graphic display of 128x160 pixels
tft.fillScreen(ST7735_BLACK);
tft.setTextSize(3);
// If there's an OTA running...
if (deviceIsOTA) {
tft.setCursor(2, 16);
tft.print("Updating.Please wait!");
return;
}
tft.setTextSize(1);
tft.setCursor(2, 6);
tft.print("FM");
tft.setCursor(125, 6);
struct tm timeinfo;
if (!getLocalTime(&timeinfo)) {
DEBUG_PRINTLN("[TIME] Failed to obtain time");
} else {
tft.println(&timeinfo, "%H:%M");
}
/*
// Top red BAR with WiFi signal power
tft.drawXBitmap(0, 0, wifi_icon_bits, wifi_icon_width, wifi_icon_height, 0xff);
tft.fillRect(10, 0, 84, 8, RED);
tft.setTextColor(WHITE, BLACK);
tft.setCursor(100, 0);
tft.println(String(WiFi.RSSI()) + "dB");
*/
if (streamIsPlaying) {
showVolumeBar();
} else {
tft.setCursor(4, 80);
if (streamIsPaused) {
tft.println("*** PAUSE ***");
} else {
tft.println("Loading...");
}
}
}
bool playStream(uint8_t stream_id) {
if (getStreamURL(stream_id)) {
streamIsPlaying = audio.connecttohost(config.stream_url);
updateDisplay();
return true;
}
DEBUG_PRINTLN("[AUDIO] No STREAM URL defined!");
env["status"] = "No stream url defined!";
return false;
}
//**************************************************************************************************
// E V E N T S *
//**************************************************************************************************
void audio_info(const char *info) {
Serial.print("info "); Serial.println(info);
}
void audio_showstation(const char *info) {
_station = info;
showStation(info);
}
void audio_showstreamtitle(const char *info) {
_title = info;
showStreamTitle(info);
}
void audio_commercial(const char *info) { // called from I2S
Serial.print("commercial "); Serial.println(info);
_commercial_dur = atoi(info) / 1000; // info is the duration of advertising in ms
_title = "Advertising " + (String) _commercial_dur + "s";
showStreamTitle(_title);
}
//**************************************************************************************************
// S T R E A M S A C T I O N S *
//**************************************************************************************************
void nextStream() {
//config.stream_id++;
config.stream_id = countStreams;
if (config.stream_id >= config.stream_count) {
config.stream_id = 0;
}
streamChanged = true;
}
void nextStreamWeb() {
config.stream_id++;
if (config.stream_id >= config.stream_count) {
config.stream_id = 0;
}
updateDisplay();
streamChanged = true;
}
void togglePlay() {
streamIsPlaying = audio.pauseResume();
DEBUG_PRINT("[AUDIO] pauseResume(): ");
if (streamIsPlaying) {
DEBUG_PRINTLN("PLAY");
streamIsPaused = false;
env["status"] = "Playing " + config.stream_id;
} else {
DEBUG_PRINTLN("PAUSE");
streamIsPaused = true;
env["status"] = "Pause";
}
}
uint8_t tickCounter = 0;
//**************************************************************************************************
// L O O P *
//**************************************************************************************************
void loop() {
if (config.ota_enable) {
ArduinoOTA.handle();
}
if ((millis() - last) > 1100) {
streamsControl();
if (WiFi.status() != WL_CONNECTED) {
// Not connected? RETRY!
connectToWifi();
}
tickCounter++;
if ((tickCounter % 10) == 0) {
if (!streamIsPlaying) {
playStream(config.stream_id);
}
}
volumeControl();
timer1sec();
if (f_1min == true) {
updateTime();
f_1min = false;
}
last = millis();
}
}
//******************************** FIN LOOP **************************************
void volumeControl() {
countVol = (encoder.getCount());
if (countVol < 1) {
countVol = 1;
encoder.setCount(countVol);
}
if (countVol > 21) {
countVol = 21;
encoder.setCount(countVol);
}
if (countVol != oldCountVol) {
config.volume = countVol;
oldCountVol = countVol;
audio.setVolume(config.volume);
env["volume"] = config.volume;
showVolumeBar();
}
}
void streamsControl() {
countStreams = (encoder2.getCount());
if (countStreams < 0) {
countStreams = config.stream_count - 1;
encoder2.setCount(countStreams);
}
if (countStreams >= config.stream_count) {
countStreams = 0;
encoder2.setCount(countStreams);
}
if (countStreams != oldCountStreams) {
nextStream();
oldCountStreams = countStreams;
updateDisplay();
}
}