Browse Source

Code-reformat + tiny fixes

master
Torsten Stauder 4 years ago
parent
commit
f27d15df59
  1. 503
      src/AudioPlayer.cpp
  2. 46
      src/Battery.cpp
  3. 16
      src/Bluetooth.cpp
  4. 101
      src/Button.cpp
  5. 174
      src/Cmd.cpp
  6. 68
      src/Common.h
  7. 48
      src/Ftp.cpp
  8. 64
      src/HTMLaccesspoint.h
  9. 4
      src/HTMLaccesspoint_DE.h
  10. 4
      src/HTMLaccesspoint_EN.h
  11. 1111
      src/HTMLmanagement.h
  12. 4
      src/HTMLmanagement_DE.h
  13. 4
      src/HTMLmanagement_EN.h
  14. 94
      src/IrReceiver.cpp
  15. 348
      src/Led.cpp
  16. 18
      src/Log.cpp
  17. 199
      src/Mqtt.cpp
  18. 33
      src/Port.cpp
  19. 15
      src/Queues.cpp
  20. 44
      src/RfidCommon.cpp
  21. 29
      src/RfidMfrc522.cpp
  22. 99
      src/RfidPn5180.cpp
  23. 25
      src/RotaryEncoder.cpp
  24. 82
      src/SdCard.cpp
  25. 107
      src/System.cpp
  26. 504
      src/Web.cpp
  27. 81
      src/Wlan.cpp
  28. 57
      src/main.cpp

503
src/AudioPlayer.cpp
File diff suppressed because it is too large
View File

46
src/Battery.cpp

@ -13,69 +13,54 @@ uint8_t voltageCheckInterval = s_voltageCheckInterval;
float voltageIndicatorLow = s_voltageIndicatorLow;
float voltageIndicatorHigh = s_voltageIndicatorHigh;
void Battery_Init()
{
void Battery_Init() {
#ifdef MEASURE_BATTERY_VOLTAGE
// Get voltages from NVS for Neopixel
float vLowIndicator = gPrefsSettings.getFloat("vIndicatorLow", 999.99);
if (vLowIndicator <= 999)
{
if (vLowIndicator <= 999) {
voltageIndicatorLow = vLowIndicator;
snprintf(Log_Buffer, Log_BufferLength, "%s: %.2f V", (char *) FPSTR(voltageIndicatorLowFromNVS), vLowIndicator);
Log_Println(Log_Buffer, LOGLEVEL_INFO);
}
else
{ // preseed if not set
} else { // preseed if not set
gPrefsSettings.putFloat("vIndicatorLow", voltageIndicatorLow);
}
float vHighIndicator = gPrefsSettings.getFloat("vIndicatorHigh", 999.99);
if (vHighIndicator <= 999)
{
if (vHighIndicator <= 999) {
voltageIndicatorHigh = vHighIndicator;
snprintf(Log_Buffer, Log_BufferLength, "%s: %.2f V", (char *) FPSTR(voltageIndicatorHighFromNVS), vHighIndicator);
Log_Println(Log_Buffer, LOGLEVEL_INFO);
}
else
{
} else {
gPrefsSettings.putFloat("vIndicatorHigh", voltageIndicatorHigh);
}
float vLowWarning = gPrefsSettings.getFloat("wLowVoltage", 999.99);
if (vLowWarning <= 999)
{
if (vLowWarning <= 999) {
warningLowVoltage = vLowWarning;
snprintf(Log_Buffer, Log_BufferLength, "%s: %.2f V", (char *) FPSTR(warningLowVoltageFromNVS), vLowWarning);
Log_Println(Log_Buffer, LOGLEVEL_INFO);
}
else
{
} else {
gPrefsSettings.putFloat("wLowVoltage", warningLowVoltage);
}
uint32_t vInterval = gPrefsSettings.getUInt("vCheckIntv", 17777);
if (vInterval != 17777)
{
if (vInterval != 17777) {
voltageCheckInterval = vInterval;
snprintf(Log_Buffer, Log_BufferLength, "%s: %u Minuten", (char *) FPSTR(voltageCheckIntervalFromNVS), vInterval);
Log_Println(Log_Buffer, LOGLEVEL_INFO);
}
else
{
} else {
gPrefsSettings.putUInt("vCheckIntv", voltageCheckInterval);
}
#endif
}
// The average of several analog reads will be taken to reduce the noise (Note: One analog read takes ~10µs)
float Battery_GetVoltage(void)
{
float Battery_GetVoltage(void) {
#ifdef MEASURE_BATTERY_VOLTAGE
float factor = 1 / ((float) rdiv2 / (rdiv2 + rdiv1));
float averagedAnalogValue = 0;
uint8_t i;
for (i = 0; i <= 19; i++)
{
for (i = 0; i <= 19; i++) {
averagedAnalogValue += (float) analogRead(VOLTAGE_READ_PIN);
}
averagedAnalogValue /= 20.0;
@ -84,17 +69,14 @@ float Battery_GetVoltage(void)
}
// Measures voltage of a battery as per interval or after bootup (after allowing a few seconds to settle down)
void Battery_Cyclic(void)
{
void Battery_Cyclic(void) {
#ifdef MEASURE_BATTERY_VOLTAGE
static uint32_t lastVoltageCheckTimestamp = 0;
if ((millis() - lastVoltageCheckTimestamp >= voltageCheckInterval * 60000) || (!lastVoltageCheckTimestamp && millis() >= 10000))
{
if ((millis() - lastVoltageCheckTimestamp >= voltageCheckInterval * 60000) || (!lastVoltageCheckTimestamp && millis() >= 10000)) {
float voltage = Battery_GetVoltage();
if (voltage <= warningLowVoltage)
{
if (voltage <= warningLowVoltage) {
snprintf(Log_Buffer, Log_BufferLength, "%s: (%.2f V)", (char *) FPSTR(voltageTooLow), voltage);
Log_Println(Log_Buffer, LOGLEVEL_ERROR);
Led_Indicate(LedIndicatorType::VoltageWarning);

16
src/Bluetooth.cpp

@ -12,11 +12,9 @@
BluetoothA2DPSink *a2dp_sink;
#endif
void Bluetooth_Init(void)
{
void Bluetooth_Init(void) {
#ifdef BLUETOOTH_ENABLE
if (System_GetOperationMode() == OPMODE_BLUETOOTH)
{
if (System_GetOperationMode() == OPMODE_BLUETOOTH) {
a2dp_sink = new BluetoothA2DPSink();
i2s_pin_config_t pin_config = {
.bck_io_num = I2S_BCLK,
@ -25,21 +23,17 @@ void Bluetooth_Init(void)
.data_in_num = I2S_PIN_NO_CHANGE};
a2dp_sink->set_pin_config(pin_config);
a2dp_sink->start((char *)FPSTR(nameBluetoothDevice));
}
else
{
} else {
esp_bt_mem_release(ESP_BT_MODE_BTDM);
}
#endif
}
void Bluetooth_Cyclic(void)
{
void Bluetooth_Cyclic(void) {
#ifdef BLUETOOTH_ENABLE
esp_a2d_audio_state_t state = a2dp_sink->get_audio_state();
// Reset Sleep Timer when audio is playing
if (state == ESP_A2D_AUDIO_STATE_STARTED)
{
if (state == ESP_A2D_AUDIO_STATE_STARTED) {
System_UpdateActivityTimer();
}
#endif

101
src/Button.cpp

@ -52,11 +52,9 @@ hw_timer_t *Button_Timer = NULL;
#endif
static void IRAM_ATTR onTimer();
static void Button_DoButtonActions(void);
void Button_Init()
{
void Button_Init() {
#if (WAKEUP_BUTTON <= 39)
esp_sleep_enable_ext0_wakeup((gpio_num_t)WAKEUP_BUTTON, 0);
#endif
@ -123,12 +121,9 @@ void Button_Init()
}
// If timer-semaphore is set, read buttons (unless controls are locked)
void Button_Cyclic()
{
if (xSemaphoreTake(Button_TimerSemaphore, 0) == pdTRUE)
{
if (System_AreControlsLocked())
{
void Button_Cyclic() {
if (xSemaphoreTake(Button_TimerSemaphore, 0) == pdTRUE) {
if (System_AreControlsLocked()) {
return;
}
@ -180,108 +175,72 @@ void Button_Cyclic()
// Do corresponding actions for all buttons
void Button_DoButtonActions(void)
{
if (gButtons[0].isPressed && gButtons[1].isPressed)
{
if (gButtons[0].isPressed && gButtons[1].isPressed) {
gButtons[0].isPressed = false;
gButtons[1].isPressed = false;
Cmd_Action(BUTTON_MULTI_01);
}
else if (gButtons[0].isPressed && gButtons[2].isPressed)
{
} else if (gButtons[0].isPressed && gButtons[2].isPressed) {
gButtons[0].isPressed = false;
gButtons[2].isPressed = false;
Cmd_Action(BUTTON_MULTI_02);
}
else if (gButtons[0].isPressed && gButtons[3].isPressed)
{
} else if (gButtons[0].isPressed && gButtons[3].isPressed) {
gButtons[0].isPressed = false;
gButtons[3].isPressed = false;
Cmd_Action(BUTTON_MULTI_03);
}
else if (gButtons[0].isPressed && gButtons[4].isPressed)
{
} else if (gButtons[0].isPressed && gButtons[4].isPressed) {
gButtons[0].isPressed = false;
gButtons[4].isPressed = false;
Cmd_Action(BUTTON_MULTI_04);
}
else if (gButtons[0].isPressed && gButtons[5].isPressed)
{
} else if (gButtons[0].isPressed && gButtons[5].isPressed) {
gButtons[0].isPressed = false;
gButtons[5].isPressed = false;
Cmd_Action(BUTTON_MULTI_05);
}
else if (gButtons[1].isPressed && gButtons[2].isPressed)
{
} else if (gButtons[1].isPressed && gButtons[2].isPressed) {
gButtons[1].isPressed = false;
gButtons[2].isPressed = false;
Cmd_Action(BUTTON_MULTI_12);
}
else if (gButtons[1].isPressed && gButtons[3].isPressed)
{
} else if (gButtons[1].isPressed && gButtons[3].isPressed) {
gButtons[1].isPressed = false;
gButtons[3].isPressed = false;
Cmd_Action(BUTTON_MULTI_13);
}
else if (gButtons[1].isPressed && gButtons[4].isPressed)
{
} else if (gButtons[1].isPressed && gButtons[4].isPressed) {
gButtons[1].isPressed = false;
gButtons[4].isPressed = false;
Cmd_Action(BUTTON_MULTI_14);
}
else if (gButtons[1].isPressed && gButtons[5].isPressed)
{
} else if (gButtons[1].isPressed && gButtons[5].isPressed) {
gButtons[1].isPressed = false;
gButtons[5].isPressed = false;
Cmd_Action(BUTTON_MULTI_15);
}
else if (gButtons[2].isPressed && gButtons[3].isPressed)
{
} else if (gButtons[2].isPressed && gButtons[3].isPressed) {
gButtons[2].isPressed = false;
gButtons[3].isPressed = false;
Cmd_Action(BUTTON_MULTI_23);
}
else if (gButtons[2].isPressed && gButtons[4].isPressed)
{
} else if (gButtons[2].isPressed && gButtons[4].isPressed) {
gButtons[2].isPressed = false;
gButtons[4].isPressed = false;
Cmd_Action(BUTTON_MULTI_24);
}
else if (gButtons[2].isPressed && gButtons[5].isPressed)
{
} else if (gButtons[2].isPressed && gButtons[5].isPressed) {
gButtons[2].isPressed = false;
gButtons[5].isPressed = false;
Cmd_Action(BUTTON_MULTI_25);
}
else if (gButtons[3].isPressed && gButtons[4].isPressed)
{
} else if (gButtons[3].isPressed && gButtons[4].isPressed) {
gButtons[3].isPressed = false;
gButtons[4].isPressed = false;
Cmd_Action(BUTTON_MULTI_34);
}
else if (gButtons[3].isPressed && gButtons[5].isPressed)
{
} else if (gButtons[3].isPressed && gButtons[5].isPressed) {
gButtons[3].isPressed = false;
gButtons[5].isPressed = false;
Cmd_Action(BUTTON_MULTI_35);
}
else if (gButtons[4].isPressed && gButtons[5].isPressed)
{
} else if (gButtons[4].isPressed && gButtons[5].isPressed) {
gButtons[4].isPressed = false;
gButtons[5].isPressed = false;
Cmd_Action(BUTTON_MULTI_45);
}
else
{
for (uint8_t i = 0; i < sizeof(gButtons) / sizeof(gButtons[0]); i++)
{
if (gButtons[i].isPressed)
{
if (gButtons[i].lastReleasedTimestamp > gButtons[i].lastPressedTimestamp)
{
if (gButtons[i].lastReleasedTimestamp - gButtons[i].lastPressedTimestamp >= intervalToLongPress)
{
switch (i) // Long-press-actions
{
} else {
for (uint8_t i = 0; i < sizeof(gButtons) / sizeof(gButtons[0]); i++) {
if (gButtons[i].isPressed) {
if (gButtons[i].lastReleasedTimestamp > gButtons[i].lastPressedTimestamp) {
if (gButtons[i].lastReleasedTimestamp - gButtons[i].lastPressedTimestamp >= intervalToLongPress) {
switch (i) { // Long-press-actions
case 0:
Cmd_Action(BUTTON_0_LONG);
gButtons[i].isPressed = false;
@ -312,11 +271,8 @@ void Button_DoButtonActions(void)
gButtons[i].isPressed = false;
break;
}
}
else
{
switch (i) // Short-press-actions
{
} else {
switch (i) { // Short-press-actions
case 0:
Cmd_Action(BUTTON_0_SHORT);
gButtons[i].isPressed = false;
@ -354,7 +310,6 @@ void Button_DoButtonActions(void)
}
}
void IRAM_ATTR onTimer()
{
void IRAM_ATTR onTimer() {
xSemaphoreGiveFromISR(Button_TimerSemaphore, NULL);
}

174
src/Cmd.cpp

@ -10,18 +10,14 @@
#include "System.h"
#include "Wlan.h"
void Cmd_Action(const uint16_t mod)
{
switch (mod)
{
case LOCK_BUTTONS_MOD:
{ // Locks/unlocks all buttons
void Cmd_Action(const uint16_t mod) {
switch (mod) {
case LOCK_BUTTONS_MOD: { // Locks/unlocks all buttons
System_ToggleLockControls();
break;
}
case SLEEP_TIMER_MOD_15:
{ // Enables/disables sleep after 15 minutes
case SLEEP_TIMER_MOD_15: { // Enables/disables sleep after 15 minutes
System_SetSleepTimer(15u);
gPlayProperties.sleepAfterCurrentTrack = false; // deactivate/overwrite if already active
@ -31,8 +27,7 @@ void Cmd_Action(const uint16_t mod)
break;
}
case SLEEP_TIMER_MOD_30:
{ // Enables/disables sleep after 30 minutes
case SLEEP_TIMER_MOD_30: { // Enables/disables sleep after 30 minutes
System_SetSleepTimer(30u);
gPlayProperties.sleepAfterCurrentTrack = false; // deactivate/overwrite if already active
@ -42,8 +37,7 @@ void Cmd_Action(const uint16_t mod)
break;
}
case SLEEP_TIMER_MOD_60:
{ // Enables/disables sleep after 60 minutes
case SLEEP_TIMER_MOD_60: { // Enables/disables sleep after 60 minutes
System_SetSleepTimer(60u);
gPlayProperties.sleepAfterCurrentTrack = false; // deactivate/overwrite if already active
@ -53,8 +47,7 @@ void Cmd_Action(const uint16_t mod)
break;
}
case SLEEP_TIMER_MOD_120:
{ // Enables/disables sleep after 2 hrs
case SLEEP_TIMER_MOD_120: { // Enables/disables sleep after 2 hrs
System_SetSleepTimer(120u);
gPlayProperties.sleepAfterCurrentTrack = false; // deactivate/overwrite if already active
@ -64,16 +57,13 @@ void Cmd_Action(const uint16_t mod)
break;
}
case SLEEP_AFTER_END_OF_TRACK:
{ // Puts uC to sleep after end of current track
if (gPlayProperties.playMode == NO_PLAYLIST)
{
case SLEEP_AFTER_END_OF_TRACK: { // Puts uC to sleep after end of current track
if (gPlayProperties.playMode == NO_PLAYLIST) {
Log_Println((char *) FPSTR(modificatorNotallowedWhenIdle), LOGLEVEL_NOTICE);
System_IndicateError();
return;
}
if (gPlayProperties.sleepAfterCurrentTrack)
{
if (gPlayProperties.sleepAfterCurrentTrack) {
Log_Println((char *) FPSTR(modificatorSleepAtEOTd), LOGLEVEL_NOTICE);
#ifdef MQTT_ENABLE
publishMqtt((char *) FPSTR(topicSleepTimerState), "0", false);
@ -105,16 +95,13 @@ void Cmd_Action(const uint16_t mod)
break;
}
case SLEEP_AFTER_END_OF_PLAYLIST:
{ // Puts uC to sleep after end of whole playlist (can take a while :->)
if (gPlayProperties.playMode == NO_PLAYLIST)
{
case SLEEP_AFTER_END_OF_PLAYLIST: { // Puts uC to sleep after end of whole playlist (can take a while :->)
if (gPlayProperties.playMode == NO_PLAYLIST) {
Log_Println((char *) FPSTR(modificatorNotallowedWhenIdle), LOGLEVEL_NOTICE);
System_IndicateError();
return;
}
if (gPlayProperties.sleepAfterCurrentTrack)
{
if (gPlayProperties.sleepAfterCurrentTrack) {
#ifdef MQTT_ENABLE
publishMqtt((char *) FPSTR(topicSleepTimerState), "0", false);
#endif
@ -122,9 +109,7 @@ void Cmd_Action(const uint16_t mod)
Led_ResetToInitialBrightness();
#endif
Log_Println((char *) FPSTR(modificatorSleepAtEOPd), LOGLEVEL_NOTICE);
}
else
{
} else {
#ifdef NEOPIXEL_ENABLE
Led_ResetToNightBrightness();
Log_Println((char *) FPSTR(ledsDimmedToNightmode), LOGLEVEL_INFO);
@ -146,10 +131,8 @@ void Cmd_Action(const uint16_t mod)
break;
}
case SLEEP_AFTER_5_TRACKS:
{
if (gPlayProperties.playMode == NO_PLAYLIST)
{
case SLEEP_AFTER_5_TRACKS: {
if (gPlayProperties.playMode == NO_PLAYLIST) {
Log_Println((char *) FPSTR(modificatorNotallowedWhenIdle), LOGLEVEL_NOTICE);
System_IndicateError();
return;
@ -159,8 +142,7 @@ void Cmd_Action(const uint16_t mod)
gPlayProperties.sleepAfterPlaylist = false;
System_DisableSleepTimer();
if (gPlayProperties.playUntilTrackNumber > 0)
{
if (gPlayProperties.playUntilTrackNumber > 0) {
gPlayProperties.playUntilTrackNumber = 0;
#ifdef MQTT_ENABLE
publishMqtt((char *) FPSTR(topicSleepTimerState), "0", false);
@ -169,18 +151,13 @@ void Cmd_Action(const uint16_t mod)
Led_ResetToInitialBrightness();
#endif
Log_Println((char *) FPSTR(modificatorSleepd), LOGLEVEL_NOTICE);
}
else
{
if (gPlayProperties.currentTrackNumber + 5 > gPlayProperties.numberOfTracks)
{ // If currentTrack + 5 exceeds number of tracks in playlist, sleep after end of playlist
} else {
if (gPlayProperties.currentTrackNumber + 5 > gPlayProperties.numberOfTracks) { // If currentTrack + 5 exceeds number of tracks in playlist, sleep after end of playlist
gPlayProperties.sleepAfterPlaylist = true;
#ifdef MQTT_ENABLE
publishMqtt((char *) FPSTR(topicSleepTimerState), "EOP", false);
#endif
}
else
{
} else {
gPlayProperties.playUntilTrackNumber = gPlayProperties.currentTrackNumber + 5;
#ifdef MQTT_ENABLE
publishMqtt((char *) FPSTR(topicSleepTimerState), "EO5T", false);
@ -199,21 +176,14 @@ void Cmd_Action(const uint16_t mod)
break;
}
case REPEAT_PLAYLIST:
{
if (gPlayProperties.playMode == NO_PLAYLIST)
{
case REPEAT_PLAYLIST: {
if (gPlayProperties.playMode == NO_PLAYLIST) {
Log_Println((char *) FPSTR(modificatorNotallowedWhenIdle), LOGLEVEL_NOTICE);
System_IndicateError();
}
else
{
if (gPlayProperties.repeatPlaylist)
{
} else {
if (gPlayProperties.repeatPlaylist) {
Log_Println((char *) FPSTR(modificatorPlaylistLoopDeactive), LOGLEVEL_NOTICE);
}
else
{
} else {
Log_Println((char *) FPSTR(modificatorPlaylistLoopActive), LOGLEVEL_NOTICE);
}
gPlayProperties.repeatPlaylist = !gPlayProperties.repeatPlaylist;
@ -227,21 +197,14 @@ void Cmd_Action(const uint16_t mod)
break;
}
case REPEAT_TRACK:
{ // Introduces looping for track-mode
if (gPlayProperties.playMode == NO_PLAYLIST)
{
case REPEAT_TRACK: { // Introduces looping for track-mode
if (gPlayProperties.playMode == NO_PLAYLIST) {
Log_Println((char *) FPSTR(modificatorNotallowedWhenIdle), LOGLEVEL_NOTICE);
System_IndicateError();
}
else
{
if (gPlayProperties.repeatCurrentTrack)
{
} else {
if (gPlayProperties.repeatCurrentTrack) {
Log_Println((char *) FPSTR(modificatorTrackDeactive), LOGLEVEL_NOTICE);
}
else
{
} else {
Log_Println((char *) FPSTR(modificatorTrackActive), LOGLEVEL_NOTICE);
}
gPlayProperties.repeatCurrentTrack = !gPlayProperties.repeatCurrentTrack;
@ -255,8 +218,7 @@ void Cmd_Action(const uint16_t mod)
break;
}
case DIMM_LEDS_NIGHTMODE:
{
case DIMM_LEDS_NIGHTMODE: {
#ifdef MQTT_ENABLE
publishMqtt((char *) FPSTR(topicLedBrightnessState), Led_GetBrightness(), false);
#endif
@ -268,81 +230,75 @@ void Cmd_Action(const uint16_t mod)
break;
}
case TOGGLE_WIFI_STATUS:
{
case TOGGLE_WIFI_STATUS: {
Wlan_ToggleEnable();
System_IndicateOk();
break;
}
#ifdef BLUETOOTH_ENABLE
case TOGGLE_BLUETOOTH_MODE:
{
if (System_GetOperationModeFromNvs() == OPMODE_NORMAL)
{
case TOGGLE_BLUETOOTH_MODE: {
if (System_GetOperationModeFromNvs() == OPMODE_NORMAL) {
System_IndicateOk();
System_SetOperationMode(OPMODE_BLUETOOTH);
}
else if (System_GetOperationModeFromNvs() == OPMODE_BLUETOOTH)
{
} else if (System_GetOperationModeFromNvs() == OPMODE_BLUETOOTH) {
System_IndicateOk();
System_SetOperationMode(OPMODE_NORMAL);
}
else
{
} else {
System_IndicateError();
}
break;
}
#endif
#ifdef FTP_ENABLE
case ENABLE_FTP_SERVER:
{
case ENABLE_FTP_SERVER: {
Ftp_EnableServer();
break;
}
#endif
case CMD_PLAYPAUSE:
{
case CMD_PLAYPAUSE: {
AudioPlayer_TrackControlToQueueSender(PAUSEPLAY);
break;
}
case CMD_PREVTRACK:
{
case CMD_PREVTRACK: {
AudioPlayer_TrackControlToQueueSender(PREVIOUSTRACK);
break;
}
case CMD_NEXTTRACK:
{
case CMD_NEXTTRACK: {
AudioPlayer_TrackControlToQueueSender(NEXTTRACK);
break;
}
case CMD_FIRSTTRACK:
{
case CMD_FIRSTTRACK: {
AudioPlayer_TrackControlToQueueSender(FIRSTTRACK);
break;
}
case CMD_LASTTRACK:
{
case CMD_LASTTRACK: {
AudioPlayer_TrackControlToQueueSender(LASTTRACK);
break;
}
case CMD_VOLUMEINIT:
{
case CMD_VOLUMEINIT: {
AudioPlayer_VolumeToQueueSender(AudioPlayer_GetInitVolume(), true);
break;
}
case CMD_VOLUMEUP:
{
case CMD_VOLUMEUP: {
AudioPlayer_VolumeToQueueSender(AudioPlayer_GetCurrentVolume() + 1, true);
break;
}
case CMD_VOLUMEDOWN:
{
case CMD_VOLUMEDOWN:{
AudioPlayer_VolumeToQueueSender(AudioPlayer_GetCurrentVolume() - 1, true);
break;
}
case CMD_MEASUREBATTERY:
{
case CMD_MEASUREBATTERY: {
#ifdef MEASURE_BATTERY_VOLTAGE
float voltage = Battery_GetVoltage();
snprintf(Log_Buffer, Log_BufferLength, "%s: %.2f V", (char *) FPSTR(currentVoltageMsg), voltage);
@ -356,23 +312,23 @@ void Cmd_Action(const uint16_t mod)
#endif
break;
}
case CMD_SLEEPMODE:
{
case CMD_SLEEPMODE: {
System_RequestSleep();
break;
}
case CMD_SEEK_FORWARDS:
{
case CMD_SEEK_FORWARDS: {
gPlayProperties.seekmode = SEEK_FORWARDS;
break;
}
case CMD_SEEK_BACKWARDS:
{
case CMD_SEEK_BACKWARDS: {
gPlayProperties.seekmode = SEEK_BACKWARDS;
break;
}
default:
{
default: {
snprintf(Log_Buffer, Log_BufferLength, "%s %d !", (char *) FPSTR(modificatorDoesNotExist), mod);
Log_Println(Log_Buffer, LOGLEVEL_ERROR);
System_IndicateError();

68
src/Common.h

@ -10,30 +10,23 @@ inline bool isNumber(const char *str)
{
byte i = 0;
while (*(str + i) != '\0')
{
if (!isdigit(*(str + i++)))
{
while (*(str + i) != '\0') {
if (!isdigit(*(str + i++))) {
return false;
}
}
if (i > 0)
{
if (i > 0) {
return true;
}
else
{
} else{
return false;
}
}
// Checks if string starts with prefix
// Returns true if so
inline bool startsWith(const char *str, const char *pre)
{
if (strlen(pre) < 1)
{
inline bool startsWith(const char *str, const char *pre) {
if (strlen(pre) < 1) {
return false;
}
@ -42,41 +35,33 @@ inline bool startsWith(const char *str, const char *pre)
// Checks if string ends with suffix
// Returns true if so
inline bool endsWith(const char *str, const char *suf)
{
inline bool endsWith(const char *str, const char *suf) {
const char *a = str + strlen(str);
const char *b = suf + strlen(suf);
while (a != str && b != suf)
{
if (*--a != *--b)
while (a != str && b != suf) {
if (*--a != *--b) {
break;
}
}
return b == suf && *a == *b;
}
inline void convertUtf8ToAscii(String utf8String, char *asciiString)
{
inline void convertUtf8ToAscii(String utf8String, char *asciiString) {
int k = 0;
bool f_C3_seen = false;
for (int i = 0; i < utf8String.length() && k < MAX_FILEPATH_LENTGH - 1; i++)
{
for (int i = 0; i < utf8String.length() && k < MAX_FILEPATH_LENTGH - 1; i++) {
if (utf8String[i] == 195)
{ // C3
if (utf8String[i] == 195) { // C3
f_C3_seen = true;
continue;
}
else
{
if (f_C3_seen == true)
{
} else {
if (f_C3_seen == true) {
f_C3_seen = false;
switch (utf8String[i])
{
switch (utf8String[i]) {
case 0x84:
asciiString[k++] = 0x8e;
break; // Ä
@ -99,11 +84,9 @@ inline void convertUtf8ToAscii(String utf8String, char *asciiString)
asciiString[k++] = 0xe1;
break; // ß
default:
asciiString[k++] = 0xdb; // Unknow...
}
asciiString[k++] = 0xdb; // Unknown...
}
else
{
} else {
asciiString[k++] = utf8String[i];
}
}
@ -112,16 +95,13 @@ inline void convertUtf8ToAscii(String utf8String, char *asciiString)
asciiString[k] = 0;
}
inline void convertAsciiToUtf8(String asciiString, char *utf8String)
{
inline void convertAsciiToUtf8(String asciiString, char *utf8String) {
int k = 0;
for (int i = 0; i < asciiString.length() && k < MAX_FILEPATH_LENTGH - 2; i++)
{
for (int i = 0; i < asciiString.length() && k < MAX_FILEPATH_LENTGH - 2; i++) {
switch (asciiString[i])
{
switch (asciiString[i]) {
case 0x8e:
utf8String[k++] = 0xc3;
utf8String[k++] = 0x84;
@ -159,10 +139,8 @@ inline void convertAsciiToUtf8(String asciiString, char *utf8String)
}
// Release previously allocated memory
inline void freeMultiCharArray(char **arr, const uint32_t cnt)
{
for (uint32_t i = 0; i <= cnt; i++)
{
inline void freeMultiCharArray(char **arr, const uint32_t cnt) {
for (uint32_t i = 0; i <= cnt; i++) {
/*snprintf(Log_Buffer, Log_BufferLength, "%s: %s", (char *) FPSTR(freePtr), *(arr+i));
Log_Println(Log_Buffer, LOGLEVEL_DEBUG);*/
free(*(arr + i));

48
src/Ftp.cpp

@ -25,17 +25,13 @@ bool ftpEnableCurrentStatus = false;
void ftpManager(void);
void Ftp_Init(void)
{
void Ftp_Init(void) {
// Get FTP-user from NVS
String nvsFtpUser = gPrefsSettings.getString("ftpuser", "-1");
if (!nvsFtpUser.compareTo("-1"))
{
if (!nvsFtpUser.compareTo("-1")) {
gPrefsSettings.putString("ftpuser", (String)Ftp_User);
Log_Println((char *) FPSTR(wroteFtpUserToNvs), LOGLEVEL_ERROR);
}
else
{
} else {
strncpy(Ftp_User, nvsFtpUser.c_str(), ftpUserLength);
snprintf(Log_Buffer, Log_BufferLength, "%s: %s", (char *) FPSTR(restoredFtpUserFromNvs), nvsFtpUser.c_str());
Log_Println(Log_Buffer, LOGLEVEL_INFO);
@ -43,62 +39,48 @@ void Ftp_Init(void)
// Get FTP-password from NVS
String nvsFtpPassword = gPrefsSettings.getString("ftppassword", "-1");
if (!nvsFtpPassword.compareTo("-1"))
{
if (!nvsFtpPassword.compareTo("-1")) {
gPrefsSettings.putString("ftppassword", (String)Ftp_Password);
Log_Println((char *) FPSTR(wroteFtpPwdToNvs), LOGLEVEL_ERROR);
}
else
{
} else {
strncpy(Ftp_Password, nvsFtpPassword.c_str(), ftpPasswordLength);
snprintf(Log_Buffer, Log_BufferLength, "%s: %s", (char *) FPSTR(restoredFtpPwdFromNvs), nvsFtpPassword.c_str());
Log_Println(Log_Buffer, LOGLEVEL_INFO);
}
}
void Ftp_Cyclic(void)
{
void Ftp_Cyclic(void) {
#ifdef FTP_ENABLE
ftpManager();
if (WL_CONNECTED == WiFi.status())
{
if (ftpEnableLastStatus && ftpEnableCurrentStatus)
{
if (WL_CONNECTED == WiFi.status()) {
if (ftpEnableLastStatus && ftpEnableCurrentStatus) {
ftpSrv->handleFTP();
}
}
if (ftpEnableLastStatus && ftpEnableCurrentStatus)
{
if (ftpSrv->isConnected())
{
if (ftpEnableLastStatus && ftpEnableCurrentStatus) {
if (ftpSrv->isConnected()) {
System_UpdateActivityTimer(); // Re-adjust timer while client is connected to avoid ESP falling asleep
}
}
#endif
}
void Ftp_EnableServer(void)
{
if (Wlan_IsConnected() && !ftpEnableLastStatus && !ftpEnableCurrentStatus)
{
void Ftp_EnableServer(void) {
if (Wlan_IsConnected() && !ftpEnableLastStatus && !ftpEnableCurrentStatus) {
ftpEnableLastStatus = true;
System_IndicateOk();
}
else
{
} else {
Log_Println((char *) FPSTR(unableToStartFtpServer), LOGLEVEL_ERROR);
System_IndicateError();
}
}
// Creates FTP-instance only when requested
void ftpManager(void)
{
void ftpManager(void) {
#ifdef FTP_ENABLE
if (ftpEnableLastStatus && !ftpEnableCurrentStatus)
{
if (ftpEnableLastStatus && !ftpEnableCurrentStatus) {
snprintf(Log_Buffer, Log_BufferLength, "%s: %u", (char *) FPSTR(freeHeapWithoutFtp), ESP.getFreeHeap());
Log_Println(Log_Buffer, LOGLEVEL_DEBUG);
ftpEnableCurrentStatus = true;

64
src/HTMLaccesspoint.h

@ -0,0 +1,64 @@
static const char accesspoint_HTML[] PROGMEM = "<!DOCTYPE html>\
<html>\
<head>\
<title>WLAN-Einrichtung</title>\
<style>\
input {\
width: 90%%;\
height: 44px;\
border-radius: 4px;\
margin: 10px auto;\
font-size: 15px;\
background: #f1f1f1;\
border: 0;\
padding: 0 15px\
}\
input {\
\
}\
body {\
background: #007bff;\
font-family: sans-serif;\
font-size: 14px;\
color: #777\
}\
.box {\
background: #fff;\
max-width: 258px;\
margin: 75px auto;\
padding: 30px;\
border-radius: 5px;\
text-align: center\
}\
.btn {\
background: #3498db;\
color: #fff;\
cursor: pointer;\
width: 90%%;\
height: 44px;\
border-radius: 4px;\
margin: 10px auto;\
font-size: 15px;\
}\
.rebootmsg {\
display: none;\
}\
</style>\
</head>\
<body>\
<form id=\"settings\" action=\"/init\" class=\"box\" method=\"POST\">\
<h1>WLAN-Einrichtung</h1>\
<label for=\"ssid\">SSID:</label><br>\
<input type=\"text\" id=\"ssid\" name=\"ssid\" placeholder=\"SSID\" required><br>\
<label for=\"pwd\">Passwort:</label><br>\
<input type=\"password\" id=\"pwd\" name=\"pwd\" autocomplete=\"off\" required><br>\
<label for=\"hostname\">ESPuino-Name (Hostname):</label><br>\
<input type=\"text\" id=\"hostname\" name=\"hostname\" placeholder=\"espuino\" required><br><br>\
<input class=\"btn\" type=\"submit\" id=\"save-button\" value=\"Save\">\
</form>\
<form action=\"/restart\" class=\"box\">\
<h1>Fertig?</h1>\
<input class=\"btn\" type=\"submit\" id=\"restart-button\" value=\"Reboot\">\
</form>\
</body>\
</html>";

4
src/HTMLaccesspoint_DE.h

@ -1,5 +1,3 @@
#if (LANGUAGE == 1)
static const char accesspoint_HTML[] PROGMEM = "<!DOCTYPE html>\
<html>\
<head>\
@ -64,5 +62,3 @@ static const char accesspoint_HTML[] PROGMEM = "<!DOCTYPE html>\
</form>\
</body>\
</html>";
#endif

4
src/HTMLaccesspoint_EN.h

@ -1,5 +1,3 @@
#if (LANGUAGE == 2)
static const char accesspoint_HTML[] PROGMEM = "<!DOCTYPE html>\
<html>\
<head>\
@ -64,5 +62,3 @@ static const char accesspoint_HTML[] PROGMEM = "<!DOCTYPE html>\
</form>\
</body>\
</html>";
#endif

1111
src/HTMLmanagement.h
File diff suppressed because it is too large
View File

4
src/HTMLmanagement_DE.h

@ -1,5 +1,3 @@
#if (LANGUAGE == 1)
static const char management_HTML[] PROGMEM = "<!DOCTYPE html>\
<html lang=\"de\">\
<head>\
@ -1111,5 +1109,3 @@ static const char management_HTML[] PROGMEM = "<!DOCTYPE html>\
</script>\
</body>\
</html>";
#endif

4
src/HTMLmanagement_EN.h

@ -1,5 +1,3 @@
#if (LANGUAGE == 2)
static const char management_HTML[] PROGMEM = "<!DOCTYPE html>\
<html lang=\"de\">\
<head>\
@ -1111,5 +1109,3 @@ static const char management_HTML[] PROGMEM = "<!DOCTYPE html>\
</script>\
</body>\
</html>";
#endif

94
src/IrReceiver.cpp

@ -15,99 +15,77 @@
uint32_t IrReceiver_LastRcCmdTimestamp = 0u;
#endif
void IrReceiver_Init()
{
void IrReceiver_Init() {
#ifdef IR_CONTROL_ENABLE
IrReceiver.begin(IRLED_PIN);
#endif
}
void IrReceiver_Cyclic()
{
void IrReceiver_Cyclic() {
#ifdef IR_CONTROL_ENABLE
static uint8_t lastVolume = 0;
if (IrReceiver.decode())
{
if (IrReceiver.decode()){
// Print a short summary of received data
IrReceiver.printIRResultShort(&Serial);
Serial.println();
IrReceiver.resume(); // Enable receiving of the next value
bool rcActionOk = false;
if (millis() - IrReceiver_LastRcCmdTimestamp >= IR_DEBOUNCE)
{
if (millis() - IrReceiver_LastRcCmdTimestamp >= IR_DEBOUNCE) {
rcActionOk = true; // not used for volume up/down
IrReceiver_LastRcCmdTimestamp = millis();
}
switch (IrReceiver.decodedIRData.command)
{
case RC_PLAY:
{
if (rcActionOk)
{
switch (IrReceiver.decodedIRData.command) {
case RC_PLAY: {
if (rcActionOk) {
Cmd_Action(CMD_PLAYPAUSE);
Serial.println(F("RC: Play"));
}
break;
}
case RC_PAUSE:
{
if (rcActionOk)
{
case RC_PAUSE: {
if (rcActionOk) {
Cmd_Action(CMD_PLAYPAUSE);
Serial.println(F("RC: Pause"));
}
break;
}
case RC_NEXT:
{
if (rcActionOk)
{
case RC_NEXT: {
if (rcActionOk) {
Cmd_Action(CMD_NEXTTRACK);
Serial.println(F("RC: Next"));
}
break;
}
case RC_PREVIOUS:
{
if (rcActionOk)
{
case RC_PREVIOUS: {
if (rcActionOk) {
Cmd_Action(CMD_PREVTRACK);
Serial.println(F("RC: Previous"));
}
break;
}
case RC_FIRST:
{
if (rcActionOk)
{
case RC_FIRST: {
if (rcActionOk) {
Cmd_Action(CMD_FIRSTTRACK);
Serial.println(F("RC: First"));
}
break;
}
case RC_LAST:
{
if (rcActionOk)
{
case RC_LAST: {
if (rcActionOk) {
Cmd_Action(CMD_LASTTRACK);
Serial.println(F("RC: Last"));
}
break;
}
case RC_MUTE:
{
if (rcActionOk)
{
if (AudioPlayer_GetCurrentVolume() > 0)
{
case RC_MUTE: {
if (rcActionOk) {
if (AudioPlayer_GetCurrentVolume() > 0) {
lastVolume = AudioPlayer_GetCurrentVolume();
AudioPlayer_SetCurrentVolume(0u);
}
else
{
} else {
AudioPlayer_SetCurrentVolume(lastVolume); // Remember last volume if mute is pressed again
}
@ -117,49 +95,39 @@ void IrReceiver_Cyclic()
}
break;
}
case RC_BLUETOOTH:
{
if (rcActionOk)
{
case RC_BLUETOOTH: {
if (rcActionOk) {
Cmd_Action(TOGGLE_BLUETOOTH_MODE);
Serial.println(F("RC: Bluetooth"));
}
break;
}
case RC_FTP:
{
if (rcActionOk)
{
case RC_FTP: {
if (rcActionOk) {
Cmd_Action(ENABLE_FTP_SERVER);
Serial.println(F("RC: FTP"));
}
break;
}
case RC_SHUTDOWN:
{
if (rcActionOk)
{
case RC_SHUTDOWN: {
if (rcActionOk) {
System_RequestSleep();
Serial.println(F("RC: Shutdown"));
}
break;
}
case RC_VOL_DOWN:
{
case RC_VOL_DOWN: {
Cmd_Action(CMD_VOLUMEDOWN);
Serial.println(F("RC: Volume down"));
break;
}
case RC_VOL_UP:
{
case RC_VOL_UP: {
Cmd_Action(CMD_VOLUMEUP);
Serial.println(F("RC: Volume up"));
break;
}
default:
{
if (rcActionOk)
{
default: {
if (rcActionOk) {
Serial.println(F("RC: unknown"));
}
}

348
src/Led.cpp

@ -33,38 +33,30 @@ static uint8_t Led_NightBrightness = LED_INITIAL_NIGHT_BRIGHTNESS;
static void Led_Task(void *parameter);
static uint8_t Led_Address(uint8_t number);
#endif
void Led_Init(void)
{
void Led_Init(void) {
#ifdef NEOPIXEL_ENABLE
// Get some stuff from NVS...
// Get initial LED-brightness from NVS
uint8_t nvsILedBrightness = gPrefsSettings.getUChar("iLedBrightness", 0);
if (nvsILedBrightness)
{
if (nvsILedBrightness) {
Led_InitialBrightness = nvsILedBrightness;
Led_Brightness = nvsILedBrightness;
snprintf(Log_Buffer, Log_BufferLength, "%s: %d", (char *) FPSTR(initialBrightnessfromNvs), nvsILedBrightness);
Log_Println(Log_Buffer, LOGLEVEL_INFO);
}
else
{
} else {
gPrefsSettings.putUChar("iLedBrightness", Led_InitialBrightness);
Log_Println((char *) FPSTR(wroteInitialBrightnessToNvs), LOGLEVEL_ERROR);
}
// Get night LED-brightness from NVS
uint8_t nvsNLedBrightness = gPrefsSettings.getUChar("nLedBrightness", 0);
if (nvsNLedBrightness)
{
if (nvsNLedBrightness) {
Led_NightBrightness = nvsNLedBrightness;
snprintf(Log_Buffer, Log_BufferLength, "%s: %d", (char *) FPSTR(restoredInitialBrightnessForNmFromNvs), nvsNLedBrightness);
Log_Println(Log_Buffer, LOGLEVEL_INFO);
}
else
{
} else {
gPrefsSettings.putUChar("nLedBrightness", Led_NightBrightness);
Log_Println((char *) FPSTR(wroteNmBrightnessToNvs), LOGLEVEL_ERROR);
}
@ -81,45 +73,39 @@ void Led_Init(void)
#endif
}
void Led_Exit(void)
{
void Led_Exit(void) {
#ifdef NEOPIXEL_ENABLE
FastLED.clear();
FastLED.show();
#endif
}
void Led_Indicate(LedIndicatorType value)
{
void Led_Indicate(LedIndicatorType value) {
#ifdef NEOPIXEL_ENABLE
LED_INDICATOR_SET(value);
#endif
}
void Led_SetPause(boolean value)
{
void Led_SetPause(boolean value) {
#ifdef NEOPIXEL_ENABLE
Led_Pause = value;
#endif
}
void Led_ResetToInitialBrightness(void)
{
void Led_ResetToInitialBrightness(void) {
#ifdef NEOPIXEL_ENABLE
Led_Brightness = Led_InitialBrightness;
#endif
}
void Led_ResetToNightBrightness(void)
{
void Led_ResetToNightBrightness(void) {
#ifdef NEOPIXEL_ENABLE
Led_Brightness = Led_NightBrightness;
Log_Println((char *) FPSTR(ledsDimmedToNightmode), LOGLEVEL_INFO);
#endif
}
uint8_t Led_GetBrightness(void)
{
uint8_t Led_GetBrightness(void) {
#ifdef NEOPIXEL_ENABLE
return Led_Brightness;
#else
@ -127,16 +113,14 @@ uint8_t Led_GetBrightness(void)
#endif
}
void Led_SetBrightness(uint8_t value)
{
void Led_SetBrightness(uint8_t value) {
#ifdef NEOPIXEL_ENABLE
Led_Brightness = value;
#endif
}
// Switches Neopixel-addressing from clockwise to counter clockwise (and vice versa)
uint8_t Led_Address(uint8_t number)
{
uint8_t Led_Address(uint8_t number) {
#ifdef NEOPIXEL_REVERSE_ROTATION
return NUM_LEDS - 1 - number;
#else
@ -144,8 +128,7 @@ uint8_t Led_Address(uint8_t number)
#endif
}
static void Led_Task(void *parameter)
{
static void Led_Task(void *parameter) {
#ifdef NEOPIXEL_ENABLE
static uint8_t hlastVolume = AudioPlayer_GetCurrentVolume();
static uint8_t lastPos = gPlayProperties.currentRelPos;
@ -167,17 +150,13 @@ static void Led_Task(void *parameter)
FastLED.addLeds<CHIPSET, LED_PIN, COLOR_ORDER>(leds, NUM_LEDS).setCorrection(TypicalSMD5050);
FastLED.setBrightness(Led_Brightness);
for (;;)
{
if (Led_Pause)
{ // Workaround to prevent exceptions while NVS-writes take place
for (;;) {
if (Led_Pause) { // Workaround to prevent exceptions while NVS-writes take place
vTaskDelay(portTICK_RATE_MS * 10);
continue;
}
if (System_IsSleepRequested())
{ // If deepsleep is planned, turn off LEDs first in order to avoid LEDs still glowing when ESP32 is in deepsleep
if (!turnedOffLeds)
{
if (System_IsSleepRequested()) { // If deepsleep is planned, turn off LEDs first in order to avoid LEDs still glowing when ESP32 is in deepsleep
if (!turnedOffLeds) {
FastLED.clear(true);
turnedOffLeds = true;
}
@ -185,35 +164,22 @@ static void Led_Task(void *parameter)
vTaskDelay(portTICK_RATE_MS * 10);
continue;
}
if (!LED_INDICATOR_IS_SET(LedIndicatorType::BootComplete))
{ // Rotates orange unless boot isn't complete
if (!LED_INDICATOR_IS_SET(LedIndicatorType::BootComplete)) { // Rotates orange unless boot isn't complete
FastLED.clear();
for (uint8_t led = 0; led < NUM_LEDS; led++)
{
if (showEvenError)
{
if (Led_Address(led) % 2 == 0)
{
if (millis() <= 10000)
{
for (uint8_t led = 0; led < NUM_LEDS; led++) {
if (showEvenError) {
if (Led_Address(led) % 2 == 0) {
if (millis() <= 10000) {
leds[Led_Address(led)] = CRGB::Orange;
}
else
{
} else {
leds[Led_Address(led)] = CRGB::Red;
}
}
}
else
{
if (millis() >= 10000)
{ // Flashes red after 10s (will remain forever if SD cannot be mounted)
} else {
if (millis() >= 10000) { // Flashes red after 10s (will remain forever if SD cannot be mounted)
leds[Led_Address(led)] = CRGB::Red;
}
else
{
if (Led_Address(led) % 2 == 1)
{
} else {
if (Led_Address(led) % 2 == 1) {
leds[Led_Address(led)] = CRGB::Orange;
}
}
@ -226,23 +192,18 @@ static void Led_Task(void *parameter)
continue;
}
if (lastLedBrightness != Led_Brightness)
{
if (lastLedBrightness != Led_Brightness) {
FastLED.setBrightness(Led_Brightness);
lastLedBrightness = Led_Brightness;
}
// LEDs growing red as long button for sleepmode is pressed.
if (gShutdownButton < (sizeof(gButtons) / sizeof(gButtons[0])) - 1)
{ // Only show animation, if CMD_SLEEPMODE was assigned to BUTTON_n_LONG + button is pressed
if (!gButtons[gShutdownButton].currentState)
{
if (gShutdownButton < (sizeof(gButtons) / sizeof(gButtons[0])) - 1) { // Only show animation, if CMD_SLEEPMODE was assigned to BUTTON_n_LONG + button is pressed
if (!gButtons[gShutdownButton].currentState) {
FastLED.clear();
for (uint8_t led = 0; led < NUM_LEDS; led++)
{
for (uint8_t led = 0; led < NUM_LEDS; led++) {
leds[Led_Address(led)] = CRGB::Red;
if (gButtons[gShutdownButton].currentState)
{
if (gButtons[gShutdownButton].currentState) {
FastLED.show();
delay(5);
break;
@ -251,38 +212,31 @@ static void Led_Task(void *parameter)
vTaskDelay(intervalToLongPress / NUM_LEDS * portTICK_RATE_MS);
}
}
}
else
{
} else {
gShutdownButton = (sizeof(gButtons) / sizeof(gButtons[0])) - 1; // If CMD_SLEEPMODE was not assigned to an enabled button, dummy-button is used
if (!gButtons[gShutdownButton].currentState)
{
if (!gButtons[gShutdownButton].currentState) {
gButtons[gShutdownButton].currentState = true;
}
}
if (LED_INDICATOR_IS_SET(LedIndicatorType::Error))
{ // If error occured (e.g. RFID-modification not accepted)
if (LED_INDICATOR_IS_SET(LedIndicatorType::Error)) { // If error occured (e.g. RFID-modification not accepted)
LED_INDICATOR_CLEAR(LedIndicatorType::Error);
notificationShown = true;
FastLED.clear();
for (uint8_t led = 0; led < NUM_LEDS; led++)
{
for (uint8_t led = 0; led < NUM_LEDS; led++) {
leds[Led_Address(led)] = CRGB::Red;
}
FastLED.show();
vTaskDelay(portTICK_RATE_MS * 200);
}
if (LED_INDICATOR_IS_SET(LedIndicatorType::Ok))
{ // If action was accepted
if (LED_INDICATOR_IS_SET(LedIndicatorType::Ok)) { // If action was accepted
LED_INDICATOR_CLEAR(LedIndicatorType::Ok);
notificationShown = true;
FastLED.clear();
for (uint8_t led = 0; led < NUM_LEDS; led++)
{
for (uint8_t led = 0; led < NUM_LEDS; led++) {
leds[Led_Address(led)] = CRGB::Green;
}
FastLED.show();
@ -290,24 +244,20 @@ static void Led_Task(void *parameter)
}
#ifdef MEASURE_BATTERY_VOLTAGE
if (LED_INDICATOR_IS_SET(LedIndicatorType::VoltageWarning))
{ // Flashes red three times if battery-voltage is low
if (LED_INDICATOR_IS_SET(LedIndicatorType::VoltageWarning)) { // Flashes red three times if battery-voltage is low
LED_INDICATOR_CLEAR(LedIndicatorType::VoltageWarning);
notificationShown = true;
for (uint8_t i = 0; i < 3; i++)
{
for (uint8_t i = 0; i < 3; i++) {
FastLED.clear();
for (uint8_t led = 0; led < NUM_LEDS; led++)
{
for (uint8_t led = 0; led < NUM_LEDS; led++) {
leds[Led_Address(led)] = CRGB::Red;
}
FastLED.show();
vTaskDelay(portTICK_RATE_MS * 200);
FastLED.clear();
for (uint8_t led = 0; led < NUM_LEDS; led++)
{
for (uint8_t led = 0; led < NUM_LEDS; led++) {
leds[Led_Address(led)] = CRGB::Black;
}
FastLED.show();
@ -315,44 +265,32 @@ static void Led_Task(void *parameter)
}
}
if (LED_INDICATOR_IS_SET(LedIndicatorType::Voltage))
{
if (LED_INDICATOR_IS_SET(LedIndicatorType::Voltage)) {
LED_INDICATOR_CLEAR(LedIndicatorType::Voltage);
float currentVoltage = Battery_GetVoltage();
float vDiffIndicatorRange = voltageIndicatorHigh - voltageIndicatorLow;
float vDiffCurrent = currentVoltage - voltageIndicatorLow;
if (vDiffCurrent < 0)
{ // If voltage is too low or no battery is connected
if (vDiffCurrent < 0) { // If voltage is too low or no battery is connected
LED_INDICATOR_SET(LedIndicatorType::Error);
break;
}
else
{
} else {
uint8_t numLedsToLight = ((float)vDiffCurrent / vDiffIndicatorRange) * NUM_LEDS;
FastLED.clear();
for (uint8_t led = 0; led < numLedsToLight; led++)
{
if (((float)numLedsToLight / NUM_LEDS) >= 0.6)
{
for (uint8_t led = 0; led < numLedsToLight; led++) {
if (((float)numLedsToLight / NUM_LEDS) >= 0.6) {
leds[Led_Address(led)] = CRGB::Green;
}
else if (((float)numLedsToLight / NUM_LEDS) <= 0.6 && ((float)numLedsToLight / NUM_LEDS) >= 0.3)
{
} else if (((float)numLedsToLight / NUM_LEDS) <= 0.6 && ((float)numLedsToLight / NUM_LEDS) >= 0.3) {
leds[Led_Address(led)] = CRGB::Orange;
}
else
{
} else {
leds[Led_Address(led)] = CRGB::Red;
}
FastLED.show();
vTaskDelay(portTICK_RATE_MS * 20);
}
for (uint8_t i = 0; i <= 100; i++)
{
if (hlastVolume != AudioPlayer_GetCurrentVolume() || LED_INDICATOR_IS_SET(LedIndicatorType::Error) || LED_INDICATOR_IS_SET(LedIndicatorType::Ok) || !gButtons[gShutdownButton].currentState || System_IsSleepRequested())
{
for (uint8_t i = 0; i <= 100; i++) {
if (hlastVolume != AudioPlayer_GetCurrentVolume() || LED_INDICATOR_IS_SET(LedIndicatorType::Error) || LED_INDICATOR_IS_SET(LedIndicatorType::Ok) || !gButtons[gShutdownButton].currentState || System_IsSleepRequested()) {
break;
}
@ -362,25 +300,20 @@ static void Led_Task(void *parameter)
}
#endif
if (hlastVolume != AudioPlayer_GetCurrentVolume())
{ // If volume has been changed
if (hlastVolume != AudioPlayer_GetCurrentVolume()) { // If volume has been changed
uint8_t numLedsToLight = map(AudioPlayer_GetCurrentVolume(), 0, AudioPlayer_GetMaxVolume(), 0, NUM_LEDS);
hlastVolume = AudioPlayer_GetCurrentVolume();
volumeChangeShown = true;
FastLED.clear();
for (int led = 0; led < numLedsToLight; led++)
{ // (Inverse) color-gradient from green (85) back to (still) red (245) using unsigned-cast
for (int led = 0; led < numLedsToLight; led++) { // (Inverse) color-gradient from green (85) back to (still) red (245) using unsigned-cast
leds[Led_Address(led)].setHue((uint8_t)(85 - ((double)95 / NUM_LEDS) * led));
}
FastLED.show();
for (uint8_t i = 0; i <= 50; i++)
{
if (hlastVolume != AudioPlayer_GetCurrentVolume() || LED_INDICATOR_IS_SET(LedIndicatorType::Error) || LED_INDICATOR_IS_SET(LedIndicatorType::Ok) || !gButtons[gShutdownButton].currentState || System_IsSleepRequested())
{
if (hlastVolume != AudioPlayer_GetCurrentVolume())
{
for (uint8_t i = 0; i <= 50; i++) {
if (hlastVolume != AudioPlayer_GetCurrentVolume() || LED_INDICATOR_IS_SET(LedIndicatorType::Error) || LED_INDICATOR_IS_SET(LedIndicatorType::Ok) || !gButtons[gShutdownButton].currentState || System_IsSleepRequested()) {
if (hlastVolume != AudioPlayer_GetCurrentVolume()) {
volumeChangeShown = false;
}
break;
@ -390,139 +323,101 @@ static void Led_Task(void *parameter)
}
}
if (LED_INDICATOR_IS_SET(LedIndicatorType::Rewind))
{
if (LED_INDICATOR_IS_SET(LedIndicatorType::Rewind)) {
LED_INDICATOR_CLEAR(LedIndicatorType::Rewind);
for (uint8_t i = NUM_LEDS - 1; i > 0; i--)
{
for (uint8_t i = NUM_LEDS - 1; i > 0; i--) {
leds[Led_Address(i)] = CRGB::Black;
FastLED.show();
if (hlastVolume != AudioPlayer_GetCurrentVolume() || lastLedBrightness != Led_Brightness || LED_INDICATOR_IS_SET(LedIndicatorType::Error) || LED_INDICATOR_IS_SET(LedIndicatorType::Ok) || !gButtons[gShutdownButton].currentState || System_IsSleepRequested())
{
if (hlastVolume != AudioPlayer_GetCurrentVolume() || lastLedBrightness != Led_Brightness || LED_INDICATOR_IS_SET(LedIndicatorType::Error) || LED_INDICATOR_IS_SET(LedIndicatorType::Ok) || !gButtons[gShutdownButton].currentState || System_IsSleepRequested()) {
break;
}
else
{
} else {
vTaskDelay(portTICK_RATE_MS * 30);
}
}
}
if (LED_INDICATOR_IS_SET(LedIndicatorType::PlaylistProgress))
{
if (LED_INDICATOR_IS_SET(LedIndicatorType::PlaylistProgress)) {
LED_INDICATOR_CLEAR(LedIndicatorType::PlaylistProgress);
if (gPlayProperties.numberOfTracks > 1 && gPlayProperties.currentTrackNumber < gPlayProperties.numberOfTracks)
{
if (gPlayProperties.numberOfTracks > 1 && gPlayProperties.currentTrackNumber < gPlayProperties.numberOfTracks) {
uint8_t numLedsToLight = map(gPlayProperties.currentTrackNumber, 0, gPlayProperties.numberOfTracks - 1, 0, NUM_LEDS);
FastLED.clear();
for (uint8_t i = 0; i < numLedsToLight; i++)
{
for (uint8_t i = 0; i < numLedsToLight; i++) {
leds[Led_Address(i)] = CRGB::Blue;
FastLED.show();
#ifdef MEASURE_BATTERY_VOLTAGE
if (hlastVolume != AudioPlayer_GetCurrentVolume() || lastLedBrightness != Led_Brightness || LED_INDICATOR_IS_SET(LedIndicatorType::Error) || LED_INDICATOR_IS_SET(LedIndicatorType::Ok) || LED_INDICATOR_IS_SET(LedIndicatorType::VoltageWarning) || LED_INDICATOR_IS_SET(LedIndicatorType::Voltage) || !gButtons[gShutdownButton].currentState || System_IsSleepRequested())
{
if (hlastVolume != AudioPlayer_GetCurrentVolume() || lastLedBrightness != Led_Brightness || LED_INDICATOR_IS_SET(LedIndicatorType::Error) || LED_INDICATOR_IS_SET(LedIndicatorType::Ok) || LED_INDICATOR_IS_SET(LedIndicatorType::VoltageWarning) || LED_INDICATOR_IS_SET(LedIndicatorType::Voltage) || !gButtons[gShutdownButton].currentState || System_IsSleepRequested()) {
#else
if (hlastVolume != AudioPlayer_GetCurrentVolume() || lastLedBrightness != Led_Brightness || LED_INDICATOR_IS_SET(LedIndicatorType::Error) || LED_INDICATOR_IS_SET(LedIndicatorType::Ok) || !gButtons[gShutdownButton].currentState || System_IsSleepRequested())
{
if (hlastVolume != AudioPlayer_GetCurrentVolume() || lastLedBrightness != Led_Brightness || LED_INDICATOR_IS_SET(LedIndicatorType::Error) || LED_INDICATOR_IS_SET(LedIndicatorType::Ok) || !gButtons[gShutdownButton].currentState || System_IsSleepRequested()) {
#endif
break;
}
else
{
} else {
vTaskDelay(portTICK_RATE_MS * 30);
}
}
for (uint8_t i = 0; i <= 100; i++)
{
for (uint8_t i = 0; i <= 100; i++) {
#ifdef MEASURE_BATTERY_VOLTAGE
if (hlastVolume != AudioPlayer_GetCurrentVolume() || lastLedBrightness != Led_Brightness || LED_INDICATOR_IS_SET(LedIndicatorType::Error) || LED_INDICATOR_IS_SET(LedIndicatorType::Ok) || LED_INDICATOR_IS_SET(LedIndicatorType::VoltageWarning) || LED_INDICATOR_IS_SET(LedIndicatorType::Voltage) || !gButtons[gShutdownButton].currentState || System_IsSleepRequested())
{
if (hlastVolume != AudioPlayer_GetCurrentVolume() || lastLedBrightness != Led_Brightness || LED_INDICATOR_IS_SET(LedIndicatorType::Error) || LED_INDICATOR_IS_SET(LedIndicatorType::Ok) || LED_INDICATOR_IS_SET(LedIndicatorType::VoltageWarning) || LED_INDICATOR_IS_SET(LedIndicatorType::Voltage) || !gButtons[gShutdownButton].currentState || System_IsSleepRequested()) {
#else
if (hlastVolume != AudioPlayer_GetCurrentVolume() || lastLedBrightness != Led_Brightness || LED_INDICATOR_IS_SET(LedIndicatorType::Error) || LED_INDICATOR_IS_SET(LedIndicatorType::Ok) || !gButtons[gShutdownButton].currentState || System_IsSleepRequested())
{
if (hlastVolume != AudioPlayer_GetCurrentVolume() || lastLedBrightness != Led_Brightness || LED_INDICATOR_IS_SET(LedIndicatorType::Error) || LED_INDICATOR_IS_SET(LedIndicatorType::Ok) || !gButtons[gShutdownButton].currentState || System_IsSleepRequested()) {
#endif
break;
}
else
{
} else {
vTaskDelay(portTICK_RATE_MS * 15);
}
}
for (uint8_t i = numLedsToLight; i > 0; i--)
{
for (uint8_t i = numLedsToLight; i > 0; i--) {
leds[Led_Address(i) - 1] = CRGB::Black;
FastLED.show();
#ifdef MEASURE_BATTERY_VOLTAGE
if (hlastVolume != AudioPlayer_GetCurrentVolume() || lastLedBrightness != Led_Brightness || LED_INDICATOR_IS_SET(LedIndicatorType::Error) || LED_INDICATOR_IS_SET(LedIndicatorType::Ok) || LED_INDICATOR_IS_SET(LedIndicatorType::VoltageWarning) || LED_INDICATOR_IS_SET(LedIndicatorType::Voltage) || !gButtons[gShutdownButton].currentState || System_IsSleepRequested())
{
if (hlastVolume != AudioPlayer_GetCurrentVolume() || lastLedBrightness != Led_Brightness || LED_INDICATOR_IS_SET(LedIndicatorType::Error) || LED_INDICATOR_IS_SET(LedIndicatorType::Ok) || LED_INDICATOR_IS_SET(LedIndicatorType::VoltageWarning) || LED_INDICATOR_IS_SET(LedIndicatorType::Voltage) || !gButtons[gShutdownButton].currentState || System_IsSleepRequested()) {
#else
if (hlastVolume != AudioPlayer_GetCurrentVolume() || lastLedBrightness != Led_Brightness || LED_INDICATOR_IS_SET(LedIndicatorType::Error) || LED_INDICATOR_IS_SET(LedIndicatorType::Ok) || !gButtons[gShutdownButton].currentState || System_IsSleepRequested())
{
if (hlastVolume != AudioPlayer_GetCurrentVolume() || lastLedBrightness != Led_Brightness || LED_INDICATOR_IS_SET(LedIndicatorType::Error) || LED_INDICATOR_IS_SET(LedIndicatorType::Ok) || !gButtons[gShutdownButton].currentState || System_IsSleepRequested()) {
#endif
break;
}
else
{
else {
vTaskDelay(portTICK_RATE_MS * 30);
}
}
}
}
switch (gPlayProperties.playMode)
{
switch (gPlayProperties.playMode) {
case NO_PLAYLIST: // If no playlist is active (idle)
if (System_GetOperationMode() == OPMODE_BLUETOOTH)
{
if (System_GetOperationMode() == OPMODE_BLUETOOTH) {
idleColor = CRGB::Blue;
}
else
{
if (Wlan_IsConnected())
{
} else {
if (Wlan_IsConnected()) {
idleColor = CRGB::White;
}
else
{
} else {
idleColor = CRGB::Green;
}
}
if (hlastVolume == AudioPlayer_GetCurrentVolume() && lastLedBrightness == Led_Brightness)
{
for (uint8_t i = 0; i < NUM_LEDS; i++)
{
if (hlastVolume == AudioPlayer_GetCurrentVolume() && lastLedBrightness == Led_Brightness) {
for (uint8_t i = 0; i < NUM_LEDS; i++) {
FastLED.clear();
if (Led_Address(i) == 0)
{ // White if Wifi is enabled and blue if not
if (Led_Address(i) == 0) { // White if Wifi is enabled and blue if not
leds[0] = idleColor;
leds[NUM_LEDS / 4] = idleColor;
leds[NUM_LEDS / 2] = idleColor;
leds[NUM_LEDS / 4 * 3] = idleColor;
}
else
{
} else {
leds[Led_Address(i) % NUM_LEDS] = idleColor;
leds[(Led_Address(i) + NUM_LEDS / 4) % NUM_LEDS] = idleColor;
leds[(Led_Address(i) + NUM_LEDS / 2) % NUM_LEDS] = idleColor;
leds[(Led_Address(i) + NUM_LEDS / 4 * 3) % NUM_LEDS] = idleColor;
}
FastLED.show();
for (uint8_t i = 0; i <= 50; i++)
{
for (uint8_t i = 0; i <= 50; i++) {
#ifdef MEASURE_BATTERY_VOLTAGE
if (hlastVolume != AudioPlayer_GetCurrentVolume() || lastLedBrightness != Led_Brightness || LED_INDICATOR_IS_SET(LedIndicatorType::Error) || LED_INDICATOR_IS_SET(LedIndicatorType::Ok) || LED_INDICATOR_IS_SET(LedIndicatorType::VoltageWarning) || LED_INDICATOR_IS_SET(LedIndicatorType::Voltage) || gPlayProperties.playMode != NO_PLAYLIST || !gButtons[gShutdownButton].currentState || System_IsSleepRequested())
{
if (hlastVolume != AudioPlayer_GetCurrentVolume() || lastLedBrightness != Led_Brightness || LED_INDICATOR_IS_SET(LedIndicatorType::Error) || LED_INDICATOR_IS_SET(LedIndicatorType::Ok) || LED_INDICATOR_IS_SET(LedIndicatorType::VoltageWarning) || LED_INDICATOR_IS_SET(LedIndicatorType::Voltage) || gPlayProperties.playMode != NO_PLAYLIST || !gButtons[gShutdownButton].currentState || System_IsSleepRequested()) {
#else
if (hlastVolume != AudioPlayer_GetCurrentVolume() || lastLedBrightness != Led_Brightness || LED_INDICATOR_IS_SET(LedIndicatorType::Error) || LED_INDICATOR_IS_SET(LedIndicatorType::Ok) || gPlayProperties.playMode != NO_PLAYLIST || !gButtons[gShutdownButton].currentState || System_IsSleepRequested())
{
if (hlastVolume != AudioPlayer_GetCurrentVolume() || lastLedBrightness != Led_Brightness || LED_INDICATOR_IS_SET(LedIndicatorType::Error) || LED_INDICATOR_IS_SET(LedIndicatorType::Ok) || gPlayProperties.playMode != NO_PLAYLIST || !gButtons[gShutdownButton].currentState || System_IsSleepRequested()) {
#endif
break;
}
else
{
} else {
vTaskDelay(portTICK_RATE_MS * 10);
}
}
@ -532,26 +427,21 @@ static void Led_Task(void *parameter)
case BUSY: // If uC is busy (parsing SD-card)
ledBusyShown = true;
for (uint8_t i = 0; i < NUM_LEDS; i++)
{
for (uint8_t i = 0; i < NUM_LEDS; i++) {
FastLED.clear();
if (Led_Address(i) == 0)
{
if (Led_Address(i) == 0) {
leds[0] = CRGB::BlueViolet;
leds[NUM_LEDS / 4] = CRGB::BlueViolet;
leds[NUM_LEDS / 2] = CRGB::BlueViolet;
leds[NUM_LEDS / 4 * 3] = CRGB::BlueViolet;
}
else
{
} else {
leds[Led_Address(i) % NUM_LEDS] = CRGB::BlueViolet;
leds[(Led_Address(i) + NUM_LEDS / 4) % NUM_LEDS] = CRGB::BlueViolet;
leds[(Led_Address(i) + NUM_LEDS / 2) % NUM_LEDS] = CRGB::BlueViolet;
leds[(Led_Address(i) + NUM_LEDS / 4 * 3) % NUM_LEDS] = CRGB::BlueViolet;
}
FastLED.show();
if (gPlayProperties.playMode != BUSY)
{
if (gPlayProperties.playMode != BUSY) {
break;
}
vTaskDelay(portTICK_RATE_MS * 50);
@ -559,21 +449,17 @@ static void Led_Task(void *parameter)
break;
default: // If playlist is active (doesn't matter which type)
if (!gPlayProperties.playlistFinished)
{
if (!gPlayProperties.playlistFinished) {
#ifdef MEASURE_BATTERY_VOLTAGE
if (gPlayProperties.pausePlay != lastPlayState || System_AreControlsLocked() != lastLockState || notificationShown || ledBusyShown || volumeChangeShown || LED_INDICATOR_IS_SET(LedIndicatorType::VoltageWarning) || LED_INDICATOR_IS_SET(LedIndicatorType::Voltage) || !gButtons[gShutdownButton].currentState || System_IsSleepRequested())
{
if (gPlayProperties.pausePlay != lastPlayState || System_AreControlsLocked() != lastLockState || notificationShown || ledBusyShown || volumeChangeShown || LED_INDICATOR_IS_SET(LedIndicatorType::VoltageWarning) || LED_INDICATOR_IS_SET(LedIndicatorType::Voltage) || !gButtons[gShutdownButton].currentState || System_IsSleepRequested()) {
#else
if (gPlayProperties.pausePlay != lastPlayState || System_AreControlsLocked() != lastLockState || notificationShown || ledBusyShown || volumeChangeShown || !gButtons[gShutdownButton].currentState || System_IsSleepRequested())
{
if (gPlayProperties.pausePlay != lastPlayState || System_AreControlsLocked() != lastLockState || notificationShown || ledBusyShown || volumeChangeShown || !gButtons[gShutdownButton].currentState || System_IsSleepRequested()) {
#endif
lastPlayState = gPlayProperties.pausePlay;
lastLockState = System_AreControlsLocked();
notificationShown = false;
volumeChangeShown = false;
if (ledBusyShown)
{
if (ledBusyShown) {
ledBusyShown = false;
FastLED.clear();
FastLED.show();
@ -581,27 +467,20 @@ static void Led_Task(void *parameter)
redrawProgress = true;
}
if (gPlayProperties.playMode != WEBSTREAM)
{
if (gPlayProperties.currentRelPos != lastPos || redrawProgress)
{
if (gPlayProperties.playMode != WEBSTREAM) {
if (gPlayProperties.currentRelPos != lastPos || redrawProgress) {
redrawProgress = false;
lastPos = gPlayProperties.currentRelPos;
uint8_t numLedsToLight = map(gPlayProperties.currentRelPos, 0, 98, 0, NUM_LEDS);
FastLED.clear();
for (uint8_t led = 0; led < numLedsToLight; led++)
{
if (System_AreControlsLocked())
{
for (uint8_t led = 0; led < numLedsToLight; led++) {
if (System_AreControlsLocked()) {
leds[Led_Address(led)] = CRGB::Red;
}
else if (!gPlayProperties.pausePlay)
{ // Hue-rainbow
} else if (!gPlayProperties.pausePlay) { // Hue-rainbow
leds[Led_Address(led)].setHue((uint8_t)(85 - ((double)95 / NUM_LEDS) * led));
}
}
if (gPlayProperties.pausePlay)
{
if (gPlayProperties.pausePlay) {
leds[Led_Address(0)] = CRGB::Orange;
leds[(Led_Address(NUM_LEDS / 4)) % NUM_LEDS] = CRGB::Orange;
leds[(Led_Address(NUM_LEDS / 2)) % NUM_LEDS] = CRGB::Orange;
@ -610,32 +489,23 @@ static void Led_Task(void *parameter)
}
}
}
else
{ // ... but do things a little bit different for Webstream as there's no progress available
if (lastSwitchTimestamp == 0 || (millis() - lastSwitchTimestamp >= ledSwitchInterval * 1000) || redrawProgress)
{
else { // ... but do things a little bit different for Webstream as there's no progress available
if (lastSwitchTimestamp == 0 || (millis() - lastSwitchTimestamp >= ledSwitchInterval * 1000) || redrawProgress) {
redrawProgress = false;
lastSwitchTimestamp = millis();
FastLED.clear();
if (ledPosWebstream + 1 < NUM_LEDS)
{
if (ledPosWebstream + 1 < NUM_LEDS) {
ledPosWebstream++;
}
else
{
} else {
ledPosWebstream = 0;
}
if (System_AreControlsLocked())
{
if (System_AreControlsLocked()) {
leds[Led_Address(ledPosWebstream)] = CRGB::Red;
leds[(Led_Address(ledPosWebstream) + NUM_LEDS / 2) % NUM_LEDS] = CRGB::Red;
}
else if (!gPlayProperties.pausePlay)
{
} else if (!gPlayProperties.pausePlay) {
leds[Led_Address(ledPosWebstream)].setHue(webstreamColor);
leds[(Led_Address(ledPosWebstream) + NUM_LEDS / 2) % NUM_LEDS].setHue(webstreamColor++);
}
else if (gPlayProperties.pausePlay)
} else if (gPlayProperties.pausePlay)
{
leds[Led_Address(ledPosWebstream)] = CRGB::Orange;
leds[(Led_Address(ledPosWebstream) + NUM_LEDS / 2) % NUM_LEDS] = CRGB::Orange;

18
src/Log.cpp

@ -10,8 +10,7 @@ char *Log_Buffer = (char *)calloc(Log_BufferLength, sizeof(char)); // Buffer for
static LogRingBuffer Log_RingBuffer;
void Log_Init(void)
{
void Log_Init(void){
Serial.begin(115200);
Log_Buffer = (char *) x_calloc(Log_BufferLength, sizeof(char)); // Buffer for all log-messages
}
@ -21,26 +20,21 @@ void Log_Init(void)
_minLogLevel: loglevel configured for this message.
If (SERIAL_LOGLEVEL <= _minLogLevel) message will be logged
*/
void Log_Println(const char *_logBuffer, const uint8_t _minLogLevel)
{
if (SERIAL_LOGLEVEL >= _minLogLevel)
{
void Log_Println(const char *_logBuffer, const uint8_t _minLogLevel) {
if (SERIAL_LOGLEVEL >= _minLogLevel) {
Serial.println(_logBuffer);
Log_RingBuffer.println(_logBuffer);
}
}
/* Wrapper-function for serial-logging (without newline) */
void Log_Print(const char *_logBuffer, const uint8_t _minLogLevel)
{
if (SERIAL_LOGLEVEL >= _minLogLevel)
{
void Log_Print(const char *_logBuffer, const uint8_t _minLogLevel) {
if (SERIAL_LOGLEVEL >= _minLogLevel) {
Serial.print(_logBuffer);
Log_RingBuffer.print(_logBuffer);
}
}
String Log_GetRingBuffer(void)
{
String Log_GetRingBuffer(void) {
return Log_RingBuffer.get();
}

199
src/Mqtt.cpp

@ -36,13 +36,11 @@ static void Mqtt_ClientCallback(const char *topic, const byte *payload, uint32_t
static bool Mqtt_Reconnect(void);
static void Mqtt_PostHeartbeatViaMqtt(void);
void Mqtt_Init()
{
void Mqtt_Init() {
#ifdef MQTT_ENABLE
// Get MQTT-enable from NVS
uint8_t nvsEnableMqtt = gPrefsSettings.getUChar("enableMQTT", 99);
switch (nvsEnableMqtt)
{
switch (nvsEnableMqtt) {
case 99:
gPrefsSettings.putUChar("enableMQTT", Mqtt_Enabled);
Log_Println((char *) FPSTR(wroteMqttFlagToNvs), LOGLEVEL_ERROR);
@ -61,13 +59,10 @@ void Mqtt_Init()
// Get MQTT-server from NVS
String nvsMqttServer = gPrefsSettings.getString("mqttServer", "-1");
if (!nvsMqttServer.compareTo("-1"))
{
if (!nvsMqttServer.compareTo("-1")) {
gPrefsSettings.putString("mqttServer", (String)gMqttServer);
Log_Println((char *) FPSTR(wroteMqttServerToNvs), LOGLEVEL_ERROR);
}
else
{
} else {
strncpy(gMqttServer, nvsMqttServer.c_str(), mqttServerLength);
snprintf(Log_Buffer, Log_BufferLength, "%s: %s", (char *) FPSTR(restoredMqttServerFromNvs), nvsMqttServer.c_str());
Log_Println(Log_Buffer, LOGLEVEL_INFO);
@ -75,13 +70,10 @@ void Mqtt_Init()
// Get MQTT-user from NVS
String nvsMqttUser = gPrefsSettings.getString("mqttUser", "-1");
if (!nvsMqttUser.compareTo("-1"))
{
if (!nvsMqttUser.compareTo("-1")) {
gPrefsSettings.putString("mqttUser", (String)gMqttUser);
Log_Println((char *) FPSTR(wroteMqttUserToNvs), LOGLEVEL_ERROR);
}
else
{
} else {
strncpy(gMqttUser, nvsMqttUser.c_str(), mqttUserLength);
snprintf(Log_Buffer, Log_BufferLength, "%s: %s", (char *) FPSTR(restoredMqttUserFromNvs), nvsMqttUser.c_str());
Log_Println(Log_Buffer, LOGLEVEL_INFO);
@ -89,13 +81,10 @@ void Mqtt_Init()
// Get MQTT-password from NVS
String nvsMqttPassword = gPrefsSettings.getString("mqttPassword", "-1");
if (!nvsMqttPassword.compareTo("-1"))
{
if (!nvsMqttPassword.compareTo("-1")) {
gPrefsSettings.putString("mqttPassword", (String)gMqttPassword);
Log_Println((char *) FPSTR(wroteMqttPwdToNvs), LOGLEVEL_ERROR);
}
else
{
} else {
strncpy(gMqttPassword, nvsMqttPassword.c_str(), mqttPasswordLength);
snprintf(Log_Buffer, Log_BufferLength, "%s: %s", (char *) FPSTR(restoredMqttPwdFromNvs), nvsMqttPassword.c_str());
Log_Println(Log_Buffer, LOGLEVEL_INFO);
@ -103,31 +92,25 @@ void Mqtt_Init()
// Get MQTT-password from NVS
uint32_t nvsMqttPort = gPrefsSettings.getUInt("mqttPort", 99999);
if (nvsMqttPort == 99999)
{
if (nvsMqttPort == 99999) {
gPrefsSettings.putUInt("mqttPort", gMqttPort);
}
else
{
} else {
gMqttPort = nvsMqttPort;
snprintf(Log_Buffer, Log_BufferLength, "%s: %u", (char *) FPSTR(restoredMqttPortFromNvs), gMqttPort);
Log_Println(Log_Buffer, LOGLEVEL_INFO);
}
// Only enable MQTT if requested
if (Mqtt_Enabled)
{
if (Mqtt_Enabled) {
Mqtt_PubSubClient.setServer(gMqttServer, gMqttPort);
Mqtt_PubSubClient.setCallback(Mqtt_ClientCallback);
}
#endif
}
void Mqtt_Cyclic(void)
{
void Mqtt_Cyclic(void) {
#ifdef MQTT_ENABLE
if (Mqtt_Enabled && Wlan_IsConnected())
{
if (Mqtt_Enabled && Wlan_IsConnected()) {
Mqtt_Reconnect();
Mqtt_PubSubClient.loop();
Mqtt_PostHeartbeatViaMqtt();
@ -135,8 +118,7 @@ void Mqtt_Cyclic(void)
#endif
}
void Mqtt_Exit(void)
{
void Mqtt_Exit(void) {
#ifdef MQTT_ENABLE
publishMqtt((char *) FPSTR(topicState), "Offline", false);
publishMqtt((char *) FPSTR(topicTrackState), "---", false);
@ -144,30 +126,26 @@ void Mqtt_Exit(void)
#endif
}
bool Mqtt_IsEnabled(void)
{
bool Mqtt_IsEnabled(void) {
return Mqtt_Enabled;
}
/* Wrapper-functions for MQTT-publish */
bool publishMqtt(const char *topic, const char *payload, bool retained)
{
bool publishMqtt(const char *topic, const char *payload, bool retained) {
#ifdef MQTT_ENABLE
if (strcmp(topic, "") != 0)
{
if (Mqtt_PubSubClient.connected())
{
if (strcmp(topic, "") != 0) {
if (Mqtt_PubSubClient.connected()) {
Mqtt_PubSubClient.publish(topic, payload, retained);
delay(100);
return true;
}
}
#endif
return false;
}
bool publishMqtt(const char *topic, int32_t payload, bool retained)
{
bool publishMqtt(const char *topic, int32_t payload, bool retained) {
#ifdef MQTT_ENABLE
char buf[11];
snprintf(buf, sizeof(buf) / sizeof(buf[0]), "%d", payload);
@ -177,8 +155,7 @@ bool publishMqtt(const char *topic, int32_t payload, bool retained)
#endif
}
bool publishMqtt(const char *topic, unsigned long payload, bool retained)
{
bool publishMqtt(const char *topic, unsigned long payload, bool retained) {
#ifdef MQTT_ENABLE
char buf[11];
snprintf(buf, sizeof(buf) / sizeof(buf[0]), "%lu", payload);
@ -188,8 +165,7 @@ bool publishMqtt(const char *topic, unsigned long payload, bool retained)
#endif
}
bool publishMqtt(const char *topic, uint32_t payload, bool retained)
{
bool publishMqtt(const char *topic, uint32_t payload, bool retained) {
#ifdef MQTT_ENABLE
char buf[11];
snprintf(buf, sizeof(buf) / sizeof(buf[0]), "%u", payload);
@ -203,16 +179,13 @@ bool publishMqtt(const char *topic, uint32_t payload, bool retained)
MQTT it's gonna be offline now. But when unplugging ESPuino e.g. openHAB doesn't know ESPuino is offline.
One way to recognize this is to determine, when a topic has been updated for the last time. So by
telling openHAB connection is timed out after 2mins for instance, this is the right topic to check for. */
void Mqtt_PostHeartbeatViaMqtt(void)
{
void Mqtt_PostHeartbeatViaMqtt(void) {
#ifdef MQTT_ENABLE
static unsigned long lastOnlineTimestamp = 0u;
if (millis() - lastOnlineTimestamp >= stillOnlineInterval * 1000)
{
if (millis() - lastOnlineTimestamp >= stillOnlineInterval * 1000) {
lastOnlineTimestamp = millis();
if (publishMqtt((char *)FPSTR(topicState), "Online", false))
{
if (publishMqtt((char *) FPSTR(topicState), "Online", false)) {
Log_Println((char *) FPSTR(stillOnlineMqtt), LOGLEVEL_DEBUG);
}
}
@ -222,47 +195,36 @@ void Mqtt_PostHeartbeatViaMqtt(void)
/* Connects/reconnects to MQTT-Broker unless connection is not already available.
Manages MQTT-subscriptions.
*/
bool Mqtt_Reconnect()
{
bool Mqtt_Reconnect() {
#ifdef MQTT_ENABLE
static uint32_t mqttLastRetryTimestamp = 0u;
uint8_t connect = false;
uint8_t i = 0;
if (!mqttLastRetryTimestamp || millis() - mqttLastRetryTimestamp >= mqttRetryInterval * 1000)
{
if (!mqttLastRetryTimestamp || millis() - mqttLastRetryTimestamp >= mqttRetryInterval * 1000) {
mqttLastRetryTimestamp = millis();
}
else
{
} else {
return false;
}
while (!Mqtt_PubSubClient.connected() && i < mqttMaxRetriesPerInterval)
{
while (!Mqtt_PubSubClient.connected() && i < mqttMaxRetriesPerInterval) {
i++;
snprintf(Log_Buffer, Log_BufferLength, "%s %s", (char *) FPSTR(tryConnectMqttS), gMqttServer);
Log_Println(Log_Buffer, LOGLEVEL_NOTICE);
// Try to connect to MQTT-server. If username AND password are set, they'll be used
if (strlen(gMqttUser) < 1 || strlen(gMqttPassword) < 1)
{
if (strlen(gMqttUser) < 1 || strlen(gMqttPassword) < 1) {
Log_Println((char *) FPSTR(mqttWithoutPwd), LOGLEVEL_NOTICE);
if (Mqtt_PubSubClient.connect(DEVICE_HOSTNAME))
{
if (Mqtt_PubSubClient.connect(DEVICE_HOSTNAME)) {
connect = true;
}
}
else
{
} else {
Log_Println((char *) FPSTR(mqttWithPwd), LOGLEVEL_NOTICE);
if (Mqtt_PubSubClient.connect(DEVICE_HOSTNAME, gMqttUser, gMqttPassword))
{
if (Mqtt_PubSubClient.connect(DEVICE_HOSTNAME, gMqttUser, gMqttPassword)) {
connect = true;
}
}
if (connect)
{
if (connect) {
Log_Println((char *) FPSTR(mqttOk), LOGLEVEL_NOTICE);
// Deepsleep-subscription
@ -301,9 +263,7 @@ bool Mqtt_Reconnect()
publishMqtt((char *) FPSTR(topicCurrentIPv4IP), Wlan_GetIpAddress().c_str(), false);
return Mqtt_PubSubClient.connected();
}
else
{
} else {
snprintf(Log_Buffer, Log_BufferLength, "%s: rc=%i (%d / %d)", (char *) FPSTR(mqttConnFailed), Mqtt_PubSubClient.state(), i, mqttMaxRetriesPerInterval);
Log_Println(Log_Buffer, LOGLEVEL_ERROR);
}
@ -313,8 +273,7 @@ bool Mqtt_Reconnect()
}
// Is called if there's a new MQTT-message for us
void Mqtt_ClientCallback(const char *topic, const byte *payload, uint32_t length)
{
void Mqtt_ClientCallback(const char *topic, const byte *payload, uint32_t length) {
#ifdef MQTT_ENABLE
char *receivedString = x_strndup((char *) payload, length);
char *mqttTopic = x_strdup(topic);
@ -323,77 +282,56 @@ void Mqtt_ClientCallback(const char *topic, const byte *payload, uint32_t length
Log_Println(Log_Buffer, LOGLEVEL_INFO);
// Go to sleep?
if (strcmp_P(topic, topicSleepCmnd) == 0)
{
if ((strcmp(receivedString, "OFF") == 0) || (strcmp(receivedString, "0") == 0))
{
if (strcmp_P(topic, topicSleepCmnd) == 0) {
if ((strcmp(receivedString, "OFF") == 0) || (strcmp(receivedString, "0") == 0)) {
System_RequestSleep();
}
}
// New track to play? Take RFID-ID as input
else if (strcmp_P(topic, topicRfidCmnd) == 0)
{
else if (strcmp_P(topic, topicRfidCmnd) == 0) {
char *_rfidId = x_strdup(receivedString);
xQueueSend(gRfidCardQueue, &_rfidId, 0);
//free(_rfidId);
xQueueSend(gRfidCardQueue, _rfidId, 0);
}
// Loudness to change?
else if (strcmp_P(topic, topicLoudnessCmnd) == 0)
{
else if (strcmp_P(topic, topicLoudnessCmnd) == 0) {
unsigned long vol = strtoul(receivedString, NULL, 10);
AudioPlayer_VolumeToQueueSender(vol, true);
}
// Modify sleep-timer?
else if (strcmp_P(topic, topicSleepTimerCmnd) == 0)
{
if (gPlayProperties.playMode == NO_PLAYLIST)
{ // Don't allow sleep-modications if no playlist is active
else if (strcmp_P(topic, topicSleepTimerCmnd) == 0) {
if (gPlayProperties.playMode == NO_PLAYLIST) { // Don't allow sleep-modications if no playlist is active
Log_Println((char *) FPSTR(modificatorNotallowedWhenIdle), LOGLEVEL_INFO);
publishMqtt((char *) FPSTR(topicSleepState), 0, false);
System_IndicateError();
return;
}
if (strcmp(receivedString, "EOP") == 0)
{
if (strcmp(receivedString, "EOP") == 0) {
gPlayProperties.sleepAfterPlaylist = true;
Log_Println((char *) FPSTR(sleepTimerEOP), LOGLEVEL_NOTICE);
System_IndicateOk();
return;
}
else if (strcmp(receivedString, "EOT") == 0)
{
} else if (strcmp(receivedString, "EOT") == 0) {
gPlayProperties.sleepAfterCurrentTrack = true;
Log_Println((char *) FPSTR(sleepTimerEOT), LOGLEVEL_NOTICE);
System_IndicateOk();
return;
}
else if (strcmp(receivedString, "EO5T") == 0)
{
if ((gPlayProperties.numberOfTracks - 1) >= (gPlayProperties.currentTrackNumber + 5))
{
} else if (strcmp(receivedString, "EO5T") == 0) {
if ((gPlayProperties.numberOfTracks - 1) >= (gPlayProperties.currentTrackNumber + 5)) {
gPlayProperties.playUntilTrackNumber = gPlayProperties.currentTrackNumber + 5;
}
else
{
} else {
gPlayProperties.sleepAfterPlaylist = true;
}
Log_Println((char *) FPSTR(sleepTimerEO5), LOGLEVEL_NOTICE);
System_IndicateOk();
return;
}
else if (strcmp(receivedString, "0") == 0)
{
if (System_IsSleepTimerEnabled())
{
} else if (strcmp(receivedString, "0") == 0) {
if (System_IsSleepTimerEnabled()) {
System_DisableSleepTimer();
Log_Println((char *) FPSTR(sleepTimerStop), LOGLEVEL_NOTICE);
System_IndicateOk();
publishMqtt((char *) FPSTR(topicSleepState), 0, false);
return;
}
else
{
} else {
Log_Println((char *) FPSTR(sleepTimerAlreadyStopped), LOGLEVEL_INFO);
System_IndicateError();
return;
@ -408,23 +346,18 @@ void Mqtt_ClientCallback(const char *topic, const byte *payload, uint32_t length
gPlayProperties.sleepAfterCurrentTrack = false;
}
// Track-control (pause/play, stop, first, last, next, previous)
else if (strcmp_P(topic, topicTrackControlCmnd) == 0)
{
else if (strcmp_P(topic, topicTrackControlCmnd) == 0) {
uint8_t controlCommand = strtoul(receivedString, NULL, 10);
AudioPlayer_TrackControlToQueueSender(controlCommand);
}
// Check if controls should be locked
else if (strcmp_P(topic, topicLockControlsCmnd) == 0)
{
if (strcmp(receivedString, "OFF") == 0)
{
else if (strcmp_P(topic, topicLockControlsCmnd) == 0) {
if (strcmp(receivedString, "OFF") == 0) {
System_SetLockControls(false);
Log_Println((char *) FPSTR(allowButtons), LOGLEVEL_NOTICE);
System_IndicateOk();
}
else if (strcmp(receivedString, "ON") == 0)
{
} else if (strcmp(receivedString, "ON") == 0) {
System_SetLockControls(true);
Log_Println((char *) FPSTR(lockButtons), LOGLEVEL_NOTICE);
System_IndicateOk();
@ -432,24 +365,18 @@ void Mqtt_ClientCallback(const char *topic, const byte *payload, uint32_t length
}
// Check if playmode should be adjusted
else if (strcmp_P(topic, topicRepeatModeCmnd) == 0)
{
else if (strcmp_P(topic, topicRepeatModeCmnd) == 0) {
char rBuf[2];
uint8_t repeatMode = strtoul(receivedString, NULL, 10);
Serial.printf("Repeat: %d", repeatMode);
if (gPlayProperties.playMode != NO_PLAYLIST)
{
if (gPlayProperties.playMode == NO_PLAYLIST)
{
if (gPlayProperties.playMode != NO_PLAYLIST) {
if (gPlayProperties.playMode == NO_PLAYLIST) {
snprintf(rBuf, 2, "%u", AudioPlayer_GetRepeatMode());
publishMqtt((char *) FPSTR(topicRepeatModeState), rBuf, false);
Log_Println((char *) FPSTR(noPlaylistNotAllowedMqtt), LOGLEVEL_ERROR);
System_IndicateError();
}
else
{
switch (repeatMode)
{
} else {
switch (repeatMode) {
case NO_REPEAT:
gPlayProperties.repeatCurrentTrack = false;
gPlayProperties.repeatPlaylist = false;
@ -497,14 +424,12 @@ void Mqtt_ClientCallback(const char *topic, const byte *payload, uint32_t length
}
// Check if LEDs should be dimmed
else if (strcmp_P(topic, topicLedBrightnessCmnd) == 0)
{
else if (strcmp_P(topic, topicLedBrightnessCmnd) == 0) {
Led_SetBrightness(strtoul(receivedString, NULL, 10));
}
// Requested something that isn't specified?
else
{
else {
snprintf(Log_Buffer, Log_BufferLength, "%s: %s", (char *) FPSTR(noValidTopic), topic);
Log_Println(Log_Buffer, LOGLEVEL_ERROR);
System_IndicateError();

33
src/Port.cpp

@ -10,12 +10,10 @@ uint8_t Port_ExpanderPorts[portsToRead];
bool Port_ExpanderHandler(void);
#endif
void Port_Init(void)
{
void Port_Init(void) {
}
void Port_Cyclic(void)
{
void Port_Cyclic(void) {
#ifdef PORT_EXPANDER_ENABLE
Port_ExpanderHandler();
#endif
@ -23,10 +21,8 @@ void Port_Cyclic(void)
// Wrapper: reads from GPIOs (via digitalRead()) or from port-expander (if enabled)
// Behaviour like digitalRead(): returns true if not pressed and false if pressed
bool Port_Read(const uint8_t _channel)
{
switch (_channel)
{
bool Port_Read(const uint8_t _channel) {
switch (_channel) {
case 0 ... 39: // GPIO
return digitalRead(_channel);
@ -35,15 +31,11 @@ bool Port_Read(const uint8_t _channel)
return (Port_ExpanderPorts[0] & (1 << (_channel - 100))); // Remove offset 100 (return false if pressed)
case 108 ... 115: // Port-expander (port 1)
if (portsToRead == 2)
{ // Make sure portsToRead != 1 when channel > 107
if (portsToRead == 2) { // Make sure portsToRead != 1 when channel > 107
return (Port_ExpanderPorts[1] & (1 << (_channel - 108))); // Remove offset 100 + 8 (return false if pressed)
}
else
{
} else {
return true;
}
#endif
default: // Everything else (doesn't make sense at all) isn't supposed to be pressed
@ -54,21 +46,16 @@ bool Port_Read(const uint8_t _channel)
#ifdef PORT_EXPANDER_ENABLE
// Reads input from port-expander and writes output into global array
// Datasheet: https://www.nxp.com/docs/en/data-sheet/PCA9555.pdf
bool Port_ExpanderHandler()
{
bool Port_ExpanderHandler() {
i2cBusTwo.beginTransmission(expanderI2cAddress);
for (uint8_t i = 0; i < portsToRead; i++)
{
for (uint8_t i = 0; i < portsToRead; i++) {
i2cBusTwo.write(0x00 + i); // Go to input-register...
i2cBusTwo.endTransmission();
i2cBusTwo.requestFrom(expanderI2cAddress, 1); // ...and read its byte
if (i2cBusTwo.available())
{
if (i2cBusTwo.available()) {
Port_ExpanderPorts[i] = i2cBusTwo.read();
}
else
{
} else {
return false;
}
}

15
src/Queues.cpp

@ -8,31 +8,26 @@ QueueHandle_t gTrackQueue;
QueueHandle_t gTrackControlQueue;
QueueHandle_t gRfidCardQueue;
void Queues_Init(void)
{
void Queues_Init(void) {
// Create queues
gVolumeQueue = xQueueCreate(1, sizeof(int));
if (gVolumeQueue == NULL)
{
if (gVolumeQueue == NULL) {
Log_Println((char *) FPSTR(unableToCreateVolQ), LOGLEVEL_ERROR);
}
gRfidCardQueue = xQueueCreate(1, cardIdStringSize);
if (gRfidCardQueue == NULL)
{
if (gRfidCardQueue == NULL) {
Log_Println((char *) FPSTR(unableToCreateRfidQ), LOGLEVEL_ERROR);
}
gTrackControlQueue = xQueueCreate(1, sizeof(uint8_t));
if (gTrackControlQueue == NULL)
{
if (gTrackControlQueue == NULL) {
Log_Println((char *) FPSTR(unableToCreateMgmtQ), LOGLEVEL_ERROR);
}
char **playlistArray;
gTrackQueue = xQueueCreate(1, sizeof(playlistArray));
if (gTrackQueue == NULL)
{
if (gTrackQueue == NULL) {
Log_Println((char *) FPSTR(unableToCreatePlayQ), LOGLEVEL_ERROR);
}
}

44
src/RfidCommon.cpp

@ -15,8 +15,7 @@ unsigned long Rfid_LastRfidCheckTimestamp = 0;
char *gCurrentRfidTagId = NULL;
// Tries to lookup RFID-tag-string in NVS and extracts parameter from it if found
void Rfid_PreferenceLookupHandler(void)
{
void Rfid_PreferenceLookupHandler(void) {
BaseType_t rfidStatus;
char rfidTagId[cardIdStringSize];
char _file[255];
@ -25,8 +24,7 @@ void Rfid_PreferenceLookupHandler(void)
uint32_t _playMode = 1;
rfidStatus = xQueueReceive(gRfidCardQueue, &rfidTagId, 0);
if (rfidStatus == pdPASS)
{
if (rfidStatus == pdPASS) {
System_UpdateActivityTimer();
free(gCurrentRfidTagId);
gCurrentRfidTagId = x_strdup(rfidTagId);
@ -35,8 +33,7 @@ void Rfid_PreferenceLookupHandler(void)
Log_Println(Log_Buffer, LOGLEVEL_INFO);
String s = gPrefsRfid.getString(gCurrentRfidTagId, "-1"); // Try to lookup rfidId in NVS
if (!s.compareTo("-1"))
{
if (!s.compareTo("-1")) {
Log_Println((char *) FPSTR(rfidTagUnknownInNvs), LOGLEVEL_ERROR);
System_IndicateError();
return;
@ -45,51 +42,36 @@ void Rfid_PreferenceLookupHandler(void)
char *token;
uint8_t i = 1;
token = strtok((char *)s.c_str(), stringDelimiter);
while (token != NULL)
{ // Try to extract data from string after lookup
if (i == 1)
{
while (token != NULL) { // Try to extract data from string after lookup
if (i == 1) {
strncpy(_file, token, sizeof(_file) / sizeof(_file[0]));
}
else if (i == 2)
{
} else if (i == 2) {
_lastPlayPos = strtoul(token, NULL, 10);
}
else if (i == 3)
{
} else if (i == 3) {
_playMode = strtoul(token, NULL, 10);
}
else if (i == 4)
{
} else if (i == 4) {
_trackLastPlayed = strtoul(token, NULL, 10);
}
i++;
token = strtok(NULL, stringDelimiter);
}
if (i != 5)
{
if (i != 5) {
Log_Println((char *) FPSTR(errorOccuredNvs), LOGLEVEL_ERROR);
System_IndicateError();
}
else
{
} else {
// Only pass file to queue if strtok revealed 3 items
if (_playMode >= 100)
{
if (_playMode >= 100) {
// Modification-cards can change some settings (e.g. introducing track-looping or sleep after track/playlist).
Cmd_Action(_playMode);
}
else
{
} else {
#ifdef MQTT_ENABLE
publishMqtt((char *) FPSTR(topicRfidState), gCurrentRfidTagId, false);
#endif
#ifdef BLUETOOTH_ENABLE
// if music rfid was read, go back to normal mode
if (System_GetOperationMode() == OPMODE_BLUETOOTH)
{
if (System_GetOperationMode() == OPMODE_BLUETOOTH) {
System_SetOperationMode(OPMODE_NORMAL);
}
#endif

29
src/RfidMfrc522.cpp

@ -7,7 +7,6 @@
#include "System.h"
#if defined RFID_READER_TYPE_MFRC522_SPI || defined RFID_READER_TYPE_MFRC522_I2C
#ifdef RFID_READER_TYPE_MFRC522_SPI
#include <MFRC522.h>
#endif
@ -22,15 +21,13 @@ extern unsigned long Rfid_LastRfidCheckTimestamp;
#ifdef RFID_READER_TYPE_MFRC522_I2C
extern TwoWire i2cBusTwo;
static MFRC522_I2C mfrc522(MFRC522_ADDR, MFRC522_RST_PIN, &i2cBusTwo);
#endif
#ifdef RFID_READER_TYPE_MFRC522_SPI
static MFRC522 mfrc522(RFID_CS, RST_PIN);
#endif
void Rfid_Init(void)
{
void Rfid_Init(void) {
#ifdef RFID_READER_TYPE_MFRC522_SPI
SPI.begin(RFID_SCK, RFID_MISO, RFID_MOSI, RFID_CS);
SPI.setFrequency(1000000);
@ -45,24 +42,20 @@ void Rfid_Init(void)
#endif
}
void Rfid_Cyclic(void)
{
void Rfid_Cyclic(void) {
byte cardId[cardIdSize];
String cardIdString;
if ((millis() - Rfid_LastRfidCheckTimestamp) >= RFID_SCAN_INTERVAL)
{
if ((millis() - Rfid_LastRfidCheckTimestamp) >= RFID_SCAN_INTERVAL) {
Rfid_LastRfidCheckTimestamp = millis();
// Reset the loop if no new card is present on the sensor/reader. This saves the entire process when idle.
if (!mfrc522.PICC_IsNewCardPresent())
{
if (!mfrc522.PICC_IsNewCardPresent()) {
return;
}
// Select one of the cards
if (!mfrc522.PICC_ReadCardSerial())
{
if (!mfrc522.PICC_ReadCardSerial()) {
return;
}
@ -73,14 +66,12 @@ void Rfid_Cyclic(void)
memcpy(cardId, mfrc522.uid.uidByte, cardIdSize);
Log_Print((char *) FPSTR(rfidTagDetected), LOGLEVEL_NOTICE);
for (uint8_t i = 0u; i < cardIdSize; i++)
{
for (uint8_t i = 0u; i < cardIdSize; i++) {
snprintf(Log_Buffer, Log_BufferLength, "%02x%s", cardId[i], (i < cardIdSize - 1u) ? "-" : "\n");
Log_Print(Log_Buffer, LOGLEVEL_NOTICE);
}
for (uint8_t i = 0u; i < cardIdSize; i++)
{
for (uint8_t i = 0u; i < cardIdSize; i++) {
char num[4];
snprintf(num, sizeof(num), "%03d", cardId[i]);
cardIdString += num;
@ -90,12 +81,10 @@ void Rfid_Cyclic(void)
}
}
void Rfid_Exit(void)
{
void Rfid_Exit(void) {
}
void Rfid_WakeupCheck(void)
{
void Rfid_WakeupCheck(void) {
}
#endif

99
src/RfidPn5180.cpp

@ -28,12 +28,10 @@
extern unsigned long Rfid_LastRfidCheckTimestamp;
#ifdef RFID_READER_TYPE_PN5180
static void Rfid_Task(void *parameter);
static void Rfid_Read(void);
void Rfid_Init(void)
{
void Rfid_Init(void) {
#ifdef PN5180_ENABLE_LPCD
// disable pin hold from deep sleep
gpio_deep_sleep_hold_dis();
@ -53,22 +51,18 @@ void Rfid_Init(void)
);
}
void Rfid_Cyclic(void)
{
void Rfid_Cyclic(void) {
// Implemented via task
}
void Rfid_Task(void *parameter)
{
for (;;)
{
void Rfid_Task(void *parameter) {
for (;;) {
Rfid_Read();
vTaskDelay(5u);
}
}
void Rfid_Read(void)
{
void Rfid_Read(void) {
static PN5180ISO14443 nfc14443(RFID_CS, RFID_BUSY, RFID_RST);
static PN5180ISO15693 nfc15693(RFID_CS, RFID_BUSY, RFID_RST);
static uint8_t stateMachine = RFID_PN5180_STATE_INIT;
@ -77,8 +71,7 @@ void Rfid_Read(void)
String cardIdString;
bool cardReceived = false;
if (RFID_PN5180_STATE_INIT == stateMachine)
{
if (RFID_PN5180_STATE_INIT == stateMachine) {
nfc14443.begin();
nfc14443.reset();
// show PN5180 reader version
@ -92,62 +85,45 @@ void Rfid_Read(void)
// activate RF field
delay(4);
Log_Println((char *) FPSTR(rfidScannerReady), LOGLEVEL_DEBUG);
}
// 1. check for an ISO-14443 card
else if (RFID_PN5180_NFC14443_STATE_RESET == stateMachine)
{
} else if (RFID_PN5180_NFC14443_STATE_RESET == stateMachine) {
nfc14443.reset();
}
else if (RFID_PN5180_NFC14443_STATE_SETUPRF == stateMachine)
{
} else if (RFID_PN5180_NFC14443_STATE_SETUPRF == stateMachine) {
nfc14443.setupRF();
}
else if (RFID_PN5180_NFC14443_STATE_READCARD == stateMachine)
{
if (nfc14443.readCardSerial(uid) >= 4u)
{
} else if (RFID_PN5180_NFC14443_STATE_READCARD == stateMachine) {
if (nfc14443.readCardSerial(uid) >= 4u) {
cardReceived = true;
}
}
// 2. check for an ISO-15693 card
else if (RFID_PN5180_NFC15693_STATE_RESET == stateMachine)
{
} else if (RFID_PN5180_NFC15693_STATE_RESET == stateMachine) {
nfc15693.reset();
}
else if (RFID_PN5180_NFC15693_STATE_SETUPRF == stateMachine)
{
} else if (RFID_PN5180_NFC15693_STATE_SETUPRF == stateMachine) {
nfc15693.setupRF();
}
else if (RFID_PN5180_NFC15693_STATE_DISABLEPRIVACYMODE == stateMachine)
{
} else if (RFID_PN5180_NFC15693_STATE_DISABLEPRIVACYMODE == stateMachine) {
// check for ICODE-SLIX2 password protected tag
// put your privacy password here, e.g.:
// https://de.ifixit.com/Antworten/Ansehen/513422/nfc+Chips+f%C3%BCr+tonies+kaufen
uint8_t password[] = {0x01, 0x02, 0x03, 0x04};
ISO15693ErrorCode myrc = nfc15693.disablePrivacyMode(password);
if (ISO15693_EC_OK == myrc)
{
if (ISO15693_EC_OK == myrc) {
Serial.println(F("disabling privacy-mode successful"));
}
}
else if (RFID_PN5180_NFC15693_STATE_GETINVENTORY == stateMachine)
{
} else if (RFID_PN5180_NFC15693_STATE_GETINVENTORY == stateMachine) {
// try to read ISO15693 inventory
ISO15693ErrorCode rc = nfc15693.getInventory(uid);
if (rc == ISO15693_EC_OK)
{
if (rc == ISO15693_EC_OK) {
cardReceived = true;
}
}
// send card to queue
if (cardReceived)
{
if (cardReceived) {
memcpy(cardId, uid, cardIdSize);
// check for different card id
if (memcmp((const void *)cardId, (const void *)lastCardId, sizeof(cardId)) == 0)
{
if (memcmp((const void *)cardId, (const void *)lastCardId, sizeof(cardId)) == 0) {
// reset state machine
stateMachine = RFID_PN5180_NFC14443_STATE_RESET;
return;
@ -156,14 +132,12 @@ void Rfid_Read(void)
memcpy(lastCardId, cardId, cardIdSize);
Log_Print((char *) FPSTR(rfidTagDetected), LOGLEVEL_NOTICE);
for (uint8_t i = 0u; i < cardIdSize; i++)
{
for (uint8_t i = 0u; i < cardIdSize; i++) {
snprintf(Log_Buffer, Log_BufferLength, "%02x%s", cardId[i], (i < cardIdSize - 1u) ? "-" : "\n");
Log_Print(Log_Buffer, LOGLEVEL_NOTICE);
}
for (uint8_t i = 0u; i < cardIdSize; i++)
{
for (uint8_t i = 0u; i < cardIdSize; i++) {
char num[4];
snprintf(num, sizeof(num), "%03d", cardId[i]);
cardIdString += num;
@ -174,14 +148,12 @@ void Rfid_Read(void)
stateMachine++;
if (stateMachine > RFID_PN5180_NFC15693_STATE_GETINVENTORY)
{
if (stateMachine > RFID_PN5180_NFC15693_STATE_GETINVENTORY) {
stateMachine = RFID_PN5180_NFC14443_STATE_RESET;
}
}
void Rfid_Exit(void)
{
void Rfid_Exit(void) {
// goto low power card detection mode
#ifdef PN5180_ENABLE_LPCD
static PN5180 nfc(RFID_CS, RFID_BUSY, RFID_RST);
@ -195,8 +167,7 @@ void Rfid_Exit(void)
Serial.println(firmwareVersion[0]);
// check firmware version: PN5180 firmware < 4.0 has several bugs preventing the LPCD mode
// you can flash latest firmware with this project: https://github.com/abidxraihan/PN5180_Updater_ESP32
if (firmwareVersion[1] < 4)
{
if (firmwareVersion[1] < 4) {
Serial.println(F("This PN5180 firmware does not work with LPCD! use firmware >= 4.0"));
return;
}
@ -207,8 +178,7 @@ void Rfid_Exit(void)
Serial.println(Port_Read(RFID_IRQ));
// turn on LPCD
uint16_t wakeupCounterInMs = 0x3FF; // must be in the range of 0x0 - 0xA82. max wake-up time is 2960 ms.
if (nfc.switchToLPCD(wakeupCounterInMs))
{
if (nfc.switchToLPCD(wakeupCounterInMs)) {
Serial.println(F("switch to low power card detection: success"));
// configure wakeup pin for deep-sleep wake-up, use ext1
esp_sleep_enable_ext1_wakeup((1ULL << (RFID_IRQ)), ESP_EXT1_WAKEUP_ANY_HIGH);
@ -216,31 +186,26 @@ void Rfid_Exit(void)
gpio_hold_en(gpio_num_t(RFID_CS)); // CS/NSS
gpio_hold_en(gpio_num_t(RFID_RST)); // RST
gpio_deep_sleep_hold_en();
}
else
{
} else {
Serial.println(F("switchToLPCD failed"));
}
#endif
}
// wake up from LPCD, check card is present. This works only for ISO-14443 compatible cards
void Rfid_WakeupCheck(void)
{
void Rfid_WakeupCheck(void) {
#ifdef PN5180_ENABLE_LPCD
static PN5180ISO14443 nfc14443(RFID_CS, RFID_BUSY, RFID_RST);
nfc14443.begin();
nfc14443.reset();
nfc14443.setupRF();
if (!nfc14443.isCardPresent())
{
if (!nfc14443.isCardPresent()) {
nfc14443.clearIRQStatus(0xffffffff);
Serial.print(F("Logic level at PN5180' IRQ-PIN: "));
Serial.println(Port_Read(RFID_IRQ));
// turn on LPCD
uint16_t wakeupCounterInMs = 0x3FF; // needs to be in the range of 0x0 - 0xA82. max wake-up time is 2960 ms.
if (nfc14443.switchToLPCD(wakeupCounterInMs))
{
if (nfc14443.switchToLPCD(wakeupCounterInMs)) {
Log_Println((char *) FPSTR(lowPowerCardSuccess), LOGLEVEL_INFO);
// configure wakeup pin for deep-sleep wake-up, use ext1
esp_sleep_enable_ext1_wakeup((1ULL << (RFID_IRQ)), ESP_EXT1_WAKEUP_ANY_HIGH);
@ -250,9 +215,7 @@ void Rfid_WakeupCheck(void)
gpio_deep_sleep_hold_en();
Log_Println((char *) FPSTR(wakeUpRfidNoIso14443), LOGLEVEL_ERROR);
esp_deep_sleep_start();
}
else
{
} else {
Serial.println(F("switchToLPCD failed"));
}
}

25
src/RotaryEncoder.cpp

@ -18,8 +18,7 @@ int32_t currentEncoderValue;
int32_t lastVolume = -1; // Don't change -1 as initial-value!
#endif
void RotaryEncoder_Init(void)
{
void RotaryEncoder_Init(void) {
// Init rotary encoder
#ifdef USEROTARY_ENABLE
encoder.attachHalfQuad(DREHENCODER_CLK, DREHENCODER_DT);
@ -28,8 +27,7 @@ void RotaryEncoder_Init(void)
#endif
}
void RotaryEncoder_Readjust(void)
{
void RotaryEncoder_Readjust(void) {
#ifdef USEROTARY_ENABLE
encoder.clearCount();
encoder.setCount(AudioPlayer_GetCurrentVolume() * 2);
@ -37,11 +35,9 @@ void RotaryEncoder_Readjust(void)
}
// Handles volume directed by rotary encoder
void RotaryEncoder_Cyclic(void)
{
void RotaryEncoder_Cyclic(void) {
#ifdef USEROTARY_ENABLE
if (System_AreControlsLocked())
{
if (System_AreControlsLocked()) {
encoder.clearCount();
encoder.setCount(AudioPlayer_GetCurrentVolume() * 2);
return;
@ -49,18 +45,14 @@ void RotaryEncoder_Cyclic(void)
currentEncoderValue = encoder.getCount();
// Only if initial run or value has changed. And only after "full step" of rotary encoder
if (((lastEncoderValue != currentEncoderValue) || lastVolume == -1) && (currentEncoderValue % 2 == 0))
{
if (((lastEncoderValue != currentEncoderValue) || lastVolume == -1) && (currentEncoderValue % 2 == 0)) {
System_UpdateActivityTimer(); // Set inactive back if rotary encoder was used
if ((AudioPlayer_GetMaxVolume() * 2) < currentEncoderValue)
{
if ((AudioPlayer_GetMaxVolume() * 2) < currentEncoderValue) {
encoder.clearCount();
encoder.setCount(AudioPlayer_GetMaxVolume() * 2);
Log_Println((char *) FPSTR(maxLoudnessReached), LOGLEVEL_INFO);
currentEncoderValue = encoder.getCount();
}
else if (currentEncoderValue < AudioPlayer_GetMinVolume())
{
} else if (currentEncoderValue < AudioPlayer_GetMinVolume()) {
encoder.clearCount();
encoder.setCount(AudioPlayer_GetMinVolume());
Log_Println((char *) FPSTR(minLoudnessReached), LOGLEVEL_INFO);
@ -68,8 +60,7 @@ void RotaryEncoder_Cyclic(void)
}
lastEncoderValue = currentEncoderValue;
AudioPlayer_SetCurrentVolume(lastEncoderValue / 2u);
if (AudioPlayer_GetCurrentVolume() != lastVolume)
{
if (AudioPlayer_GetCurrentVolume() != lastVolume) {
lastVolume = AudioPlayer_GetCurrentVolume();
AudioPlayer_VolumeToQueueSender(AudioPlayer_GetCurrentVolume(), false);
}

82
src/SdCard.cpp

@ -14,36 +14,30 @@ SPIClass spiSD(HSPI);
fs::FS gFSystem = (fs::FS)SD;
#endif
void SdCard_Init(void)
{
void SdCard_Init(void) {
#ifndef SINGLE_SPI_ENABLE
#ifdef SD_MMC_1BIT_MODE
pinMode(2, INPUT_PULLUP);
while (!SD_MMC.begin("/sdcard", true))
{
while (!SD_MMC.begin("/sdcard", true)) {
#else
pinMode(SPISD_CS, OUTPUT);
digitalWrite(SPISD_CS, HIGH);
spiSD.begin(SPISD_SCK, SPISD_MISO, SPISD_MOSI, SPISD_CS);
spiSD.setFrequency(1000000);
while (!SD.begin(SPISD_CS, spiSD))
{
while (!SD.begin(SPISD_CS, spiSD)) {
#endif
#else
#ifdef SD_MMC_1BIT_MODE
pinMode(2, INPUT_PULLUP);
while (!SD_MMC.begin("/sdcard", true))
{
while (!SD_MMC.begin("/sdcard", true)) {
#else
while (!SD.begin(SPISD_CS))
{
while (!SD.begin(SPISD_CS)) {
#endif
#endif
Log_Println((char *) FPSTR(unableToMountSd), LOGLEVEL_ERROR);
delay(500);
#ifdef SHUTDOWN_IF_SD_BOOT_FAILS
if (millis() >= deepsleepTimeAfterBootFails * 1000)
{
if (millis() >= deepsleepTimeAfterBootFails * 1000) {
Log_Println((char *) FPSTR(sdBootFailedDeepsleep), LOGLEVEL_ERROR);
esp_deep_sleep_start();
}
@ -51,16 +45,14 @@ void SdCard_Init(void)
}
}
void SdCard_Exit(void)
{
void SdCard_Exit(void) {
// SD card goto idle mode
#ifdef SD_MMC_1BIT_MODE
SD_MMC.end();
#endif
}
sdcard_type_t SdCard_GetType(void)
{
sdcard_type_t SdCard_GetType(void) {
sdcard_type_t cardType;
#ifdef SD_MMC_1BIT_MODE
Log_Println((char *) FPSTR(sdMountedMmc1BitMode), LOGLEVEL_NOTICE);
@ -73,8 +65,7 @@ sdcard_type_t SdCard_GetType(void)
}
// Check if file-type is correct
bool fileValid(const char *_fileItem)
{
bool fileValid(const char *_fileItem) {
const char ch = '/';
char *subst;
subst = strrchr(_fileItem, ch); // Don't use files that start with .
@ -91,8 +82,7 @@ bool fileValid(const char *_fileItem)
/* Puts SD-file(s) or directory into a playlist
First element of array always contains the number of payload-items. */
char **SdCard_ReturnPlaylist(const char *fileName)
{
char **SdCard_ReturnPlaylist(const char *fileName) {
static char **files;
char fileNameBuf[255];
@ -101,8 +91,7 @@ char **SdCard_ReturnPlaylist(const char *fileName)
snprintf(Log_Buffer, Log_BufferLength, "%s: %u", (char *) FPSTR(freeMemory), ESP.getFreeHeap());
Log_Println(Log_Buffer, LOGLEVEL_DEBUG);
if (files != NULL)
{ // If **ptr already exists, de-allocate its memory
if (files != NULL) { // If **ptr already exists, de-allocate its memory
Log_Println((char *) FPSTR(releaseMemoryOfOldPlaylist), LOGLEVEL_DEBUG);
--files;
freeMultiCharArray(files, strtoul(*files, NULL, 10));
@ -110,18 +99,15 @@ char **SdCard_ReturnPlaylist(const char *fileName)
Log_Println(Log_Buffer, LOGLEVEL_DEBUG);
}
if (!fileOrDirectory)
{
if (!fileOrDirectory) {
Log_Println((char *) FPSTR(dirOrFileDoesNotExist), LOGLEVEL_ERROR);
return NULL;
}
// File-mode
if (!fileOrDirectory.isDirectory())
{
if (!fileOrDirectory.isDirectory()) {
files = (char **) x_malloc(sizeof(char *) * 2);
if (files == NULL)
{
if (files == NULL) {
Log_Println((char *) FPSTR(unableToAllocateMemForPlaylist), LOGLEVEL_ERROR);
System_IndicateError();
return NULL;
@ -141,40 +127,31 @@ char **SdCard_ReturnPlaylist(const char *fileName)
// Directory-mode
uint16_t allocCount = 1;
uint16_t allocSize = 512;
if (psramInit())
{
if (psramInit()) {
allocSize = 16384; // There's enough PSRAM. So we don't have to care...
}
char *serializedPlaylist;
serializedPlaylist = (char *) x_calloc(allocSize, sizeof(char));
while (true)
{
while (true) {
File fileItem = fileOrDirectory.openNextFile();
if (!fileItem)
{
if (!fileItem) {
break;
}
if (fileItem.isDirectory())
{
if (fileItem.isDirectory()) {
continue;
}
else
{
} else {
strncpy(fileNameBuf, (char *) fileItem.name(), sizeof(fileNameBuf) / sizeof(fileNameBuf[0]));
// Don't support filenames that start with "." and only allow .mp3
if (fileValid(fileNameBuf))
{
if (fileValid(fileNameBuf)) {
/*snprintf(Log_Buffer, Log_BufferLength, "%s: %s", (char *) FPSTR(nameOfFileFound), fileNameBuf);
Log_Println(Log_Buffer, LOGLEVEL_INFO);*/
if ((strlen(serializedPlaylist) + strlen(fileNameBuf) + 2) >= allocCount * allocSize)
{
if ((strlen(serializedPlaylist) + strlen(fileNameBuf) + 2) >= allocCount * allocSize) {
serializedPlaylist = (char *) realloc(serializedPlaylist, ++allocCount * allocSize);
Log_Println((char *) FPSTR(reallocCalled), LOGLEVEL_DEBUG);
if (serializedPlaylist == NULL)
{
if (serializedPlaylist == NULL) {
Log_Println((char *) FPSTR(unableToAllocateMemForLinearPlaylist), LOGLEVEL_ERROR);
System_IndicateError();
return files;
@ -188,10 +165,8 @@ char **SdCard_ReturnPlaylist(const char *fileName)
// Get number of elements out of serialized playlist
uint32_t cnt = 0;
for (uint32_t k = 0; k < (strlen(serializedPlaylist)); k++)
{
if (serializedPlaylist[k] == '#')
{
for (uint32_t k = 0; k < (strlen(serializedPlaylist)); k++) {
if (serializedPlaylist[k] == '#') {
cnt++;
}
}
@ -199,8 +174,7 @@ char **SdCard_ReturnPlaylist(const char *fileName)
// Alloc only necessary number of playlist-pointers
files = (char **) x_malloc(sizeof(char *) * cnt + 1);
if (files == NULL)
{
if (files == NULL) {
Log_Println((char *) FPSTR(unableToAllocateMemForPlaylist), LOGLEVEL_ERROR);
System_IndicateError();
free(serializedPlaylist);
@ -211,8 +185,7 @@ char **SdCard_ReturnPlaylist(const char *fileName)
char *token;
token = strtok(serializedPlaylist, stringDelimiter);
uint32_t pos = 1;
while (token != NULL)
{
while (token != NULL) {
files[pos++] = x_strdup(token);
token = strtok(NULL, stringDelimiter);
}
@ -221,8 +194,7 @@ char **SdCard_ReturnPlaylist(const char *fileName)
files[0] = (char *) x_malloc(sizeof(char) * 5);
if (files[0] == NULL)
{
if (files[0] == NULL) {
Log_Println((char *) FPSTR(unableToAllocateMemForPlaylist), LOGLEVEL_ERROR);
System_IndicateError();
return NULL;

107
src/System.cpp

@ -28,8 +28,7 @@ volatile uint8_t System_OperationMode;
void System_SleepHandler(void);
void System_DeepSleepManager(void);
void System_Init(void)
{
void System_Init(void) {
srand(esp_random());
pinMode(POWER, OUTPUT);
digitalWrite(POWER, HIGH);
@ -39,14 +38,11 @@ void System_Init(void)
// Get maximum inactivity-time from NVS
uint32_t nvsMInactivityTime = gPrefsSettings.getUInt("mInactiviyT", 0);
if (nvsMInactivityTime)
{
if (nvsMInactivityTime) {
System_MaxInactivityTime = nvsMInactivityTime;
snprintf(Log_Buffer, Log_BufferLength, "%s: %u", (char *) FPSTR(restoredMaxInactivityFromNvs), nvsMInactivityTime);
Log_Println(Log_Buffer, LOGLEVEL_INFO);
}
else
{
} else {
gPrefsSettings.putUInt("mInactiviyT", System_MaxInactivityTime);
Log_Println((char *) FPSTR(wroteMaxInactivityToNvs), LOGLEVEL_ERROR);
}
@ -54,40 +50,32 @@ void System_Init(void)
System_OperationMode = gPrefsSettings.getUChar("operationMode", OPMODE_NORMAL);
}
void System_Cyclic(void)
{
void System_Cyclic(void) {
System_SleepHandler();
System_DeepSleepManager();
}
void System_UpdateActivityTimer(void)
{
void System_UpdateActivityTimer(void) {
System_LastTimeActiveTimestamp = millis();
}
void System_RequestSleep(void)
{
void System_RequestSleep(void) {
System_GoToSleep = true;
}
bool System_IsSleepRequested(void)
{
bool System_IsSleepRequested(void) {
return System_GoToSleep;
}
bool System_SetSleepTimer(uint8_t minutes)
{
bool System_SetSleepTimer(uint8_t minutes) {
bool sleepTimerEnabled = false;
if (System_SleepTimerStartTimestamp && (System_SleepTimer == minutes))
{
if (System_SleepTimerStartTimestamp && (System_SleepTimer == minutes)) {
System_SleepTimerStartTimestamp = 0u;
Led_ResetToInitialBrightness();
Log_Println((char *) FPSTR(modificatorSleepd), LOGLEVEL_NOTICE);
publishMqtt((char *) FPSTR(topicLedBrightnessState), Led_GetBrightness(), false);
}
else
{
} else {
System_SleepTimer = minutes;
System_SleepTimerStartTimestamp = millis();
sleepTimerEnabled = true;
@ -101,104 +89,82 @@ bool System_SetSleepTimer(uint8_t minutes)
return sleepTimerEnabled;
}
void System_DisableSleepTimer(void)
{
void System_DisableSleepTimer(void) {
System_SleepTimerStartTimestamp = 0u;
}
bool System_IsSleepTimerEnabled(void)
{
bool System_IsSleepTimerEnabled(void) {
return (System_SleepTimerStartTimestamp > 0u);
}
uint32_t System_GetSleepTimerTimeStamp(void)
{
uint32_t System_GetSleepTimerTimeStamp(void) {
return System_SleepTimerStartTimestamp;
}
bool System_IsSleepPending(void)
{
bool System_IsSleepPending(void) {
return System_Sleeping;
}
uint8_t System_GetSleepTimer(void)
{
uint8_t System_GetSleepTimer(void) {
return System_SleepTimer;
}
void System_SetLockControls(bool value)
{
void System_SetLockControls(bool value) {
System_LockControls = value;
}
void System_ToggleLockControls(void)
{
void System_ToggleLockControls(void) {
System_LockControls = !System_LockControls;
if (System_LockControls)
{
if (System_LockControls) {
Log_Println((char *) FPSTR(modificatorAllButtonsLocked), LOGLEVEL_NOTICE);
publishMqtt((char *) FPSTR(topicLockControlsState), "ON", false);
System_IndicateOk();
}
else
{
} else {
Log_Println((char *) FPSTR(modificatorAllButtonsUnlocked), LOGLEVEL_NOTICE);
publishMqtt((char *) FPSTR(topicLockControlsState), "OFF", false);
}
}
bool System_AreControlsLocked(void)
{
bool System_AreControlsLocked(void) {
return System_LockControls;
}
void System_IndicateError(void)
{
void System_IndicateError(void) {
Led_Indicate(LedIndicatorType::Error);
}
void System_IndicateOk(void)
{
void System_IndicateOk(void) {
Led_Indicate(LedIndicatorType::Ok);
}
// Writes to NVS, if bluetooth or "normal" mode is desired
void System_SetOperationMode(uint8_t opMode)
{
void System_SetOperationMode(uint8_t opMode) {
uint8_t currentOperationMode = gPrefsSettings.getUChar("operationMode", OPMODE_NORMAL);
if (currentOperationMode != opMode)
{
if (gPrefsSettings.putUChar("operationMode", opMode))
{
if (currentOperationMode != opMode) {
if (gPrefsSettings.putUChar("operationMode", opMode)) {
ESP.restart();
}
}
}
uint8_t System_GetOperationMode(void)
{
uint8_t System_GetOperationMode(void) {
return System_OperationMode;
}
// Reads from NVS, if bluetooth or "normal" mode is desired
uint8_t System_GetOperationModeFromNvs(void)
{
uint8_t System_GetOperationModeFromNvs(void) {
return gPrefsSettings.getUChar("operationMode", OPMODE_NORMAL);
}
// Sets deep-sleep-flag if max. inactivity-time is reached
void System_SleepHandler(void)
{
void System_SleepHandler(void) {
unsigned long m = millis();
if (m >= System_LastTimeActiveTimestamp && (m - System_LastTimeActiveTimestamp >= (System_MaxInactivityTime * 1000u * 60u)))
{
if (m >= System_LastTimeActiveTimestamp && (m - System_LastTimeActiveTimestamp >= (System_MaxInactivityTime * 1000u * 60u))) {
Log_Println((char *) FPSTR(goToSleepDueToIdle), LOGLEVEL_INFO);
System_RequestSleep();
}
else if (System_SleepTimerStartTimestamp > 00)
{
if (m - System_SleepTimerStartTimestamp >= (System_SleepTimer * 1000u * 60u))
{
} else if (System_SleepTimerStartTimestamp > 00) {
if (m - System_SleepTimerStartTimestamp >= (System_SleepTimer * 1000u * 60u)) {
Log_Println((char *) FPSTR(goToSleepDueToTimer), LOGLEVEL_INFO);
System_RequestSleep();
}
@ -206,12 +172,9 @@ void System_SleepHandler(void)
}
// Puts uC to deep-sleep if flag is set
void System_DeepSleepManager(void)
{
if (System_GoToSleep)
{
if (System_Sleeping)
{
void System_DeepSleepManager(void) {
if (System_GoToSleep) {
if (System_Sleeping) {
return;
}

504
src/Web.cpp

@ -21,13 +21,18 @@
#include "Web.h"
#include "Wlan.h"
#if (LANGUAGE == 1)
#include "HTMLaccesspoint_DE.h"
#include "HTMLaccesspoint_EN.h"
#include "HTMLmanagement_DE.h"
#endif
#if (LANGUAGE == 2)
#include "HTMLaccesspoint_EN.h"
#include "HTMLmanagement_EN.h"
#endif
typedef struct
{
typedef struct {
char nvsKey[13];
char nvsEntry[275];
} nvs_t;
@ -60,15 +65,13 @@ static void onWebsocketEvent(AsyncWebSocket *server, AsyncWebSocketClient *clien
static String templateProcessor(const String &templ);
static void webserverStart(void);
void Web_Init(void)
{
void Web_Init(void) {
wServer.on("/", HTTP_GET, [](AsyncWebServerRequest *request) {
request->send_P(200, "text/html", accesspoint_HTML);
});
wServer.on("/init", HTTP_POST, [](AsyncWebServerRequest *request) {
if (request->hasParam("ssid", true) && request->hasParam("pwd", true) && request->hasParam("hostname", true))
{
if (request->hasParam("ssid", true) && request->hasParam("pwd", true) && request->hasParam("hostname", true)) {
Serial.println(request->getParam("ssid", true)->value());
Serial.println(request->getParam("pwd", true)->value());
Serial.println(request->getParam("hostname", true)->value());
@ -104,21 +107,17 @@ void Web_Init(void)
Log_Println((char *) FPSTR(httpReady), LOGLEVEL_NOTICE);
}
void Web_Cyclic(void)
{
void Web_Cyclic(void) {
webserverStart();
ws.cleanupClients();
}
void notFound(AsyncWebServerRequest *request)
{
void notFound(AsyncWebServerRequest *request) {
request->send(404, "text/plain", "Not found");
}
void webserverStart(void)
{
if (Wlan_IsConnected() && !webserverStarted)
{
void webserverStart(void) {
if (Wlan_IsConnected() && !webserverStarted) {
// attach AsyncWebSocket for Mgmt-Interface
ws.onEvent(onWebsocketEvent);
wServer.addHandler(&ws);
@ -185,133 +184,75 @@ void webserverStart(void)
// Used for substitution of some variables/templates of html-files. Is called by webserver's template-engine
String templateProcessor(const String &templ)
{
if (templ == "FTP_USER")
{
if (templ == "FTP_USER") {
return gPrefsSettings.getString("ftpuser", "-1");
}
else if (templ == "FTP_PWD")
{
} else if (templ == "FTP_PWD") {
return gPrefsSettings.getString("ftppassword", "-1");
}
else if (templ == "FTP_USER_LENGTH")
{
} else if (templ == "FTP_USER_LENGTH") {
return String(ftpUserLength - 1);
}
else if (templ == "FTP_PWD_LENGTH")
{
} else if (templ == "FTP_PWD_LENGTH") {
return String(ftpPasswordLength - 1);
}
else if (templ == "SHOW_FTP_TAB")
{ // Only show FTP-tab if FTP-support was compiled
} else if (templ == "SHOW_FTP_TAB") { // Only show FTP-tab if FTP-support was compiled
#ifdef FTP_ENABLE
return (String) FPSTR(ftpTab);
#else
return String();
#endif
}
else if (templ == "INIT_LED_BRIGHTNESS")
{
} else if (templ == "INIT_LED_BRIGHTNESS") {
return String(gPrefsSettings.getUChar("iLedBrightness", 0));
}
else if (templ == "NIGHT_LED_BRIGHTNESS")
{
} else if (templ == "NIGHT_LED_BRIGHTNESS") {
return String(gPrefsSettings.getUChar("nLedBrightness", 0));
}
else if (templ == "MAX_INACTIVITY")
{
} else if (templ == "MAX_INACTIVITY") {
return String(gPrefsSettings.getUInt("mInactiviyT", 0));
}
else if (templ == "INIT_VOLUME")
{
} else if (templ == "INIT_VOLUME") {
return String(gPrefsSettings.getUInt("initVolume", 0));
}
else if (templ == "CURRENT_VOLUME")
{
} else if (templ == "CURRENT_VOLUME") {
return String(AudioPlayer_GetCurrentVolume());
}
else if (templ == "MAX_VOLUME_SPEAKER")
{
} else if (templ == "MAX_VOLUME_SPEAKER") {
return String(gPrefsSettings.getUInt("maxVolumeSp", 0));
}
else if (templ == "MAX_VOLUME_HEADPHONE")
{
} else if (templ == "MAX_VOLUME_HEADPHONE") {
return String(gPrefsSettings.getUInt("maxVolumeHp", 0));
}
else if (templ == "WARNING_LOW_VOLTAGE")
{
} else if (templ == "WARNING_LOW_VOLTAGE") {
return String(gPrefsSettings.getFloat("wLowVoltage", warningLowVoltage));
}
else if (templ == "VOLTAGE_INDICATOR_LOW")
{
} else if (templ == "VOLTAGE_INDICATOR_LOW") {
return String(gPrefsSettings.getFloat("vIndicatorLow", voltageIndicatorLow));
}
else if (templ == "VOLTAGE_INDICATOR_HIGH")
{
} else if (templ == "VOLTAGE_INDICATOR_HIGH") {
return String(gPrefsSettings.getFloat("vIndicatorHigh", voltageIndicatorHigh));
}
else if (templ == "VOLTAGE_CHECK_INTERVAL")
{
} else if (templ == "VOLTAGE_CHECK_INTERVAL") {
return String(gPrefsSettings.getUInt("vCheckIntv", voltageCheckInterval));
}
else if (templ == "MQTT_SERVER")
{
} else if (templ == "MQTT_SERVER") {
return gPrefsSettings.getString("mqttServer", "-1");
}
else if (templ == "SHOW_MQTT_TAB")
{ // Only show MQTT-tab if MQTT-support was compiled
} else if (templ == "SHOW_MQTT_TAB") { // Only show MQTT-tab if MQTT-support was compiled
#ifdef MQTT_ENABLE
return (String) FPSTR(mqttTab);
#else
return String();
#endif
}
else if (templ == "MQTT_ENABLE")
{
if (Mqtt_IsEnabled())
{
} else if (templ == "MQTT_ENABLE") {
if (Mqtt_IsEnabled()) {
return String("checked=\"checked\"");
}
else
{
} else {
return String();
}
}
else if (templ == "MQTT_USER")
{
} else if (templ == "MQTT_USER") {
return gPrefsSettings.getString("mqttUser", "-1");
}
else if (templ == "MQTT_PWD")
{
} else if (templ == "MQTT_PWD") {
return gPrefsSettings.getString("mqttPassword", "-1");
}
else if (templ == "MQTT_USER_LENGTH")
{
} else if (templ == "MQTT_USER_LENGTH") {
return String(mqttUserLength - 1);
}
else if (templ == "MQTT_PWD_LENGTH")
{
} else if (templ == "MQTT_PWD_LENGTH") {
return String(mqttPasswordLength - 1);
}
else if (templ == "MQTT_SERVER_LENGTH")
{
} else if (templ == "MQTT_SERVER_LENGTH") {
return String(mqttServerLength - 1);
}
else if (templ == "MQTT_PORT")
{
} else if (templ == "MQTT_PORT") {
return String(gMqttPort);
}
else if (templ == "IPv4")
{
} else if (templ == "IPv4") {
IPAddress myIP = WiFi.localIP();
snprintf(Log_Buffer, Log_BufferLength, "%d.%d.%d.%d", myIP[0], myIP[1], myIP[2], myIP[3]);
return String(Log_Buffer);
}
else if (templ == "RFID_TAG_ID")
{
} else if (templ == "RFID_TAG_ID") {
return String(gCurrentRfidTagId);
}
else if (templ == "HOSTNAME")
{
} else if (templ == "HOSTNAME") {
return gPrefsSettings.getString("Hostname", "-1");
}
@ -320,14 +261,12 @@ String templateProcessor(const String &templ)
// Takes inputs from webgui, parses JSON and saves values in NVS
// If operation was successful (NVS-write is verified) true is returned
bool processJsonRequest(char *_serialJson)
{
bool processJsonRequest(char *_serialJson) {
StaticJsonDocument<1000> doc;
DeserializationError error = deserializeJson(doc, _serialJson);
JsonObject object = doc.as<JsonObject>();
if (error)
{
if (error) {
#if (LANGUAGE == 1)
Serial.print(F("deserializeJson() fehlgeschlagen: "));
#else
@ -337,8 +276,7 @@ bool processJsonRequest(char *_serialJson)
return false;
}
if (doc.containsKey("general"))
{
if (doc.containsKey("general")) {
uint8_t iVol = doc["general"]["iVol"].as<uint8_t>();
uint8_t mVolSpeaker = doc["general"]["mVolSpeaker"].as<uint8_t>();
uint8_t mVolHeadphone = doc["general"]["mVolHeadphone"].as<uint8_t>();
@ -371,13 +309,10 @@ bool processJsonRequest(char *_serialJson)
gPrefsSettings.getFloat("wLowVoltage", 999.99) != vWarning ||
gPrefsSettings.getFloat("vIndicatorLow", 999.99) != vIndLow ||
gPrefsSettings.getFloat("vIndicatorHigh", 999.99) != vIndHi ||
gPrefsSettings.getUInt("vCheckIntv", 17777) != vInt)
{
gPrefsSettings.getUInt("vCheckIntv", 17777) != vInt) {
return false;
}
}
else if (doc.containsKey("ftp"))
{
} else if (doc.containsKey("ftp")) {
const char *_ftpUser = doc["ftp"]["ftpUser"];
const char *_ftpPwd = doc["ftp"]["ftpPwd"];
@ -385,13 +320,10 @@ bool processJsonRequest(char *_serialJson)
gPrefsSettings.putString("ftppassword", (String)_ftpPwd);
if (!(String(_ftpUser).equals(gPrefsSettings.getString("ftpuser", "-1")) ||
String(_ftpPwd).equals(gPrefsSettings.getString("ftppassword", "-1"))))
{
String(_ftpPwd).equals(gPrefsSettings.getString("ftppassword", "-1")))) {
return false;
}
}
else if (doc.containsKey("mqtt"))
{
} else if (doc.containsKey("mqtt")) {
uint8_t _mqttEnable = doc["mqtt"]["mqttEnable"].as<uint8_t>();
const char *_mqttServer = object["mqtt"]["mqttServer"];
gPrefsSettings.putUChar("enableMQTT", _mqttEnable);
@ -408,35 +340,26 @@ bool processJsonRequest(char *_serialJson)
gPrefsSettings.putUInt("mqttPort", _mqttPort);
if ((gPrefsSettings.getUChar("enableMQTT", 99) != _mqttEnable) ||
(!String(_mqttServer).equals(gPrefsSettings.getString("mqttServer", "-1"))))
{
(!String(_mqttServer).equals(gPrefsSettings.getString("mqttServer", "-1")))) {
return false;
}
}
else if (doc.containsKey("rfidMod"))
{
} else if (doc.containsKey("rfidMod")) {
const char *_rfidIdModId = object["rfidMod"]["rfidIdMod"];
uint8_t _modId = object["rfidMod"]["modId"];
char rfidString[12];
if (_modId <= 0)
{
if (_modId <= 0) {
gPrefsRfid.remove(_rfidIdModId);
}
else
{
} else {
snprintf(rfidString, sizeof(rfidString) / sizeof(rfidString[0]), "%s0%s0%s%u%s0", stringDelimiter, stringDelimiter, stringDelimiter, _modId, stringDelimiter);
gPrefsRfid.putString(_rfidIdModId, rfidString);
String s = gPrefsRfid.getString(_rfidIdModId, "-1");
if (s.compareTo(rfidString))
{
if (s.compareTo(rfidString)) {
return false;
}
}
Web_DumpNvsToSd("rfidTags", (const char*) FPSTR(backupFile)); // Store backup-file every time when a new rfid-tag is programmed
}
else if (doc.containsKey("rfidAssign"))
{
} else if (doc.containsKey("rfidAssign")) {
const char *_rfidIdAssinId = object["rfidAssign"]["rfidIdMusic"];
char _fileOrUrlAscii[MAX_FILEPATH_LENTGH];
convertUtf8ToAscii(object["rfidAssign"]["fileOrUrl"], _fileOrUrlAscii);
@ -448,14 +371,11 @@ bool processJsonRequest(char *_serialJson)
Serial.println(rfidString);
String s = gPrefsRfid.getString(_rfidIdAssinId, "-1");
if (s.compareTo(rfidString))
{
if (s.compareTo(rfidString)) {
return false;
}
Web_DumpNvsToSd("rfidTags", (const char*) FPSTR(backupFile)); // Store backup-file every time when a new rfid-tag is programmed
}
else if (doc.containsKey("wifiConfig"))
{
} else if (doc.containsKey("wifiConfig")) {
const char *_ssid = object["wifiConfig"]["ssid"];
const char *_pwd = object["wifiConfig"]["pwd"];
const char *_hostname = object["wifiConfig"]["hostname"];
@ -468,25 +388,18 @@ bool processJsonRequest(char *_serialJson)
String sPwd = gPrefsSettings.getString("Password", "-1");
String sHostname = gPrefsSettings.getString("Hostname", "-1");
if (sSsid.compareTo(_ssid) || sPwd.compareTo(_pwd))
{
if (sSsid.compareTo(_ssid) || sPwd.compareTo(_pwd)) {
return false;
}
}
else if (doc.containsKey("ping"))
{
else if (doc.containsKey("ping")) {
Web_SendWebsocketData(0, 20);
return false;
}
else if (doc.containsKey("controls"))
{
if (object["controls"].containsKey("set_volume"))
{
} else if (doc.containsKey("controls")) {
if (object["controls"].containsKey("set_volume")) {
uint8_t new_vol = doc["controls"]["set_volume"].as<uint8_t>();
AudioPlayer_VolumeToQueueSender(new_vol, true);
}
if (object["controls"].containsKey("action"))
{
} if (object["controls"].containsKey("action")) {
uint8_t cmd = doc["controls"]["action"].as<uint8_t>();
Cmd_Action(cmd);
}
@ -496,8 +409,7 @@ bool processJsonRequest(char *_serialJson)
}
// Sends JSON-answers via websocket
void Web_SendWebsocketData(uint32_t client, uint8_t code)
{
void Web_SendWebsocketData(uint32_t client, uint8_t code) {
char *jBuf;
jBuf = (char *)x_calloc(255, sizeof(char));
@ -505,84 +417,58 @@ void Web_SendWebsocketData(uint32_t client, uint8_t code)
StaticJsonDocument<CAPACITY> doc;
JsonObject object = doc.to<JsonObject>();
if (code == 1)
{
if (code == 1) {
object["status"] = "ok";
}
else if (code == 2)
{
} else if (code == 2) {
object["status"] = "error";
}
else if (code == 10)
{
} else if (code == 10) {
object["rfidId"] = gCurrentRfidTagId;
}
else if (code == 20)
{
} else if (code == 20) {
object["pong"] = "pong";
}
serializeJson(doc, jBuf, 255);
if (client == 0)
{
if (client == 0) {
ws.printfAll(jBuf);
}
else
{
} else {
ws.printf(client, jBuf);
}
free(jBuf);
}
// Processes websocket-requests
void onWebsocketEvent(AsyncWebSocket *server, AsyncWebSocketClient *client, AwsEventType type, void *arg, uint8_t *data, size_t len)
{
if (type == WS_EVT_CONNECT)
{
void onWebsocketEvent(AsyncWebSocket *server, AsyncWebSocketClient *client, AwsEventType type, void *arg, uint8_t *data, size_t len) {
if (type == WS_EVT_CONNECT) {
//client connected
Serial.printf("ws[%s][%u] connect\n", server->url(), client->id());
//client->printf("Hello Client %u :)", client->id());
client->ping();
}
else if (type == WS_EVT_DISCONNECT)
{
} else if (type == WS_EVT_DISCONNECT) {
//client disconnected
Serial.printf("ws[%s][%u] disconnect\n", server->url(), client->id());
}
else if (type == WS_EVT_ERROR)
{
} else if (type == WS_EVT_ERROR) {
//error was received from the other end
Serial.printf("ws[%s][%u] error(%u): %s\n", server->url(), client->id(), *((uint16_t *)arg), (char *)data);
}
else if (type == WS_EVT_PONG)
{
} else if (type == WS_EVT_PONG) {
//pong message was received (in response to a ping request maybe)
Serial.printf("ws[%s][%u] pong[%u]: %s\n", server->url(), client->id(), len, (len) ? (char *)data : "");
}
else if (type == WS_EVT_DATA)
{
} else if (type == WS_EVT_DATA) {
//data packet
AwsFrameInfo *info = (AwsFrameInfo *)arg;
if (info->final && info->index == 0 && info->len == len)
{
if (info->final && info->index == 0 && info->len == len) {
//the whole message is in a single frame and we got all of it's data
Serial.printf("ws[%s][%u] %s-message[%llu]: ", server->url(), client->id(), (info->opcode == WS_TEXT) ? "text" : "binary", info->len);
if (processJsonRequest((char *)data))
{
if (processJsonRequest((char *)data)) {
Web_SendWebsocketData(client->id(), 1);
}
if (info->opcode == WS_TEXT)
{
if (info->opcode == WS_TEXT) {
data[len] = 0;
Serial.printf("%s\n", (char *)data);
}
else
{
for (size_t i = 0; i < info->len; i++)
{
} else {
for (size_t i = 0; i < info->len; i++) {
Serial.printf("%02x ", data[i]);
}
Serial.printf("\n");
@ -593,23 +479,18 @@ void onWebsocketEvent(AsyncWebSocket *server, AsyncWebSocketClient *client, AwsE
// Handles file upload request from the explorer
// requires a GET parameter path, as directory path to the file
void explorerHandleFileUpload(AsyncWebServerRequest *request, String filename, size_t index, uint8_t *data, size_t len, bool final)
{
void explorerHandleFileUpload(AsyncWebServerRequest *request, String filename, size_t index, uint8_t *data, size_t len, bool final) {
System_UpdateActivityTimer();
// New File
if (!index)
{
if (!index) {
String utf8FilePath;
static char filePath[MAX_FILEPATH_LENTGH];
if (request->hasParam("path"))
{
if (request->hasParam("path")) {
AsyncWebParameter *param = request->getParam("path");
utf8FilePath = param->value() + "/" + filename;
}
else
{
} else {
utf8FilePath = "/" + filename;
}
@ -619,14 +500,12 @@ void explorerHandleFileUpload(AsyncWebServerRequest *request, String filename, s
Log_Println(Log_Buffer, LOGLEVEL_INFO);
// Create Ringbuffer for upload
if (explorerFileUploadRingBuffer == NULL)
{
if (explorerFileUploadRingBuffer == NULL) {
explorerFileUploadRingBuffer = xRingbufferCreate(4096, RINGBUF_TYPE_BYTEBUF);
}
// Create Queue for receiving a signal from the store task as synchronisation
if (explorerFileUploadStatusQueue == NULL)
{
if (explorerFileUploadStatusQueue == NULL) {
explorerFileUploadStatusQueue = xQueueCreate(1, sizeof(uint8_t));
}
@ -641,14 +520,12 @@ void explorerHandleFileUpload(AsyncWebServerRequest *request, String filename, s
);
}
if (len)
{
if (len) {
// stream the incoming chunk to the ringbuffer
xRingbufferSend(explorerFileUploadRingBuffer, data, len, portTICK_PERIOD_MS * 1000);
}
if (final)
{
if (final) {
// notify storage task that last data was stored on the ring buffer
xTaskNotify(fileStorageTaskHandle, 1u, eNoAction);
// watit until the storage task is sending the signal to finish
@ -660,8 +537,7 @@ void explorerHandleFileUpload(AsyncWebServerRequest *request, String filename, s
}
}
void explorerHandleFileStorageTask(void *parameter)
{
void explorerHandleFileStorageTask(void *parameter) {
File uploadFile;
size_t item_size;
@ -673,22 +549,17 @@ void explorerHandleFileStorageTask(void *parameter)
uploadFile = gFSystem.open((char *)parameter, "w");
for (;;)
{
for (;;) {
esp_task_wdt_reset();
item = (uint8_t *)xRingbufferReceive(explorerFileUploadRingBuffer, &item_size, portTICK_PERIOD_MS * 100);
if (item != NULL)
{
if (item != NULL) {
uploadFile.write(item, item_size);
vRingbufferReturnItem(explorerFileUploadRingBuffer, (void *)item);
}
else
{
} else {
// No data in the buffer, check if all data arrived for the file
uploadFileNotification = xTaskNotifyWait(0, 0, &uploadFileNotificationValue, 0);
if (uploadFileNotification == pdPASS)
{
if (uploadFileNotification == pdPASS) {
uploadFile.close();
// done exit loop to terminate
break;
@ -703,8 +574,7 @@ void explorerHandleFileStorageTask(void *parameter)
// Sends a list of the content of a directory as JSON file
// requires a GET parameter path for the directory
void explorerHandleListRequest(AsyncWebServerRequest *request)
{
void explorerHandleListRequest(AsyncWebServerRequest *request) {
DynamicJsonDocument jsonBuffer(16384);
//StaticJsonDocument<4096> jsonBuffer;
String serializedJsonString;
@ -712,26 +582,21 @@ void explorerHandleListRequest(AsyncWebServerRequest *request)
char filePath[MAX_FILEPATH_LENTGH];
JsonArray obj = jsonBuffer.createNestedArray();
File root;
if (request->hasParam("path"))
{
if (request->hasParam("path")) {
param = request->getParam("path");
convertUtf8ToAscii(param->value(), filePath);
root = gFSystem.open(filePath);
}
else
{
} else {
root = gFSystem.open("/");
}
if (!root)
{
if (!root) {
snprintf(Log_Buffer, Log_BufferLength, (char *) FPSTR(failedToOpenDirectory));
Log_Println(Log_Buffer, LOGLEVEL_DEBUG);
return;
}
if (!root.isDirectory())
{
if (!root.isDirectory()) {
snprintf(Log_Buffer, Log_BufferLength, (char *) FPSTR(notADirectory));
Log_Println(Log_Buffer, LOGLEVEL_DEBUG);
return;
@ -739,11 +604,9 @@ void explorerHandleListRequest(AsyncWebServerRequest *request)
File file = root.openNextFile();
while (file)
{
while (file) {
// ignore hidden folders, e.g. MacOS spotlight files
if (!startsWith(file.name(), (char *)"/."))
{
if (!startsWith(file.name(), (char *)"/.")) {
JsonObject entry = obj.createNestedObject();
convertAsciiToUtf8(file.name(), filePath);
std::string path = filePath;
@ -761,19 +624,14 @@ void explorerHandleListRequest(AsyncWebServerRequest *request)
request->send(200, "application/json; charset=utf-8", serializedJsonString);
}
bool explorerDeleteDirectory(File dir)
{
bool explorerDeleteDirectory(File dir) {
File file = dir.openNextFile();
while (file)
{
while (file) {
if (file.isDirectory())
{
if (file.isDirectory()) {
explorerDeleteDirectory(file);
}
else
{
} else {
gFSystem.remove(file.name());
}
@ -787,53 +645,37 @@ bool explorerDeleteDirectory(File dir)
// Handles delete request of a file or directory
// requires a GET parameter path to the file or directory
void explorerHandleDeleteRequest(AsyncWebServerRequest *request)
{
void explorerHandleDeleteRequest(AsyncWebServerRequest *request) {
File file;
AsyncWebParameter *param;
char filePath[MAX_FILEPATH_LENTGH];
if (request->hasParam("path"))
{
if (request->hasParam("path")) {
param = request->getParam("path");
convertUtf8ToAscii(param->value(), filePath);
if (gFSystem.exists(filePath))
{
if (gFSystem.exists(filePath)) {
file = gFSystem.open(filePath);
if (file.isDirectory())
{
if (explorerDeleteDirectory(file))
{
if (file.isDirectory()) {
if (explorerDeleteDirectory(file)) {
snprintf(Log_Buffer, Log_BufferLength, "DELETE: %s deleted", param->value().c_str());
Log_Println(Log_Buffer, LOGLEVEL_INFO);
}
else
{
} else {
snprintf(Log_Buffer, Log_BufferLength, "DELETE: Cannot delete %s", param->value().c_str());
Log_Println(Log_Buffer, LOGLEVEL_ERROR);
}
}
else
{
if (gFSystem.remove(filePath))
{
} else {
if (gFSystem.remove(filePath)) {
snprintf(Log_Buffer, Log_BufferLength, "DELETE: %s deleted", param->value().c_str());
Log_Println(Log_Buffer, LOGLEVEL_INFO);
}
else
{
} else {
snprintf(Log_Buffer, Log_BufferLength, "DELETE: Cannot delete %s", param->value().c_str());
Log_Println(Log_Buffer, LOGLEVEL_ERROR);
}
}
}
else
{
} else {
snprintf(Log_Buffer, Log_BufferLength, "DELETE: Path %s does not exist", param->value().c_str());
Log_Println(Log_Buffer, LOGLEVEL_ERROR);
}
}
else
{
} else {
Log_Println("DELETE: No path variable set", LOGLEVEL_ERROR);
}
request->send(200);
@ -842,27 +684,20 @@ void explorerHandleDeleteRequest(AsyncWebServerRequest *request)
// Handles create request of a directory
// requires a GET parameter path to the new directory
void explorerHandleCreateRequest(AsyncWebServerRequest *request)
{
void explorerHandleCreateRequest(AsyncWebServerRequest *request) {
AsyncWebParameter *param;
char filePath[MAX_FILEPATH_LENTGH];
if (request->hasParam("path"))
{
if (request->hasParam("path")) {
param = request->getParam("path");
convertUtf8ToAscii(param->value(), filePath);
if (gFSystem.mkdir(filePath))
{
if (gFSystem.mkdir(filePath)) {
snprintf(Log_Buffer, Log_BufferLength, "CREATE: %s created", param->value().c_str());
Log_Println(Log_Buffer, LOGLEVEL_INFO);
}
else
{
} else {
snprintf(Log_Buffer, Log_BufferLength, "CREATE: Cannot create %s", param->value().c_str());
Log_Println(Log_Buffer, LOGLEVEL_ERROR);
}
}
else
{
} else {
Log_Println("CREATE: No path variable set", LOGLEVEL_ERROR);
}
request->send(200);
@ -871,39 +706,29 @@ void explorerHandleCreateRequest(AsyncWebServerRequest *request)
// Handles rename request of a file or directory
// requires a GET parameter srcpath to the old file or directory name
// requires a GET parameter dstpath to the new file or directory name
void explorerHandleRenameRequest(AsyncWebServerRequest *request)
{
void explorerHandleRenameRequest(AsyncWebServerRequest *request) {
AsyncWebParameter *srcPath;
AsyncWebParameter *dstPath;
char srcFullFilePath[MAX_FILEPATH_LENTGH];
char dstFullFilePath[MAX_FILEPATH_LENTGH];
if (request->hasParam("srcpath") && request->hasParam("dstpath"))
{
if (request->hasParam("srcpath") && request->hasParam("dstpath")) {
srcPath = request->getParam("srcpath");
dstPath = request->getParam("dstpath");
convertUtf8ToAscii(srcPath->value(), srcFullFilePath);
convertUtf8ToAscii(dstPath->value(), dstFullFilePath);
if (gFSystem.exists(srcFullFilePath))
{
if (gFSystem.rename(srcFullFilePath, dstFullFilePath))
{
if (gFSystem.exists(srcFullFilePath)) {
if (gFSystem.rename(srcFullFilePath, dstFullFilePath)) {
snprintf(Log_Buffer, Log_BufferLength, "RENAME: %s renamed to %s", srcPath->value().c_str(), dstPath->value().c_str());
Log_Println(Log_Buffer, LOGLEVEL_INFO);
}
else
{
} else {
snprintf(Log_Buffer, Log_BufferLength, "RENAME: Cannot rename %s", srcPath->value().c_str());
Log_Println(Log_Buffer, LOGLEVEL_ERROR);
}
}
else
{
} else {
snprintf(Log_Buffer, Log_BufferLength, "RENAME: Path %s does not exist", srcPath->value().c_str());
Log_Println(Log_Buffer, LOGLEVEL_ERROR);
}
}
else
{
} else {
Log_Println("RENAME: No path variable set", LOGLEVEL_ERROR);
}
@ -913,14 +738,12 @@ void explorerHandleRenameRequest(AsyncWebServerRequest *request)
// Handles audio play requests
// requires a GET parameter path to the audio file or directory
// requires a GET parameter playmode
void explorerHandleAudioRequest(AsyncWebServerRequest *request)
{
void explorerHandleAudioRequest(AsyncWebServerRequest *request) {
AsyncWebParameter *param;
String playModeString;
uint32_t playMode;
char filePath[MAX_FILEPATH_LENTGH];
if (request->hasParam("path") && request->hasParam("playmode"))
{
if (request->hasParam("path") && request->hasParam("playmode")) {
param = request->getParam("path");
convertUtf8ToAscii(param->value(), filePath);
param = request->getParam("playmode");
@ -928,9 +751,7 @@ void explorerHandleAudioRequest(AsyncWebServerRequest *request)
playMode = atoi(playModeString.c_str());
AudioPlayer_TrackQueueDispatcher(filePath, 0, playMode, 0);
}
else
{
} else {
Log_Println("AUDIO: No path variable set", LOGLEVEL_ERROR);
}
@ -938,8 +759,7 @@ void explorerHandleAudioRequest(AsyncWebServerRequest *request)
}
// Handles uploaded backup-file and writes valid entries into NVS
void handleUpload(AsyncWebServerRequest *request, String filename, size_t index, uint8_t *data, size_t len, bool final)
{
void handleUpload(AsyncWebServerRequest *request, String filename, size_t index, uint8_t *data, size_t len, bool final) {
Led_SetPause(true); // Workaround to prevent exceptions due to Neopixel-signalisation while NVS-write
char ebuf[290];
uint16_t j = 0;
@ -947,35 +767,26 @@ void handleUpload(AsyncWebServerRequest *request, String filename, size_t index,
uint8_t count = 0;
nvs_t nvsEntry[1];
for (size_t i = 0; i < len; i++)
{
if (data[i] != '\n')
{
for (size_t i = 0; i < len; i++) {
if (data[i] != '\n') {
ebuf[j++] = data[i];
}
else
{
} else {
ebuf[j] = '\0';
j = 0;
token = strtok(ebuf, stringOuterDelimiter);
while (token != NULL)
{
if (!count)
{
while (token != NULL) {
if (!count) {
count++;
memcpy(nvsEntry[0].nvsKey, token, strlen(token));
nvsEntry[0].nvsKey[strlen(token)] = '\0';
}
else if (count == 1)
{
} else if (count == 1) {
count = 0;
memcpy(nvsEntry[0].nvsEntry, token, strlen(token));
nvsEntry[0].nvsEntry[strlen(token)] = '\0';
}
token = strtok(NULL, stringOuterDelimiter);
}
if (isNumber(nvsEntry[0].nvsKey) && nvsEntry[0].nvsEntry[0] == '#')
{
if (isNumber(nvsEntry[0].nvsKey) && nvsEntry[0].nvsEntry[0] == '#') {
snprintf(Log_Buffer, Log_BufferLength, "%s: %s => %s", (char *) FPSTR(writeEntryToNvs), nvsEntry[0].nvsKey, nvsEntry[0].nvsEntry);
Log_Println(Log_Buffer, LOGLEVEL_NOTICE);
gPrefsRfid.putString(nvsEntry[0].nvsKey, nvsEntry[0].nvsEntry);
@ -986,8 +797,7 @@ void handleUpload(AsyncWebServerRequest *request, String filename, size_t index,
}
// Dumps all RFID-entries from NVS into a file on SD-card
bool Web_DumpNvsToSd(const char *_namespace, const char *_destFile)
{
bool Web_DumpNvsToSd(const char *_namespace, const char *_destFile) {
Led_SetPause(true); // Workaround to prevent exceptions due to Neopixel-signalisation while NVS-write
esp_partition_iterator_t pi; // Iterator for find
const esp_partition_t *nvs; // Pointer to partition struct
@ -1002,31 +812,25 @@ bool Web_DumpNvsToSd(const char *_namespace, const char *_destFile)
pi = esp_partition_find(ESP_PARTITION_TYPE_DATA, // Get partition iterator for
ESP_PARTITION_SUBTYPE_ANY, // this partition
partname);
if (pi)
{
if (pi) {
nvs = esp_partition_get(pi); // Get partition struct
esp_partition_iterator_release(pi); // Release the iterator
dbgprint("Partition %s found, %d bytes", partname, nvs->size);
}
else
{
} else {
snprintf(Log_Buffer, Log_BufferLength, "Partition %s not found!", partname);
Log_Println(Log_Buffer, LOGLEVEL_ERROR);
return NULL;
}
namespace_ID = FindNsID(nvs, _namespace); // Find ID of our namespace in NVS
File backupFile = gFSystem.open(_destFile, FILE_WRITE);
if (!backupFile)
{
if (!backupFile) {
return false;
}
while (offset < nvs->size)
{
while (offset < nvs->size) {
result = esp_partition_read(nvs, offset, // Read 1 page in nvs partition
&buf,
sizeof(nvs_page));
if (result != ESP_OK)
{
if (result != ESP_OK) {
snprintf(Log_Buffer, Log_BufferLength, "Error reading NVS!");
Log_Println(Log_Buffer, LOGLEVEL_ERROR);
return false;
@ -1034,24 +838,18 @@ bool Web_DumpNvsToSd(const char *_namespace, const char *_destFile)
i = 0;
while (i < 126)
{
while (i < 126) {
bm = (buf.Bitmap[i / 4] >> ((i % 4) * 2)) & 0x03; // Get bitmap for this entry
if (bm == 2)
{
if (bm == 2) {
if ((namespace_ID == 0xFF) || // Show all if ID = 0xFF
(buf.Entry[i].Ns == namespace_ID))
{ // otherwise just my namespace
if (isNumber(buf.Entry[i].Key))
{
(buf.Entry[i].Ns == namespace_ID)) { // otherwise just my namespace
if (isNumber(buf.Entry[i].Key)) {
String s = gPrefsRfid.getString((const char *)buf.Entry[i].Key);
backupFile.printf("%s%s%s%s\n", stringOuterDelimiter, buf.Entry[i].Key, stringOuterDelimiter, s.c_str());
}
}
i += buf.Entry[i].Span; // Next entry
}
else
{
} else {
i++;
}
}

81
src/Wlan.cpp

@ -25,30 +25,24 @@ void accessPointStart(const char *SSID, IPAddress ip, IPAddress netmask);
bool getWifiEnableStatusFromNVS(void);
void writeWifiStatusToNVS(bool wifiStatus);
void Wlan_Init(void)
{
void Wlan_Init(void) {
wifiEnabled = getWifiEnableStatusFromNVS();
}
void Wlan_Cyclic(void)
{
void Wlan_Cyclic(void) {
// If wifi whould not be activated, return instantly
if (!wifiEnabled)
{
if (!wifiEnabled) {
return;
}
if (!wifiCheckLastTimestamp || wifiNeedsRestart)
{
if (!wifiCheckLastTimestamp || wifiNeedsRestart) {
// Get credentials from NVS
String strSSID = gPrefsSettings.getString("SSID", "-1");
if (!strSSID.compareTo("-1"))
{
if (!strSSID.compareTo("-1")) {
Log_Println((char *) FPSTR(ssidNotFoundInNvs), LOGLEVEL_ERROR);
}
String strPassword = gPrefsSettings.getString("Password", "-1");
if (!strPassword.compareTo("-1"))
{
if (!strPassword.compareTo("-1")) {
Log_Println((char *) FPSTR(wifiPwdNotFoundInNvs), LOGLEVEL_ERROR);
}
const char *_ssid = strSSID.c_str();
@ -56,15 +50,12 @@ void Wlan_Cyclic(void)
// Get (optional) hostname-configration from NVS
String hostname = gPrefsSettings.getString("Hostname", "-1");
if (hostname.compareTo("-1"))
{
if (hostname.compareTo("-1")) {
//WiFi.config(INADDR_NONE, INADDR_NONE, INADDR_NONE);
WiFi.setHostname(hostname.c_str());
snprintf(Log_Buffer, Log_BufferLength, "%s: %s", (char *) FPSTR(restoredHostnameFromNvs), hostname.c_str());
Log_Println(Log_Buffer, LOGLEVEL_INFO);
}
else
{
} else {
Log_Println((char *) FPSTR(wifiHostnameNotSet), LOGLEVEL_INFO);
}
@ -72,8 +63,7 @@ void Wlan_Cyclic(void)
#ifdef STATIC_IP_ENABLE
snprintf(Log_Buffer, Log_BufferLength, "%s", (char *) FPSTR(tryStaticIpConfig));
Log_Println(Log_Buffer, LOGLEVEL_NOTICE);
if (!WiFi.config(IPAddress(LOCAL_IP), IPAddress(GATEWAY_IP), IPAddress(SUBNET_IP), IPAddress(DNS_IP)))
{
if (!WiFi.config(IPAddress(LOCAL_IP), IPAddress(GATEWAY_IP), IPAddress(SUBNET_IP), IPAddress(DNS_IP))) {
snprintf(Log_Buffer, Log_BufferLength, "%s", (char *) FPSTR(staticIPConfigFailed));
Log_Println(Log_Buffer, LOGLEVEL_ERROR);
}
@ -83,20 +73,17 @@ void Wlan_Cyclic(void)
WiFi.begin(_ssid, _pwd);
uint8_t tryCount = 0;
while (WiFi.status() != WL_CONNECTED && tryCount <= 4)
{
while (WiFi.status() != WL_CONNECTED && tryCount <= 4) {
delay(500);
Serial.print(F("."));
tryCount++;
wifiCheckLastTimestamp = millis();
if (tryCount >= 4 && WiFi.status() == WL_CONNECT_FAILED)
{
if (tryCount >= 4 && WiFi.status() == WL_CONNECT_FAILED) {
WiFi.begin(_ssid, _pwd); // ESP32-workaround (otherwise WiFi-connection sometimes fails)
}
}
if (WiFi.status() == WL_CONNECTED)
{
if (WiFi.status() == WL_CONNECTED) {
IPAddress myIP = WiFi.localIP();
#if (LANGUAGE == 1)
snprintf(Log_Buffer, Log_BufferLength, "Aktuelle IP: %d.%d.%d.%d", myIP[0], myIP[1], myIP[2], myIP[3]);
@ -104,16 +91,13 @@ void Wlan_Cyclic(void)
snprintf(Log_Buffer, Log_BufferLength, "Current IP: %d.%d.%d.%d", myIP[0], myIP[1], myIP[2], myIP[3]);
#endif
Log_Println(Log_Buffer, LOGLEVEL_NOTICE);
}
else
{ // Starts AP if WiFi-connect wasn't successful
} else { // Starts AP if WiFi-connect wasn't successful
accessPointStart((char *) FPSTR(accessPointNetworkSSID), apIP, apNetmask);
}
#ifdef MDNS_ENABLE
// zero conf, make device available as <hostname>.local
if (MDNS.begin(hostname.c_str()))
{
if (MDNS.begin(hostname.c_str())) {
MDNS.addService("http", "tcp", 80);
}
#endif
@ -122,19 +106,16 @@ void Wlan_Cyclic(void)
}
}
void Wlan_ToggleEnable(void)
{
void Wlan_ToggleEnable(void) {
writeWifiStatusToNVS(!getWifiEnableStatusFromNVS());
}
String Wlan_GetIpAddress(void)
{
String Wlan_GetIpAddress(void) {
return WiFi.localIP().toString();
}
// Initialize soft access-point
void accessPointStart(const char *SSID, IPAddress ip, IPAddress netmask)
{
void accessPointStart(const char *SSID, IPAddress ip, IPAddress netmask) {
WiFi.mode(WIFI_AP);
WiFi.softAPConfig(ip, ip, netmask);
WiFi.softAP(SSID);
@ -150,13 +131,11 @@ void accessPointStart(const char *SSID, IPAddress ip, IPAddress netmask)
}
// Reads stored WiFi-status from NVS
bool getWifiEnableStatusFromNVS(void)
{
bool getWifiEnableStatusFromNVS(void) {
uint32_t wifiStatus = gPrefsSettings.getUInt("enableWifi", 99);
// if not set so far, preseed with 1 (enable)
if (wifiStatus == 99)
{
if (wifiStatus == 99) {
gPrefsSettings.putUInt("enableWifi", 1);
wifiStatus = 1;
}
@ -165,26 +144,19 @@ bool getWifiEnableStatusFromNVS(void)
}
// Writes to NVS whether WiFi should be activated
void writeWifiStatusToNVS(bool wifiStatus)
{
if (!wifiStatus)
{
if (gPrefsSettings.putUInt("enableWifi", 0))
{ // disable
void writeWifiStatusToNVS(bool wifiStatus) {
if (!wifiStatus) {
if (gPrefsSettings.putUInt("enableWifi", 0)) { // disable
Log_Println((char *) FPSTR(wifiDisabledAfterRestart), LOGLEVEL_NOTICE);
if (gPlayProperties.playMode == WEBSTREAM)
{
if (gPlayProperties.playMode == WEBSTREAM) {
AudioPlayer_TrackControlToQueueSender(STOP);
}
delay(300);
WiFi.mode(WIFI_OFF);
wifiEnabled = false;
}
}
else
{
if (gPrefsSettings.putUInt("enableWifi", 1))
{ // enable
} else {
if (gPrefsSettings.putUInt("enableWifi", 1)) { // enable
Log_Println((char *) FPSTR(wifiEnabledAfterRestart), LOGLEVEL_NOTICE);
wifiNeedsRestart = true;
wifiEnabled = true;
@ -192,7 +164,6 @@ void writeWifiStatusToNVS(bool wifiStatus)
}
}
bool Wlan_IsConnected(void)
{
bool Wlan_IsConnected(void) {
return (WiFi.status() == WL_CONNECTED);
}

57
src/main.cpp

@ -43,25 +43,19 @@ TwoWire i2cBusTwo = TwoWire(1);
#ifdef PLAY_LAST_RFID_AFTER_REBOOT
// Get last RFID-tag applied from NVS
void recoverLastRfidPlayed(void)
{
if (recoverLastRfid)
{
if (System_GetOperationMode() == OPMODE_BLUETOOTH)
{ // Don't recover if BT-mode is desired
void recoverLastRfidPlayed(void) {
if (recoverLastRfid) {
if (System_GetOperationMode() == OPMODE_BLUETOOTH) { // Don't recover if BT-mode is desired
recoverLastRfid = false;
return;
}
recoverLastRfid = false;
String lastRfidPlayed = gPrefsSettings.getString("lastRfid", "-1");
if (!lastRfidPlayed.compareTo("-1"))
{
if (!lastRfidPlayed.compareTo("-1")) {
Log_Println((char *) FPSTR(unableToRestoreLastRfidFromNVS), LOGLEVEL_INFO);
}
else
{
} else {
char *lastRfid = x_strdup(lastRfidPlayed.c_str());
xQueueSend(gRfidCardQueue, &lastRfid, 0);
xQueueSend(gRfidCardQueue, lastRfid, 0);
snprintf(Log_Buffer, Log_BufferLength, "%s: %s", (char *) FPSTR(restoredLastRfidFromNVS), lastRfidPlayed.c_str());
Log_Println(Log_Buffer, LOGLEVEL_INFO);
}
@ -70,13 +64,11 @@ void recoverLastRfidPlayed(void)
#endif
// Print the wake-up reason why ESP32 is awake now
void printWakeUpReason()
{
void printWakeUpReason() {
esp_sleep_wakeup_cause_t wakeup_reason;
wakeup_reason = esp_sleep_get_wakeup_cause();
switch (wakeup_reason)
{
switch (wakeup_reason) {
case ESP_SLEEP_WAKEUP_EXT0:
Serial.println(F("Wakeup caused by push button"));
break;
@ -126,8 +118,7 @@ void setup()
#if (HAL == 2)
i2cBusOne.begin(IIC_DATA, IIC_CLK, 40000);
while (not ac.begin())
{
while (not ac.begin()) {
Serial.println(F("AC101 Failed!"));
delay(1000);
}
@ -166,20 +157,13 @@ void setup()
// show SD card type
sdcard_type_t cardType = SdCard_GetType();
Serial.print(F("SD card type: "));
if (cardType == CARD_MMC)
{
if (cardType == CARD_MMC) {
Serial.println(F("MMC"));
}
else if (cardType == CARD_SD)
{
} else if (cardType == CARD_SD) {
Serial.println(F("SDSC"));
}
else if (cardType == CARD_SDHC)
{
} else if (cardType == CARD_SDHC) {
Serial.println(F("SDHC"));
}
else
{
} else {
Serial.println(F("UNKNOWN"));
}
@ -194,15 +178,12 @@ void setup()
Wlan_Init();
Bluetooth_Init();
if (OPMODE_NORMAL == System_GetOperationMode())
{
if (OPMODE_NORMAL == System_GetOperationMode()) {
Wlan_Cyclic();
}
IrReceiver_Init();
System_UpdateActivityTimer(); // initial set after boot
Led_Indicate(LedIndicatorType::BootComplete);
snprintf(Log_Buffer, Log_BufferLength, "%s: %u", (char *) FPSTR(freeHeapAfterSetup), ESP.getFreeHeap());
@ -210,16 +191,12 @@ void setup()
Serial.printf("PSRAM: %u bytes\n", ESP.getPsramSize());
}
void loop()
{
void loop() {
Rfid_Cyclic();
if (OPMODE_BLUETOOTH == System_GetOperationMode())
{
if (OPMODE_BLUETOOTH == System_GetOperationMode()) {
Bluetooth_Cyclic();
}
else
{
} else {
Wlan_Cyclic();
Web_Cyclic();
Ftp_Cyclic();

Loading…
Cancel
Save