diff --git a/src/AudioPlayer.cpp b/src/AudioPlayer.cpp index f8fa029..46a9695 100644 --- a/src/AudioPlayer.cpp +++ b/src/AudioPlayer.cpp @@ -31,9 +31,9 @@ static uint8_t AudioPlayer_MinVolume = AUDIOPLAYER_VOLUME_MIN; static uint8_t AudioPlayer_InitVolume = AUDIOPLAYER_VOLUME_INIT; #ifdef HEADPHONE_ADJUST_ENABLE -static bool AudioPlayer_HeadphoneLastDetectionState; -static uint32_t AudioPlayer_HeadphoneLastDetectionTimestamp = 0u; -static uint8_t AudioPlayer_MaxVolumeHeadphone = 11u; // Maximum volume that can be adjusted in headphone-mode (default; can be changed later via GUI) + static bool AudioPlayer_HeadphoneLastDetectionState; + static uint32_t AudioPlayer_HeadphoneLastDetectionTimestamp = 0u; + static uint8_t AudioPlayer_MaxVolumeHeadphone = 11u; // Maximum volume that can be adjusted in headphone-mode (default; can be changed later via GUI) #endif static void AudioPlayer_Task(void *parameter); @@ -44,69 +44,57 @@ static void AudioPlayer_SortPlaylist(const char **arr, int n); static void AudioPlayer_SortPlaylist(char *str[], const uint32_t count); static size_t AudioPlayer_NvsRfidWriteWrapper(const char *_rfidCardId, const char *_track, const uint32_t _playPosition, const uint8_t _playMode, const uint16_t _trackLastPlayed, const uint16_t _numberOfTracks); -void AudioPlayer_Init(void) -{ -#ifndef USE_LAST_VOLUME_AFTER_REBOOT - // Get initial volume from NVS - uint32_t nvsInitialVolume = gPrefsSettings.getUInt("initVolume", 0); -#else - // Get volume used at last shutdown - uint32_t nvsInitialVolume = gPrefsSettings.getUInt("previousVolume", 999); - if (nvsInitialVolume == 999) - { - gPrefsSettings.putUInt("previousVolume", AudioPlayer_GetInitVolume()); - nvsInitialVolume = AudioPlayer_GetInitVolume(); - } - else - { - Log_Println((char *)FPSTR(rememberLastVolume), LOGLEVEL_ERROR); - } -#endif - if (nvsInitialVolume) - { +void AudioPlayer_Init(void) { + #ifndef USE_LAST_VOLUME_AFTER_REBOOT + // Get initial volume from NVS + uint32_t nvsInitialVolume = gPrefsSettings.getUInt("initVolume", 0); + #else + // Get volume used at last shutdown + uint32_t nvsInitialVolume = gPrefsSettings.getUInt("previousVolume", 999); + if (nvsInitialVolume == 999) { + gPrefsSettings.putUInt("previousVolume", AudioPlayer_GetInitVolume()); + nvsInitialVolume = AudioPlayer_GetInitVolume(); + } else { + Log_Println((char *) FPSTR(rememberLastVolume), LOGLEVEL_ERROR); + } + #endif + + if (nvsInitialVolume) { AudioPlayer_SetInitVolume(nvsInitialVolume); - snprintf(Log_Buffer, Log_BufferLength, "%s: %u", (char *)FPSTR(restoredInitialLoudnessFromNvs), nvsInitialVolume); + snprintf(Log_Buffer, Log_BufferLength, "%s: %u", (char *) FPSTR(restoredInitialLoudnessFromNvs), nvsInitialVolume); Log_Println(Log_Buffer, LOGLEVEL_INFO); - } - else - { + } else { gPrefsSettings.putUInt("initVolume", AudioPlayer_GetInitVolume()); - Log_Println((char *)FPSTR(wroteInitialLoudnessToNvs), LOGLEVEL_ERROR); + Log_Println((char *) FPSTR(wroteInitialLoudnessToNvs), LOGLEVEL_ERROR); } // Get maximum volume for speaker from NVS uint32_t nvsMaxVolumeSpeaker = gPrefsSettings.getUInt("maxVolumeSp", 0); - if (nvsMaxVolumeSpeaker) - { + if (nvsMaxVolumeSpeaker) { AudioPlayer_SetMaxVolumeSpeaker(nvsMaxVolumeSpeaker); AudioPlayer_SetMaxVolume(nvsMaxVolumeSpeaker); - snprintf(Log_Buffer, Log_BufferLength, "%s: %u", (char *)FPSTR(restoredMaxLoudnessForSpeakerFromNvs), nvsMaxVolumeSpeaker); + snprintf(Log_Buffer, Log_BufferLength, "%s: %u", (char *) FPSTR(restoredMaxLoudnessForSpeakerFromNvs), nvsMaxVolumeSpeaker); Log_Println(Log_Buffer, LOGLEVEL_INFO); - } - else - { + } else { gPrefsSettings.putUInt("maxVolumeSp", nvsMaxVolumeSpeaker); - Log_Println((char *)FPSTR(wroteMaxLoudnessForSpeakerToNvs), LOGLEVEL_ERROR); + Log_Println((char *) FPSTR(wroteMaxLoudnessForSpeakerToNvs), LOGLEVEL_ERROR); } -#ifdef HEADPHONE_ADJUST_ENABLE - pinMode(HP_DETECT, INPUT); - AudioPlayer_HeadphoneLastDetectionState = Port_Read(HP_DETECT); - - // Get maximum volume for headphone from NVS - uint32_t nvsAudioPlayer_MaxVolumeHeadphone = gPrefsSettings.getUInt("maxVolumeHp", 0); - if (nvsAudioPlayer_MaxVolumeHeadphone) - { - AudioPlayer_MaxVolumeHeadphone = nvsAudioPlayer_MaxVolumeHeadphone; - snprintf(Log_Buffer, Log_BufferLength, "%s: %u", (char *)FPSTR(restoredMaxLoudnessForHeadphoneFromNvs), nvsAudioPlayer_MaxVolumeHeadphone); - Log_Println(Log_Buffer, LOGLEVEL_INFO); - } - else - { - gPrefsSettings.putUInt("maxVolumeHp", nvsAudioPlayer_MaxVolumeHeadphone); - Log_Println((char *)FPSTR(wroteMaxLoudnessForHeadphoneToNvs), LOGLEVEL_ERROR); - } -#endif + #ifdef HEADPHONE_ADJUST_ENABLE + pinMode(HP_DETECT, INPUT); + AudioPlayer_HeadphoneLastDetectionState = Port_Read(HP_DETECT); + + // Get maximum volume for headphone from NVS + uint32_t nvsAudioPlayer_MaxVolumeHeadphone = gPrefsSettings.getUInt("maxVolumeHp", 0); + if (nvsAudioPlayer_MaxVolumeHeadphone) { + AudioPlayer_MaxVolumeHeadphone = nvsAudioPlayer_MaxVolumeHeadphone; + snprintf(Log_Buffer, Log_BufferLength, "%s: %u", (char *) FPSTR(restoredMaxLoudnessForHeadphoneFromNvs), nvsAudioPlayer_MaxVolumeHeadphone); + Log_Println(Log_Buffer, LOGLEVEL_INFO); + } else { + gPrefsSettings.putUInt("maxVolumeHp", nvsAudioPlayer_MaxVolumeHeadphone); + Log_Println((char *) FPSTR(wroteMaxLoudnessForHeadphoneToNvs), LOGLEVEL_ERROR); + } + #endif // Adjust volume depending on headphone is connected and volume-adjustment is enabled AudioPlayer_SetupVolume(); @@ -121,131 +109,108 @@ void AudioPlayer_Init(void) ); } -void AudioPlayer_Cyclic(void) -{ +void AudioPlayer_Cyclic(void) { AudioPlayer_HeadphoneVolumeManager(); } -uint8_t AudioPlayer_GetCurrentVolume(void) -{ +uint8_t AudioPlayer_GetCurrentVolume(void) { return AudioPlayer_CurrentVolume; } -void AudioPlayer_SetCurrentVolume(uint8_t value) -{ +void AudioPlayer_SetCurrentVolume(uint8_t value) { AudioPlayer_CurrentVolume = value; } -uint8_t AudioPlayer_GetMaxVolume(void) -{ +uint8_t AudioPlayer_GetMaxVolume(void) { return AudioPlayer_MaxVolume; } -void AudioPlayer_SetMaxVolume(uint8_t value) -{ +void AudioPlayer_SetMaxVolume(uint8_t value) { AudioPlayer_MaxVolume = value; } -uint8_t AudioPlayer_GetMaxVolumeSpeaker(void) -{ +uint8_t AudioPlayer_GetMaxVolumeSpeaker(void) { return AudioPlayer_MaxVolumeSpeaker; } -void AudioPlayer_SetMaxVolumeSpeaker(uint8_t value) -{ +void AudioPlayer_SetMaxVolumeSpeaker(uint8_t value) { AudioPlayer_MaxVolumeSpeaker = value; } -uint8_t AudioPlayer_GetMinVolume(void) -{ +uint8_t AudioPlayer_GetMinVolume(void) { return AudioPlayer_MinVolume; } -void AudioPlayer_SetMinVolume(uint8_t value) -{ +void AudioPlayer_SetMinVolume(uint8_t value) { AudioPlayer_MinVolume = value; } -uint8_t AudioPlayer_GetInitVolume(void) -{ +uint8_t AudioPlayer_GetInitVolume(void) { return AudioPlayer_InitVolume; } -void AudioPlayer_SetInitVolume(uint8_t value) -{ +void AudioPlayer_SetInitVolume(uint8_t value) { AudioPlayer_InitVolume = value; } // Set maxVolume depending on headphone-adjustment is enabled and headphone is/is not connected -void AudioPlayer_SetupVolume(void) -{ -#ifndef HEADPHONE_ADJUST_ENABLE - AudioPlayer_MaxVolume = AudioPlayer_MaxVolumeSpeaker; - return; -#else - if (Port_Read(HP_DETECT)) - { - AudioPlayer_MaxVolume = AudioPlayer_MaxVolumeSpeaker; // 1 if headphone is not connected -#ifdef PLAY_MONO_SPEAKER - gPlayProperties.newPlayMono = true; -#else - gPlayProperties.newPlayMono = false; -#endif - } - else - { - AudioPlayer_MaxVolume = AudioPlayer_MaxVolumeHeadphone; // 0 if headphone is connected (put to GND) - gPlayProperties.newPlayMono = false; // always stereo for headphones! - } - snprintf(Log_Buffer, Log_BufferLength, "%s: %u", (char *)FPSTR(maxVolumeSet), AudioPlayer_MaxVolume); - Log_Println(Log_Buffer, LOGLEVEL_INFO); - return; -#endif -} - -void AudioPlayer_HeadphoneVolumeManager(void) -{ -#ifdef HEADPHONE_ADJUST_ENABLE - bool currentHeadPhoneDetectionState = Port_Read(HP_DETECT); - - if (AudioPlayer_HeadphoneLastDetectionState != currentHeadPhoneDetectionState && (millis() - AudioPlayer_HeadphoneLastDetectionTimestamp >= headphoneLastDetectionDebounce)) - { - if (currentHeadPhoneDetectionState) - { - AudioPlayer_MaxVolume = AudioPlayer_MaxVolumeSpeaker; -#ifdef PLAY_MONO_SPEAKER - gPlayProperties.newPlayMono = true; -#else - gPlayProperties.newPlayMono = false; -#endif +void AudioPlayer_SetupVolume(void) { + #ifndef HEADPHONE_ADJUST_ENABLE + AudioPlayer_MaxVolume = AudioPlayer_MaxVolumeSpeaker; + return; + #else + if (Port_Read(HP_DETECT)) { + AudioPlayer_MaxVolume = AudioPlayer_MaxVolumeSpeaker; // 1 if headphone is not connected + #ifdef PLAY_MONO_SPEAKER + gPlayProperties.newPlayMono = true; + #else + gPlayProperties.newPlayMono = false; + #endif + } else { + AudioPlayer_MaxVolume = AudioPlayer_MaxVolumeHeadphone; // 0 if headphone is connected (put to GND) + gPlayProperties.newPlayMono = false; // always stereo for headphones! } - else - { - AudioPlayer_MaxVolume = AudioPlayer_MaxVolumeHeadphone; - gPlayProperties.newPlayMono = false; // Always stereo for headphones - if (AudioPlayer_GetCurrentVolume() > AudioPlayer_MaxVolume) - { - AudioPlayer_VolumeToQueueSender(AudioPlayer_MaxVolume, true); // Lower volume for headphone if headphone's maxvolume is exceeded by volume set in speaker-mode + snprintf(Log_Buffer, Log_BufferLength, "%s: %u", (char *) FPSTR(maxVolumeSet), AudioPlayer_MaxVolume); + Log_Println(Log_Buffer, LOGLEVEL_INFO); + return; + #endif +} + +void AudioPlayer_HeadphoneVolumeManager(void) { + #ifdef HEADPHONE_ADJUST_ENABLE + bool currentHeadPhoneDetectionState = Port_Read(HP_DETECT); + + if (AudioPlayer_HeadphoneLastDetectionState != currentHeadPhoneDetectionState && (millis() - AudioPlayer_HeadphoneLastDetectionTimestamp >= headphoneLastDetectionDebounce)) { + if (currentHeadPhoneDetectionState) { + AudioPlayer_MaxVolume = AudioPlayer_MaxVolumeSpeaker; + #ifdef PLAY_MONO_SPEAKER + gPlayProperties.newPlayMono = true; + #else + gPlayProperties.newPlayMono = false; + #endif + } else { + AudioPlayer_MaxVolume = AudioPlayer_MaxVolumeHeadphone; + gPlayProperties.newPlayMono = false; // Always stereo for headphones + if (AudioPlayer_GetCurrentVolume() > AudioPlayer_MaxVolume) { + AudioPlayer_VolumeToQueueSender(AudioPlayer_MaxVolume, true); // Lower volume for headphone if headphone's maxvolume is exceeded by volume set in speaker-mode + } } + AudioPlayer_HeadphoneLastDetectionState = currentHeadPhoneDetectionState; + AudioPlayer_HeadphoneLastDetectionTimestamp = millis(); + snprintf(Log_Buffer, Log_BufferLength, "%s: %u", (char *) FPSTR(maxVolumeSet), AudioPlayer_MaxVolume); + Log_Println(Log_Buffer, LOGLEVEL_INFO); } - AudioPlayer_HeadphoneLastDetectionState = currentHeadPhoneDetectionState; - AudioPlayer_HeadphoneLastDetectionTimestamp = millis(); - snprintf(Log_Buffer, Log_BufferLength, "%s: %u", (char *)FPSTR(maxVolumeSet), AudioPlayer_MaxVolume); - Log_Println(Log_Buffer, LOGLEVEL_INFO); - } -#endif + #endif } // Function to play music as task -void AudioPlayer_Task(void *parameter) -{ +void AudioPlayer_Task(void *parameter) { static Audio audio; uint8_t settleCount = 0; audio.setPinout(I2S_BCLK, I2S_LRC, I2S_DOUT); audio.setVolume(AudioPlayer_GetInitVolume()); audio.forceMono(gPlayProperties.currentPlayMono); - if (gPlayProperties.currentPlayMono) - { + if (gPlayProperties.currentPlayMono) { audio.setTone(3, 0, 0); } @@ -254,292 +219,243 @@ void AudioPlayer_Task(void *parameter) static uint8_t trackCommand = 0; bool audioReturnCode; - for (;;) - { - if (xQueueReceive(gVolumeQueue, ¤tVolume, 0) == pdPASS) - { - snprintf(Log_Buffer, Log_BufferLength, "%s: %d", (char *)FPSTR(newLoudnessReceivedQueue), currentVolume); + for (;;) { + if (xQueueReceive(gVolumeQueue, ¤tVolume, 0) == pdPASS) { + snprintf(Log_Buffer, Log_BufferLength, "%s: %d", (char *) FPSTR(newLoudnessReceivedQueue), currentVolume); Log_Println(Log_Buffer, LOGLEVEL_INFO); audio.setVolume(currentVolume); -#ifdef MQTT_ENABLE - publishMqtt((char *)FPSTR(topicLoudnessState), currentVolume, false); -#endif + #ifdef MQTT_ENABLE + publishMqtt((char *) FPSTR(topicLoudnessState), currentVolume, false); + #endif } - if (xQueueReceive(gTrackControlQueue, &trackCommand, 0) == pdPASS) - { - snprintf(Log_Buffer, Log_BufferLength, "%s: %d", (char *)FPSTR(newCntrlReceivedQueue), trackCommand); + if (xQueueReceive(gTrackControlQueue, &trackCommand, 0) == pdPASS) { + snprintf(Log_Buffer, Log_BufferLength, "%s: %d", (char *) FPSTR(newCntrlReceivedQueue), trackCommand); Log_Println(Log_Buffer, LOGLEVEL_INFO); } trackQStatus = xQueueReceive(gTrackQueue, &gPlayProperties.playlist, 0); - if (trackQStatus == pdPASS || gPlayProperties.trackFinished || trackCommand != 0) - { - if (trackQStatus == pdPASS) - { - if (gPlayProperties.pausePlay) - { + if (trackQStatus == pdPASS || gPlayProperties.trackFinished || trackCommand != 0) { + if (trackQStatus == pdPASS) { + if (gPlayProperties.pausePlay) { gPlayProperties.pausePlay = !gPlayProperties.pausePlay; } audio.stopSong(); -#if (LANGUAGE == 1) - snprintf(Log_Buffer, Log_BufferLength, "%s mit %d Titel(n)", (char *)FPSTR(newPlaylistReceived), gPlayProperties.numberOfTracks); -#else - snprintf(Log_Buffer, Log_BufferLength, "%s with %d track(s)", (char *)FPSTR(newPlaylistReceived), gPlayProperties.numberOfTracks); -#endif + #if (LANGUAGE == 1) + snprintf(Log_Buffer, Log_BufferLength, "%s mit %d Titel(n)", (char *) FPSTR(newPlaylistReceived), gPlayProperties.numberOfTracks); + #else + snprintf(Log_Buffer, Log_BufferLength, "%s with %d track(s)", (char *) FPSTR(newPlaylistReceived), gPlayProperties.numberOfTracks); + #endif Log_Println(Log_Buffer, LOGLEVEL_NOTICE); Serial.print(F("Free heap: ")); Serial.println(ESP.getFreeHeap()); // If we're in audiobook-mode and apply a modification-card, we don't // want to save lastPlayPosition for the mod-card but for the card that holds the playlist - if (gCurrentRfidTagId != NULL) - { + if (gCurrentRfidTagId != NULL) { strncpy(gPlayProperties.playRfidTag, gCurrentRfidTagId, sizeof(gPlayProperties.playRfidTag) / sizeof(gPlayProperties.playRfidTag[0])); } } - if (gPlayProperties.trackFinished) - { + if (gPlayProperties.trackFinished) { gPlayProperties.trackFinished = false; - if (gPlayProperties.playMode == NO_PLAYLIST) - { + if (gPlayProperties.playMode == NO_PLAYLIST) { gPlayProperties.playlistFinished = true; continue; } - if (gPlayProperties.saveLastPlayPosition) - { // Don't save for AUDIOBOOK_LOOP because not necessary + if (gPlayProperties.saveLastPlayPosition) { // Don't save for AUDIOBOOK_LOOP because not necessary if (gPlayProperties.currentTrackNumber + 1 < gPlayProperties.numberOfTracks) { // Only save if there's another track, otherwise it will be saved at end of playlist anyway AudioPlayer_NvsRfidWriteWrapper(gPlayProperties.playRfidTag, *(gPlayProperties.playlist + gPlayProperties.currentTrackNumber), 0, gPlayProperties.playMode, gPlayProperties.currentTrackNumber + 1, gPlayProperties.numberOfTracks); } } - if (gPlayProperties.sleepAfterCurrentTrack) - { // Go to sleep if "sleep after track" was requested + if (gPlayProperties.sleepAfterCurrentTrack) { // Go to sleep if "sleep after track" was requested System_RequestSleep(); break; - } - if (!gPlayProperties.repeatCurrentTrack) + } if (!gPlayProperties.repeatCurrentTrack) { // If endless-loop requested, track-number will not be incremented gPlayProperties.currentTrackNumber++; - } - else - { - Log_Println((char *)FPSTR(repeatTrackDueToPlaymode), LOGLEVEL_INFO); + } else { + Log_Println((char *) FPSTR(repeatTrackDueToPlaymode), LOGLEVEL_INFO); Led_Indicate(LedIndicatorType::Rewind); } } - if (gPlayProperties.playlistFinished && trackCommand != 0) - { - Log_Println((char *)FPSTR(noPlaymodeChangeIfIdle), LOGLEVEL_NOTICE); + if (gPlayProperties.playlistFinished && trackCommand != 0) { + Log_Println((char *) FPSTR(noPlaymodeChangeIfIdle), LOGLEVEL_NOTICE); trackCommand = 0; System_IndicateError(); continue; } /* Check if track-control was called (stop, start, next track, prev. track, last track, first track...) */ - switch (trackCommand) - { - case STOP: - audio.stopSong(); - trackCommand = 0; - Log_Println((char *)FPSTR(cmndStop), LOGLEVEL_INFO); - gPlayProperties.pausePlay = true; - gPlayProperties.playlistFinished = true; - gPlayProperties.playMode = NO_PLAYLIST; - continue; - - case PAUSEPLAY: - audio.pauseResume(); - trackCommand = 0; - Log_Println((char *)FPSTR(cmndPause), LOGLEVEL_INFO); - if (gPlayProperties.saveLastPlayPosition && !gPlayProperties.pausePlay) - { - snprintf(Log_Buffer, Log_BufferLength, "%s: %u", (char *)FPSTR(trackPausedAtPos), audio.getFilePos()); - Log_Println(Log_Buffer, LOGLEVEL_INFO); - AudioPlayer_NvsRfidWriteWrapper(gPlayProperties.playRfidTag, *(gPlayProperties.playlist + gPlayProperties.currentTrackNumber), audio.getFilePos(), gPlayProperties.playMode, gPlayProperties.currentTrackNumber, gPlayProperties.numberOfTracks); - } - gPlayProperties.pausePlay = !gPlayProperties.pausePlay; - continue; + switch (trackCommand) { + case STOP: + audio.stopSong(); + trackCommand = 0; + Log_Println((char *) FPSTR(cmndStop), LOGLEVEL_INFO); + gPlayProperties.pausePlay = true; + gPlayProperties.playlistFinished = true; + gPlayProperties.playMode = NO_PLAYLIST; + continue; - case NEXTTRACK: - if (gPlayProperties.pausePlay) - { + case PAUSEPLAY: audio.pauseResume(); + trackCommand = 0; + Log_Println((char *) FPSTR(cmndPause), LOGLEVEL_INFO); + if (gPlayProperties.saveLastPlayPosition && !gPlayProperties.pausePlay) { + snprintf(Log_Buffer, Log_BufferLength, "%s: %u", (char *) FPSTR(trackPausedAtPos), audio.getFilePos()); + Log_Println(Log_Buffer, LOGLEVEL_INFO); + AudioPlayer_NvsRfidWriteWrapper(gPlayProperties.playRfidTag, *(gPlayProperties.playlist + gPlayProperties.currentTrackNumber), audio.getFilePos(), gPlayProperties.playMode, gPlayProperties.currentTrackNumber, gPlayProperties.numberOfTracks); + } gPlayProperties.pausePlay = !gPlayProperties.pausePlay; - } - if (gPlayProperties.repeatCurrentTrack) - { // End loop if button was pressed - gPlayProperties.repeatCurrentTrack = !gPlayProperties.repeatCurrentTrack; - char rBuf[2]; - snprintf(rBuf, 2, "%u", AudioPlayer_GetRepeatMode()); -#ifdef MQTT_ENABLE - publishMqtt((char *)FPSTR(topicRepeatModeState), rBuf, false); -#endif - } - if (gPlayProperties.currentTrackNumber + 1 < gPlayProperties.numberOfTracks) - { - gPlayProperties.currentTrackNumber++; - if (gPlayProperties.saveLastPlayPosition) - { - AudioPlayer_NvsRfidWriteWrapper(gPlayProperties.playRfidTag, *(gPlayProperties.playlist + gPlayProperties.currentTrackNumber), 0, gPlayProperties.playMode, gPlayProperties.currentTrackNumber, gPlayProperties.numberOfTracks); - Log_Println((char *)FPSTR(trackStartAudiobook), LOGLEVEL_INFO); + continue; + + case NEXTTRACK: + if (gPlayProperties.pausePlay) { + audio.pauseResume(); + gPlayProperties.pausePlay = !gPlayProperties.pausePlay; } - Log_Println((char *)FPSTR(cmndNextTrack), LOGLEVEL_INFO); - if (!gPlayProperties.playlistFinished) - { - audio.stopSong(); + if (gPlayProperties.repeatCurrentTrack) { // End loop if button was pressed + gPlayProperties.repeatCurrentTrack = !gPlayProperties.repeatCurrentTrack; + char rBuf[2]; + snprintf(rBuf, 2, "%u", AudioPlayer_GetRepeatMode()); + #ifdef MQTT_ENABLE + publishMqtt((char *) FPSTR(topicRepeatModeState), rBuf, false); + #endif + } + if (gPlayProperties.currentTrackNumber + 1 < gPlayProperties.numberOfTracks) { + gPlayProperties.currentTrackNumber++; + if (gPlayProperties.saveLastPlayPosition) { + AudioPlayer_NvsRfidWriteWrapper(gPlayProperties.playRfidTag, *(gPlayProperties.playlist + gPlayProperties.currentTrackNumber), 0, gPlayProperties.playMode, gPlayProperties.currentTrackNumber, gPlayProperties.numberOfTracks); + Log_Println((char *) FPSTR(trackStartAudiobook), LOGLEVEL_INFO); + } + Log_Println((char *) FPSTR(cmndNextTrack), LOGLEVEL_INFO); + if (!gPlayProperties.playlistFinished) { + audio.stopSong(); + } + } else { + Log_Println((char *) FPSTR(lastTrackAlreadyActive), LOGLEVEL_NOTICE); + trackCommand = 0; + System_IndicateError(); + continue; } - } - else - { - Log_Println((char *)FPSTR(lastTrackAlreadyActive), LOGLEVEL_NOTICE); trackCommand = 0; - System_IndicateError(); - continue; - } - trackCommand = 0; - break; + break; - case PREVIOUSTRACK: - if (gPlayProperties.pausePlay) - { - audio.pauseResume(); - gPlayProperties.pausePlay = !gPlayProperties.pausePlay; - } - if (gPlayProperties.repeatCurrentTrack) - { // End loop if button was pressed - gPlayProperties.repeatCurrentTrack = !gPlayProperties.repeatCurrentTrack; - char rBuf[2]; - snprintf(rBuf, 2, "%u", AudioPlayer_GetRepeatMode()); -#ifdef MQTT_ENABLE - publishMqtt((char *)FPSTR(topicRepeatModeState), rBuf, false); -#endif - } - if (gPlayProperties.currentTrackNumber > 0) - { - // play previous track when current track time is small, else play current track again - if (audio.getAudioCurrentTime() < 2) - { - gPlayProperties.currentTrackNumber--; + case PREVIOUSTRACK: + if (gPlayProperties.pausePlay) { + audio.pauseResume(); + gPlayProperties.pausePlay = !gPlayProperties.pausePlay; } - if (gPlayProperties.saveLastPlayPosition) - { - AudioPlayer_NvsRfidWriteWrapper(gPlayProperties.playRfidTag, *(gPlayProperties.playlist + gPlayProperties.currentTrackNumber), 0, gPlayProperties.playMode, gPlayProperties.currentTrackNumber, gPlayProperties.numberOfTracks); - Log_Println((char *)FPSTR(trackStartAudiobook), LOGLEVEL_INFO); + if (gPlayProperties.repeatCurrentTrack) { // End loop if button was pressed + gPlayProperties.repeatCurrentTrack = !gPlayProperties.repeatCurrentTrack; + char rBuf[2]; + snprintf(rBuf, 2, "%u", AudioPlayer_GetRepeatMode()); + #ifdef MQTT_ENABLE + publishMqtt((char *) FPSTR(topicRepeatModeState), rBuf, false); + #endif } - - Log_Println((char *)FPSTR(cmndPrevTrack), LOGLEVEL_INFO); - if (!gPlayProperties.playlistFinished) - { + if (gPlayProperties.currentTrackNumber > 0) { + // play previous track when current track time is small, else play current track again + if (audio.getAudioCurrentTime() < 2) { + gPlayProperties.currentTrackNumber--; + } + if (gPlayProperties.saveLastPlayPosition) { + AudioPlayer_NvsRfidWriteWrapper(gPlayProperties.playRfidTag, *(gPlayProperties.playlist + gPlayProperties.currentTrackNumber), 0, gPlayProperties.playMode, gPlayProperties.currentTrackNumber, gPlayProperties.numberOfTracks); + Log_Println((char *) FPSTR(trackStartAudiobook), LOGLEVEL_INFO); + } + + Log_Println((char *) FPSTR(cmndPrevTrack), LOGLEVEL_INFO); + if (!gPlayProperties.playlistFinished) { + audio.stopSong(); + } + } else { + if (gPlayProperties.playMode == WEBSTREAM) { + Log_Println((char *) FPSTR(trackChangeWebstream), LOGLEVEL_INFO); + System_IndicateError(); + trackCommand = 0; + continue; + } + if (gPlayProperties.saveLastPlayPosition) { + AudioPlayer_NvsRfidWriteWrapper(gPlayProperties.playRfidTag, *(gPlayProperties.playlist + gPlayProperties.currentTrackNumber), 0, gPlayProperties.playMode, gPlayProperties.currentTrackNumber, gPlayProperties.numberOfTracks); + } audio.stopSong(); - } - } - else - { - if (gPlayProperties.playMode == WEBSTREAM) - { - Log_Println((char *)FPSTR(trackChangeWebstream), LOGLEVEL_INFO); - System_IndicateError(); + Led_Indicate(LedIndicatorType::Rewind); + audioReturnCode = audio.connecttoFS(gFSystem, *(gPlayProperties.playlist + gPlayProperties.currentTrackNumber)); + // consider track as finished, when audio lib call was not successful + if (!audioReturnCode) { + System_IndicateError(); + gPlayProperties.trackFinished = true; + continue; + } + Log_Println((char *) FPSTR(trackStart), LOGLEVEL_INFO); trackCommand = 0; continue; } - if (gPlayProperties.saveLastPlayPosition) - { - AudioPlayer_NvsRfidWriteWrapper(gPlayProperties.playRfidTag, *(gPlayProperties.playlist + gPlayProperties.currentTrackNumber), 0, gPlayProperties.playMode, gPlayProperties.currentTrackNumber, gPlayProperties.numberOfTracks); + trackCommand = 0; + break; + + case FIRSTTRACK: + if (gPlayProperties.pausePlay) { + audio.pauseResume(); + gPlayProperties.pausePlay = !gPlayProperties.pausePlay; } - audio.stopSong(); - Led_Indicate(LedIndicatorType::Rewind); - audioReturnCode = audio.connecttoFS(gFSystem, *(gPlayProperties.playlist + gPlayProperties.currentTrackNumber)); - // consider track as finished, when audio lib call was not successful - if (!audioReturnCode) - { + if (gPlayProperties.currentTrackNumber > 0) { + gPlayProperties.currentTrackNumber = 0; + if (gPlayProperties.saveLastPlayPosition) { + AudioPlayer_NvsRfidWriteWrapper(gPlayProperties.playRfidTag, *(gPlayProperties.playlist + gPlayProperties.currentTrackNumber), 0, gPlayProperties.playMode, gPlayProperties.currentTrackNumber, gPlayProperties.numberOfTracks); + Log_Println((char *) FPSTR(trackStartAudiobook), LOGLEVEL_INFO); + } + Log_Println((char *) FPSTR(cmndFirstTrack), LOGLEVEL_INFO); + if (!gPlayProperties.playlistFinished) { + audio.stopSong(); + } + } else { + Log_Println((char *) FPSTR(firstTrackAlreadyActive), LOGLEVEL_NOTICE); System_IndicateError(); - gPlayProperties.trackFinished = true; + trackCommand = 0; continue; } - Log_Println((char *)FPSTR(trackStart), LOGLEVEL_INFO); trackCommand = 0; - continue; - } - trackCommand = 0; - break; + break; - case FIRSTTRACK: - if (gPlayProperties.pausePlay) - { - audio.pauseResume(); - gPlayProperties.pausePlay = !gPlayProperties.pausePlay; - } - if (gPlayProperties.currentTrackNumber > 0) - { - gPlayProperties.currentTrackNumber = 0; - if (gPlayProperties.saveLastPlayPosition) - { - AudioPlayer_NvsRfidWriteWrapper(gPlayProperties.playRfidTag, *(gPlayProperties.playlist + gPlayProperties.currentTrackNumber), 0, gPlayProperties.playMode, gPlayProperties.currentTrackNumber, gPlayProperties.numberOfTracks); - Log_Println((char *)FPSTR(trackStartAudiobook), LOGLEVEL_INFO); + case LASTTRACK: + if (gPlayProperties.pausePlay) { + audio.pauseResume(); + gPlayProperties.pausePlay = !gPlayProperties.pausePlay; } - Log_Println((char *)FPSTR(cmndFirstTrack), LOGLEVEL_INFO); - if (!gPlayProperties.playlistFinished) - { - audio.stopSong(); + if (gPlayProperties.currentTrackNumber + 1 < gPlayProperties.numberOfTracks) { + gPlayProperties.currentTrackNumber = gPlayProperties.numberOfTracks - 1; + if (gPlayProperties.saveLastPlayPosition) { + AudioPlayer_NvsRfidWriteWrapper(gPlayProperties.playRfidTag, *(gPlayProperties.playlist + gPlayProperties.currentTrackNumber), 0, gPlayProperties.playMode, gPlayProperties.currentTrackNumber, gPlayProperties.numberOfTracks); + Log_Println((char *) FPSTR(trackStartAudiobook), LOGLEVEL_INFO); + } + Log_Println((char *) FPSTR(cmndLastTrack), LOGLEVEL_INFO); + if (!gPlayProperties.playlistFinished) { + audio.stopSong(); + } + } else { + Log_Println((char *) FPSTR(lastTrackAlreadyActive), LOGLEVEL_NOTICE); + System_IndicateError(); + trackCommand = 0; + continue; } - } - else - { - Log_Println((char *)FPSTR(firstTrackAlreadyActive), LOGLEVEL_NOTICE); - System_IndicateError(); trackCommand = 0; - continue; - } - trackCommand = 0; - break; + break; - case LASTTRACK: - if (gPlayProperties.pausePlay) - { - audio.pauseResume(); - gPlayProperties.pausePlay = !gPlayProperties.pausePlay; - } - if (gPlayProperties.currentTrackNumber + 1 < gPlayProperties.numberOfTracks) - { - gPlayProperties.currentTrackNumber = gPlayProperties.numberOfTracks - 1; - if (gPlayProperties.saveLastPlayPosition) - { - AudioPlayer_NvsRfidWriteWrapper(gPlayProperties.playRfidTag, *(gPlayProperties.playlist + gPlayProperties.currentTrackNumber), 0, gPlayProperties.playMode, gPlayProperties.currentTrackNumber, gPlayProperties.numberOfTracks); - Log_Println((char *)FPSTR(trackStartAudiobook), LOGLEVEL_INFO); - } - Log_Println((char *)FPSTR(cmndLastTrack), LOGLEVEL_INFO); - if (!gPlayProperties.playlistFinished) - { - audio.stopSong(); - } - } - else - { - Log_Println((char *)FPSTR(lastTrackAlreadyActive), LOGLEVEL_NOTICE); - System_IndicateError(); + case 0: + break; + + default: trackCommand = 0; + Log_Println((char *) FPSTR(cmndDoesNotExist), LOGLEVEL_NOTICE); + System_IndicateError(); continue; - } - trackCommand = 0; - break; - - case 0: - break; - - default: - trackCommand = 0; - Log_Println((char *)FPSTR(cmndDoesNotExist), LOGLEVEL_NOTICE); - System_IndicateError(); - continue; } - if (gPlayProperties.playUntilTrackNumber == gPlayProperties.currentTrackNumber && gPlayProperties.playUntilTrackNumber > 0) - { - if (gPlayProperties.saveLastPlayPosition) - { + if (gPlayProperties.playUntilTrackNumber == gPlayProperties.currentTrackNumber && gPlayProperties.playUntilTrackNumber > 0) { + if (gPlayProperties.saveLastPlayPosition) { AudioPlayer_NvsRfidWriteWrapper(gPlayProperties.playRfidTag, *(gPlayProperties.playlist + gPlayProperties.currentTrackNumber), 0, gPlayProperties.playMode, 0, gPlayProperties.numberOfTracks); } gPlayProperties.playlistFinished = true; @@ -548,96 +464,80 @@ void AudioPlayer_Task(void *parameter) continue; } - if (gPlayProperties.currentTrackNumber >= gPlayProperties.numberOfTracks) - { // Check if last element of playlist is already reached - Log_Println((char *)FPSTR(endOfPlaylistReached), LOGLEVEL_NOTICE); - if (!gPlayProperties.repeatPlaylist) - { - if (gPlayProperties.saveLastPlayPosition) - { + if (gPlayProperties.currentTrackNumber >= gPlayProperties.numberOfTracks) { // Check if last element of playlist is already reached + Log_Println((char *) FPSTR(endOfPlaylistReached), LOGLEVEL_NOTICE); + if (!gPlayProperties.repeatPlaylist) { + if (gPlayProperties.saveLastPlayPosition) { // Set back to first track AudioPlayer_NvsRfidWriteWrapper(gPlayProperties.playRfidTag, *(gPlayProperties.playlist + 0), 0, gPlayProperties.playMode, 0, gPlayProperties.numberOfTracks); } -#ifdef MQTT_ENABLE -#if (LANGUAGE == 1) - publishMqtt((char *)FPSTR(topicTrackState), "", false); -#else - publishMqtt((char *)FPSTR(topicTrackState), "", false); -#endif -#endif + #ifdef MQTT_ENABLE + #if (LANGUAGE == 1) + publishMqtt((char *) FPSTR(topicTrackState), "", false); + #else + publishMqtt((char *) FPSTR(topicTrackState), "", false); + #endif + #endif gPlayProperties.playlistFinished = true; gPlayProperties.playMode = NO_PLAYLIST; -#ifdef MQTT_ENABLE - publishMqtt((char *)FPSTR(topicPlaymodeState), gPlayProperties.playMode, false); -#endif + #ifdef MQTT_ENABLE + publishMqtt((char *) FPSTR(topicPlaymodeState), gPlayProperties.playMode, false); + #endif gPlayProperties.currentTrackNumber = 0; gPlayProperties.numberOfTracks = 0; - if (gPlayProperties.sleepAfterPlaylist) - { + if (gPlayProperties.sleepAfterPlaylist) { System_RequestSleep(); } continue; - } - else - { // Check if sleep after current track/playlist was requested - if (gPlayProperties.sleepAfterPlaylist || gPlayProperties.sleepAfterCurrentTrack) - { + } else { // Check if sleep after current track/playlist was requested + if (gPlayProperties.sleepAfterPlaylist || gPlayProperties.sleepAfterCurrentTrack) { gPlayProperties.playlistFinished = true; gPlayProperties.playMode = NO_PLAYLIST; System_RequestSleep(); continue; } // Repeat playlist; set current track number back to 0 - Log_Println((char *)FPSTR(repeatPlaylistDueToPlaymode), LOGLEVEL_NOTICE); + Log_Println((char *) FPSTR(repeatPlaylistDueToPlaymode), LOGLEVEL_NOTICE); gPlayProperties.currentTrackNumber = 0; - if (gPlayProperties.saveLastPlayPosition) - { + if (gPlayProperties.saveLastPlayPosition) { AudioPlayer_NvsRfidWriteWrapper(gPlayProperties.playRfidTag, *(gPlayProperties.playlist + 0), 0, gPlayProperties.playMode, gPlayProperties.currentTrackNumber, gPlayProperties.numberOfTracks); } } } - if (gPlayProperties.playMode == WEBSTREAM) - { // Webstream + if (gPlayProperties.playMode == WEBSTREAM) { // Webstream audio.connecttohost(*(gPlayProperties.playlist + gPlayProperties.currentTrackNumber)); gPlayProperties.playlistFinished = false; - } - else - { + } else { // Files from SD - if (!gFSystem.exists(*(gPlayProperties.playlist + gPlayProperties.currentTrackNumber))) - { // Check first if file/folder exists - snprintf(Log_Buffer, Log_BufferLength, "%s: %s", (char *)FPSTR(dirOrFileDoesNotExist), *(gPlayProperties.playlist + gPlayProperties.currentTrackNumber)); + if (!gFSystem.exists(*(gPlayProperties.playlist + gPlayProperties.currentTrackNumber))) { // Check first if file/folder exists + snprintf(Log_Buffer, Log_BufferLength, "%s: %s", (char *) FPSTR(dirOrFileDoesNotExist), *(gPlayProperties.playlist + gPlayProperties.currentTrackNumber)); Log_Println(Log_Buffer, LOGLEVEL_ERROR); gPlayProperties.trackFinished = true; continue; - } - else - { + } else { audioReturnCode = audio.connecttoFS(gFSystem, *(gPlayProperties.playlist + gPlayProperties.currentTrackNumber)); // consider track as finished, when audio lib call was not successful - if (!audioReturnCode) - { + if (!audioReturnCode) { System_IndicateError(); gPlayProperties.trackFinished = true; continue; } Led_Indicate(LedIndicatorType::PlaylistProgress); - if (gPlayProperties.startAtFilePos > 0) - { + if (gPlayProperties.startAtFilePos > 0) { audio.setFilePos(gPlayProperties.startAtFilePos); - snprintf(Log_Buffer, Log_BufferLength, "%s %u", (char *)FPSTR(trackStartatPos), audio.getFilePos()); + snprintf(Log_Buffer, Log_BufferLength, "%s %u", (char *) FPSTR(trackStartatPos), audio.getFilePos()); Log_Println(Log_Buffer, LOGLEVEL_NOTICE); } char buf[255]; snprintf(buf, sizeof(buf) / sizeof(buf[0]), "(%d/%d) %s", (gPlayProperties.currentTrackNumber + 1), gPlayProperties.numberOfTracks, (const char *)*(gPlayProperties.playlist + gPlayProperties.currentTrackNumber)); -#ifdef MQTT_ENABLE - publishMqtt((char *)FPSTR(topicTrackState), buf, false); -#endif -#if (LANGUAGE == 1) - snprintf(Log_Buffer, Log_BufferLength, "'%s' wird abgespielt (%d von %d)", *(gPlayProperties.playlist + gPlayProperties.currentTrackNumber), (gPlayProperties.currentTrackNumber + 1), gPlayProperties.numberOfTracks); -#else - snprintf(Log_Buffer, Log_BufferLength, "'%s' is being played (%d of %d)", *(gPlayProperties.playlist + gPlayProperties.currentTrackNumber), (gPlayProperties.currentTrackNumber + 1), gPlayProperties.numberOfTracks); -#endif + #ifdef MQTT_ENABLE + publishMqtt((char *) FPSTR(topicTrackState), buf, false); + #endif + #if (LANGUAGE == 1) + snprintf(Log_Buffer, Log_BufferLength, "'%s' wird abgespielt (%d von %d)", *(gPlayProperties.playlist + gPlayProperties.currentTrackNumber), (gPlayProperties.currentTrackNumber + 1), gPlayProperties.numberOfTracks); + #else + snprintf(Log_Buffer, Log_BufferLength, "'%s' is being played (%d of %d)", *(gPlayProperties.playlist + gPlayProperties.currentTrackNumber), (gPlayProperties.currentTrackNumber + 1), gPlayProperties.numberOfTracks); + #endif Log_Println(Log_Buffer, LOGLEVEL_NOTICE); gPlayProperties.playlistFinished = false; } @@ -645,35 +545,25 @@ void AudioPlayer_Task(void *parameter) } // Handle seekmodes - if (gPlayProperties.seekmode != SEEK_NORMAL) - { - if (gPlayProperties.seekmode == SEEK_FORWARDS) - { - if (audio.setTimeOffset(jumpOffset)) - { -#if (LANGUAGE == 1) - Serial.printf("%d Sekunden nach vorne gesprungen\n", jumpOffset); -#else - Serial.printf("Jumped %d seconds forwards\n", jumpOffset); -#endif - } - else - { + if (gPlayProperties.seekmode != SEEK_NORMAL) { + if (gPlayProperties.seekmode == SEEK_FORWARDS) { + if (audio.setTimeOffset(jumpOffset)) { + #if (LANGUAGE == 1) + Serial.printf("%d Sekunden nach vorne gesprungen\n", jumpOffset); + #else + Serial.printf("Jumped %d seconds forwards\n", jumpOffset); + #endif + } else { System_IndicateError(); } - } - else if (gPlayProperties.seekmode == SEEK_BACKWARDS) - { - if (audio.setTimeOffset(-(jumpOffset))) - { -#if (LANGUAGE == 1) - Serial.printf("%d Sekunden zurueck gesprungen\n", jumpOffset); -#else - Serial.printf("Jumped %d seconds backwards\n", jumpOffset); -#endif - } - else - { + } else if (gPlayProperties.seekmode == SEEK_BACKWARDS) { + if (audio.setTimeOffset(-(jumpOffset))) { + #if (LANGUAGE == 1) + Serial.printf("%d Sekunden zurueck gesprungen\n", jumpOffset); + #else + Serial.printf("Jumped %d seconds backwards\n", jumpOffset); + #endif + } else { System_IndicateError(); } } @@ -681,56 +571,42 @@ void AudioPlayer_Task(void *parameter) } // Handle if mono/stereo should be changed (e.g. if plugging headphones) - if (gPlayProperties.newPlayMono != gPlayProperties.currentPlayMono) - { + if (gPlayProperties.newPlayMono != gPlayProperties.currentPlayMono) { gPlayProperties.currentPlayMono = gPlayProperties.newPlayMono; audio.forceMono(gPlayProperties.currentPlayMono); - if (gPlayProperties.currentPlayMono) - { + if (gPlayProperties.currentPlayMono) { Log_Println(newPlayModeMono, LOGLEVEL_NOTICE); audio.setTone(3, 0, 0); - } - else - { + } else { Log_Println(newPlayModeStereo, LOGLEVEL_NOTICE); audio.setTone(0, 0, 0); } } // Calculate relative position in file (for neopixel) for SD-card-mode - if (!gPlayProperties.playlistFinished && gPlayProperties.playMode != WEBSTREAM) - { + if (!gPlayProperties.playlistFinished && gPlayProperties.playMode != WEBSTREAM) { double fp = (double)audio.getFilePos() / (double)audio.getFileSize(); - if (millis() % 100 == 0) - { + if (millis() % 100 == 0) { gPlayProperties.currentRelPos = fp * 100; } - } - else - { + } else { gPlayProperties.currentRelPos = 0; } audio.loop(); - if (gPlayProperties.playlistFinished || gPlayProperties.pausePlay) - { + if (gPlayProperties.playlistFinished || gPlayProperties.pausePlay) { vTaskDelay(portTICK_PERIOD_MS * 10); // Waste some time if playlist is not active - } - else - { + } else { System_UpdateActivityTimer(); // Refresh if playlist is active so uC will not fall asleep due to reaching inactivity-time } - if (audio.isRunning()) - { + if (audio.isRunning()) { settleCount = 0; } // If error occured: remove playlist from ESPuino - if (gPlayProperties.playMode != NO_PLAYLIST && gPlayProperties.playMode != BUSY && !audio.isRunning() && !gPlayProperties.pausePlay) - { - if (settleCount++ == 50) - { // Hack to give audio some time to settle down after playlist was generated + if (gPlayProperties.playMode != NO_PLAYLIST && gPlayProperties.playMode != BUSY && !audio.isRunning() && !gPlayProperties.pausePlay) { + if (settleCount++ == 50) { // Hack to give audio some time to settle down after playlist was generated gPlayProperties.playlistFinished = true; gPlayProperties.playMode = NO_PLAYLIST; settleCount = 0; @@ -743,47 +619,32 @@ void AudioPlayer_Task(void *parameter) } // Returns current repeat-mode (mix of repeat current track and current playlist) -uint8_t AudioPlayer_GetRepeatMode(void) -{ - if (gPlayProperties.repeatPlaylist && gPlayProperties.repeatCurrentTrack) - { +uint8_t AudioPlayer_GetRepeatMode(void) { + if (gPlayProperties.repeatPlaylist && gPlayProperties.repeatCurrentTrack) { return TRACK_N_PLAYLIST; - } - else if (gPlayProperties.repeatPlaylist && !gPlayProperties.repeatCurrentTrack) - { + } else if (gPlayProperties.repeatPlaylist && !gPlayProperties.repeatCurrentTrack) { return PLAYLIST; - } - else if (!gPlayProperties.repeatPlaylist && gPlayProperties.repeatCurrentTrack) - { + } else if (!gPlayProperties.repeatPlaylist && gPlayProperties.repeatCurrentTrack) { return TRACK; - } - else - { + } else{ return NO_REPEAT; } } // Adds new volume-entry to volume-queue // If volume is changed via webgui or MQTT, it's necessary to re-adjust current value of rotary-encoder. -void AudioPlayer_VolumeToQueueSender(const int32_t _newVolume, bool reAdjustRotary) -{ +void AudioPlayer_VolumeToQueueSender(const int32_t _newVolume, bool reAdjustRotary) { uint32_t _volume; - if (_newVolume < AudioPlayer_GetMinVolume()) - { - Log_Println((char *)FPSTR(minLoudnessReached), LOGLEVEL_INFO); + if (_newVolume < AudioPlayer_GetMinVolume()) { + Log_Println((char *) FPSTR(minLoudnessReached), LOGLEVEL_INFO); return; - } - else if (_newVolume > AudioPlayer_GetMaxVolume()) - { - Log_Println((char *)FPSTR(maxLoudnessReached), LOGLEVEL_INFO); + } else if (_newVolume > AudioPlayer_GetMaxVolume()) { + Log_Println((char *) FPSTR(maxLoudnessReached), LOGLEVEL_INFO); return; - } - else - { + } else { _volume = _newVolume; AudioPlayer_SetCurrentVolume(_volume); - if (reAdjustRotary) - { + if (reAdjustRotary) { RotaryEncoder_Readjust(); } } @@ -792,10 +653,9 @@ void AudioPlayer_VolumeToQueueSender(const int32_t _newVolume, bool reAdjustRota // Receives de-serialized RFID-data (from NVS) and dispatches playlists for the given // playmode to the track-queue. -void AudioPlayer_TrackQueueDispatcher(const char *_itemToPlay, const uint32_t _lastPlayPos, const uint32_t _playMode, const uint16_t _trackLastPlayed) -{ +void AudioPlayer_TrackQueueDispatcher(const char *_itemToPlay, const uint32_t _lastPlayPos, const uint32_t _playMode, const uint16_t _trackLastPlayed) { char *filename; - filename = (char *)x_malloc(sizeof(char) * 255); + filename = (char *) x_malloc(sizeof(char) * 255); strncpy(filename, _itemToPlay, 255); gPlayProperties.startAtFilePos = _lastPlayPos; @@ -803,32 +663,28 @@ void AudioPlayer_TrackQueueDispatcher(const char *_itemToPlay, const uint32_t _l char **musicFiles; gPlayProperties.playMode = BUSY; // Show @Neopixel, if uC is busy with creating playlist -#ifdef MQTT_ENABLE - publishMqtt((char *)FPSTR(topicLedBrightnessState), 0, false); - publishMqtt((char *)FPSTR(topicPlaymodeState), gPlayProperties.playMode, false); -#endif - if (_playMode != WEBSTREAM) - { + #ifdef MQTT_ENABLE + publishMqtt((char *) FPSTR(topicLedBrightnessState), 0, false); + publishMqtt((char *) FPSTR(topicPlaymodeState), gPlayProperties.playMode, false); + #endif + + if (_playMode != WEBSTREAM) { musicFiles = SdCard_ReturnPlaylist(filename); - } - else - { + } else { musicFiles = AudioPlayer_ReturnPlaylistFromWebstream(filename); } -#ifdef MQTT_ENABLE - publishMqtt((char *)FPSTR(topicLedBrightnessState), Led_GetBrightness(), false); -#endif - if (musicFiles == NULL) - { - Log_Println((char *)FPSTR(errorOccured), LOGLEVEL_ERROR); + #ifdef MQTT_ENABLE + publishMqtt((char *) FPSTR(topicLedBrightnessState), Led_GetBrightness(), false); + #endif + + if (musicFiles == NULL) { + Log_Println((char *) FPSTR(errorOccured), LOGLEVEL_ERROR); System_IndicateError(); gPlayProperties.playMode = NO_PLAYLIST; return; - } - else if (!strcmp(*(musicFiles - 1), "0")) - { - Log_Println((char *)FPSTR(noMp3FilesInDir), LOGLEVEL_NOTICE); + } else if (!strcmp(*(musicFiles - 1), "0")) { + Log_Println((char *) FPSTR(noMp3FilesInDir), LOGLEVEL_NOTICE); System_IndicateError(); gPlayProperties.playMode = NO_PLAYLIST; free(filename); @@ -845,174 +701,156 @@ void AudioPlayer_TrackQueueDispatcher(const char *_itemToPlay, const uint32_t _l gPlayProperties.saveLastPlayPosition = false; gPlayProperties.playUntilTrackNumber = 0; -#ifdef PLAY_LAST_RFID_AFTER_REBOOT - // Store last RFID-tag to NVS - gPrefsSettings.putString("lastRfid", gCurrentRfidTagId); -#endif - - switch (gPlayProperties.playMode) - { - case SINGLE_TRACK: - { - Log_Println((char *)FPSTR(modeSingleTrack), LOGLEVEL_NOTICE); -#ifdef MQTT_ENABLE - publishMqtt((char *)FPSTR(topicPlaymodeState), gPlayProperties.playMode, false); - publishMqtt((char *)FPSTR(topicRepeatModeState), NO_REPEAT, false); -#endif - xQueueSend(gTrackQueue, &(musicFiles), 0); - break; - } - - case SINGLE_TRACK_LOOP: - { - gPlayProperties.repeatCurrentTrack = true; - Log_Println((char *)FPSTR(modeSingleTrackLoop), LOGLEVEL_NOTICE); -#ifdef MQTT_ENABLE - publishMqtt((char *)FPSTR(topicPlaymodeState), gPlayProperties.playMode, false); - publishMqtt((char *)FPSTR(topicRepeatModeState), TRACK, false); -#endif - xQueueSend(gTrackQueue, &(musicFiles), 0); - break; - } + #ifdef PLAY_LAST_RFID_AFTER_REBOOT + // Store last RFID-tag to NVS + gPrefsSettings.putString("lastRfid", gCurrentRfidTagId); + #endif + + switch (gPlayProperties.playMode) { + case SINGLE_TRACK: { + Log_Println((char *) FPSTR(modeSingleTrack), LOGLEVEL_NOTICE); + #ifdef MQTT_ENABLE + publishMqtt((char *) FPSTR(topicPlaymodeState), gPlayProperties.playMode, false); + publishMqtt((char *) FPSTR(topicRepeatModeState), NO_REPEAT, false); + #endif + xQueueSend(gTrackQueue, &(musicFiles), 0); + break; + } - case AUDIOBOOK: - { // Tracks need to be alph. sorted! - gPlayProperties.saveLastPlayPosition = true; - Log_Println((char *)FPSTR(modeSingleAudiobook), LOGLEVEL_NOTICE); -#ifdef MQTT_ENABLE - publishMqtt((char *)FPSTR(topicPlaymodeState), gPlayProperties.playMode, false); - publishMqtt((char *)FPSTR(topicRepeatModeState), NO_REPEAT, false); -#endif - AudioPlayer_SortPlaylist((const char **)musicFiles, strtoul(*(musicFiles - 1), NULL, 10)); - xQueueSend(gTrackQueue, &(musicFiles), 0); - break; - } + case SINGLE_TRACK_LOOP: { + gPlayProperties.repeatCurrentTrack = true; + Log_Println((char *) FPSTR(modeSingleTrackLoop), LOGLEVEL_NOTICE); + #ifdef MQTT_ENABLE + publishMqtt((char *) FPSTR(topicPlaymodeState), gPlayProperties.playMode, false); + publishMqtt((char *) FPSTR(topicRepeatModeState), TRACK, false); + #endif + xQueueSend(gTrackQueue, &(musicFiles), 0); + break; + } - case AUDIOBOOK_LOOP: - { // Tracks need to be alph. sorted! - gPlayProperties.repeatPlaylist = true; - gPlayProperties.saveLastPlayPosition = true; - Log_Println((char *)FPSTR(modeSingleAudiobookLoop), LOGLEVEL_NOTICE); -#ifdef MQTT_ENABLE - publishMqtt((char *)FPSTR(topicPlaymodeState), gPlayProperties.playMode, false); - publishMqtt((char *)FPSTR(topicRepeatModeState), PLAYLIST, false); -#endif - AudioPlayer_SortPlaylist((const char **)musicFiles, strtoul(*(musicFiles - 1), NULL, 10)); - xQueueSend(gTrackQueue, &(musicFiles), 0); - break; - } + case AUDIOBOOK: { // Tracks need to be alph. sorted! + gPlayProperties.saveLastPlayPosition = true; + Log_Println((char *) FPSTR(modeSingleAudiobook), LOGLEVEL_NOTICE); + #ifdef MQTT_ENABLE + publishMqtt((char *) FPSTR(topicPlaymodeState), gPlayProperties.playMode, false); + publishMqtt((char *) FPSTR(topicRepeatModeState), NO_REPEAT, false); + #endif + AudioPlayer_SortPlaylist((const char **)musicFiles, strtoul(*(musicFiles - 1), NULL, 10)); + xQueueSend(gTrackQueue, &(musicFiles), 0); + break; + } - case ALL_TRACKS_OF_DIR_SORTED: - { - snprintf(Log_Buffer, Log_BufferLength, "%s '%s' ", (char *)FPSTR(modeAllTrackAlphSorted), filename); - Log_Println(Log_Buffer, LOGLEVEL_NOTICE); - AudioPlayer_SortPlaylist((const char **)musicFiles, strtoul(*(musicFiles - 1), NULL, 10)); -#ifdef MQTT_ENABLE - publishMqtt((char *)FPSTR(topicPlaymodeState), gPlayProperties.playMode, false); - publishMqtt((char *)FPSTR(topicRepeatModeState), NO_REPEAT, false); -#endif - xQueueSend(gTrackQueue, &(musicFiles), 0); - break; - } + case AUDIOBOOK_LOOP: { // Tracks need to be alph. sorted! + gPlayProperties.repeatPlaylist = true; + gPlayProperties.saveLastPlayPosition = true; + Log_Println((char *) FPSTR(modeSingleAudiobookLoop), LOGLEVEL_NOTICE); + #ifdef MQTT_ENABLE + publishMqtt((char *) FPSTR(topicPlaymodeState), gPlayProperties.playMode, false); + publishMqtt((char *) FPSTR(topicRepeatModeState), PLAYLIST, false); + #endif + AudioPlayer_SortPlaylist((const char **)musicFiles, strtoul(*(musicFiles - 1), NULL, 10)); + xQueueSend(gTrackQueue, &(musicFiles), 0); + break; + } - case ALL_TRACKS_OF_DIR_RANDOM: - { - Log_Println((char *)FPSTR(modeAllTrackRandom), LOGLEVEL_NOTICE); - AudioPlayer_SortPlaylist(musicFiles, strtoul(*(musicFiles - 1), NULL, 10)); -#ifdef MQTT_ENABLE - publishMqtt((char *)FPSTR(topicPlaymodeState), gPlayProperties.playMode, false); - publishMqtt((char *)FPSTR(topicRepeatModeState), NO_REPEAT, false); -#endif - xQueueSend(gTrackQueue, &(musicFiles), 0); - break; - } + case ALL_TRACKS_OF_DIR_SORTED: { + snprintf(Log_Buffer, Log_BufferLength, "%s '%s' ", (char *) FPSTR(modeAllTrackAlphSorted), filename); + Log_Println(Log_Buffer, LOGLEVEL_NOTICE); + AudioPlayer_SortPlaylist((const char **)musicFiles, strtoul(*(musicFiles - 1), NULL, 10)); + #ifdef MQTT_ENABLE + publishMqtt((char *) FPSTR(topicPlaymodeState), gPlayProperties.playMode, false); + publishMqtt((char *) FPSTR(topicRepeatModeState), NO_REPEAT, false); + #endif + xQueueSend(gTrackQueue, &(musicFiles), 0); + break; + } - case ALL_TRACKS_OF_DIR_SORTED_LOOP: - { - gPlayProperties.repeatPlaylist = true; - Log_Println((char *)FPSTR(modeAllTrackAlphSortedLoop), LOGLEVEL_NOTICE); - AudioPlayer_SortPlaylist((const char **)musicFiles, strtoul(*(musicFiles - 1), NULL, 10)); -#ifdef MQTT_ENABLE - publishMqtt((char *)FPSTR(topicPlaymodeState), gPlayProperties.playMode, false); - publishMqtt((char *)FPSTR(topicRepeatModeState), PLAYLIST, false); -#endif - xQueueSend(gTrackQueue, &(musicFiles), 0); - break; - } + case ALL_TRACKS_OF_DIR_RANDOM: { + Log_Println((char *) FPSTR(modeAllTrackRandom), LOGLEVEL_NOTICE); + AudioPlayer_SortPlaylist(musicFiles, strtoul(*(musicFiles - 1), NULL, 10)); + #ifdef MQTT_ENABLE + publishMqtt((char *) FPSTR(topicPlaymodeState), gPlayProperties.playMode, false); + publishMqtt((char *) FPSTR(topicRepeatModeState), NO_REPEAT, false); + #endif + xQueueSend(gTrackQueue, &(musicFiles), 0); + break; + } - case ALL_TRACKS_OF_DIR_RANDOM_LOOP: - { - gPlayProperties.repeatPlaylist = true; - Log_Println((char *)FPSTR(modeAllTrackRandomLoop), LOGLEVEL_NOTICE); - AudioPlayer_SortPlaylist(musicFiles, strtoul(*(musicFiles - 1), NULL, 10)); -#ifdef MQTT_ENABLE - publishMqtt((char *)FPSTR(topicPlaymodeState), gPlayProperties.playMode, false); - publishMqtt((char *)FPSTR(topicRepeatModeState), PLAYLIST, false); -#endif - xQueueSend(gTrackQueue, &(musicFiles), 0); - break; - } + case ALL_TRACKS_OF_DIR_SORTED_LOOP: { + gPlayProperties.repeatPlaylist = true; + Log_Println((char *) FPSTR(modeAllTrackAlphSortedLoop), LOGLEVEL_NOTICE); + AudioPlayer_SortPlaylist((const char **)musicFiles, strtoul(*(musicFiles - 1), NULL, 10)); + #ifdef MQTT_ENABLE + publishMqtt((char *) FPSTR(topicPlaymodeState), gPlayProperties.playMode, false); + publishMqtt((char *) FPSTR(topicRepeatModeState), PLAYLIST, false); + #endif + xQueueSend(gTrackQueue, &(musicFiles), 0); + break; + } - case WEBSTREAM: - { // This is always just one "track" - Log_Println((char *)FPSTR(modeWebstream), LOGLEVEL_NOTICE); - if (Wlan_IsConnected()) - { + case ALL_TRACKS_OF_DIR_RANDOM_LOOP: { + gPlayProperties.repeatPlaylist = true; + Log_Println((char *) FPSTR(modeAllTrackRandomLoop), LOGLEVEL_NOTICE); + AudioPlayer_SortPlaylist(musicFiles, strtoul(*(musicFiles - 1), NULL, 10)); + #ifdef MQTT_ENABLE + publishMqtt((char *) FPSTR(topicPlaymodeState), gPlayProperties.playMode, false); + publishMqtt((char *) FPSTR(topicRepeatModeState), PLAYLIST, false); + #endif xQueueSend(gTrackQueue, &(musicFiles), 0); -#ifdef MQTT_ENABLE - publishMqtt((char *)FPSTR(topicPlaymodeState), gPlayProperties.playMode, false); - publishMqtt((char *)FPSTR(topicRepeatModeState), NO_REPEAT, false); -#endif + break; } - else - { - Log_Println((char *)FPSTR(webstreamNotAvailable), LOGLEVEL_ERROR); - System_IndicateError(); - gPlayProperties.playMode = NO_PLAYLIST; + + case WEBSTREAM: { // This is always just one "track" + Log_Println((char *) FPSTR(modeWebstream), LOGLEVEL_NOTICE); + if (Wlan_IsConnected()) { + xQueueSend(gTrackQueue, &(musicFiles), 0); + #ifdef MQTT_ENABLE + publishMqtt((char *) FPSTR(topicPlaymodeState), gPlayProperties.playMode, false); + publishMqtt((char *) FPSTR(topicRepeatModeState), NO_REPEAT, false); + #endif + } else { + Log_Println((char *) FPSTR(webstreamNotAvailable), LOGLEVEL_ERROR); + System_IndicateError(); + gPlayProperties.playMode = NO_PLAYLIST; + } + break; } - break; - } - default: - Log_Println((char *)FPSTR(modeDoesNotExist), LOGLEVEL_ERROR); - gPlayProperties.playMode = NO_PLAYLIST; - System_IndicateError(); + default: + Log_Println((char *) FPSTR(modeDoesNotExist), LOGLEVEL_ERROR); + gPlayProperties.playMode = NO_PLAYLIST; + System_IndicateError(); } free(filename); } /* Wraps putString for writing settings into NVS for RFID-cards. Returns number of characters written. */ -size_t AudioPlayer_NvsRfidWriteWrapper(const char *_rfidCardId, const char *_track, const uint32_t _playPosition, const uint8_t _playMode, const uint16_t _trackLastPlayed, const uint16_t _numberOfTracks) -{ +size_t AudioPlayer_NvsRfidWriteWrapper(const char *_rfidCardId, const char *_track, const uint32_t _playPosition, const uint8_t _playMode, const uint16_t _trackLastPlayed, const uint16_t _numberOfTracks) { Led_SetPause(true); // Workaround to prevent exceptions due to Neopixel-signalisation while NVS-write char prefBuf[275]; char trackBuf[255]; snprintf(trackBuf, sizeof(trackBuf) / sizeof(trackBuf[0]), _track); // If it's a directory we just want to play/save basename(path) - if (_numberOfTracks > 1) - { + if (_numberOfTracks > 1) { const char s = '/'; char *last = strrchr(_track, s); char *first = strchr(_track, s); unsigned long substr = last - first + 1; - if (substr <= sizeof(trackBuf) / sizeof(trackBuf[0])) - { + if (substr <= sizeof(trackBuf) / sizeof(trackBuf[0])) { snprintf(trackBuf, substr, _track); // save substring basename(_track) - } - else - { + } else { return 0; // Filename too long! } } snprintf(prefBuf, sizeof(prefBuf) / sizeof(prefBuf[0]), "%s%s%s%u%s%d%s%u", stringDelimiter, trackBuf, stringDelimiter, _playPosition, stringDelimiter, _playMode, stringDelimiter, _trackLastPlayed); -#if (LANGUAGE == 1) - snprintf(Log_Buffer, Log_BufferLength, "Schreibe '%s' in NVS für RFID-Card-ID %s mit playmode %d und letzter Track %u\n", prefBuf, _rfidCardId, _playMode, _trackLastPlayed); -#else - snprintf(Log_Buffer, Log_BufferLength, "Write '%s' to NVS for RFID-Card-ID %s with playmode %d and last track %u\n", prefBuf, _rfidCardId, _playMode, _trackLastPlayed); -#endif + #if (LANGUAGE == 1) + snprintf(Log_Buffer, Log_BufferLength, "Schreibe '%s' in NVS für RFID-Card-ID %s mit playmode %d und letzter Track %u\n", prefBuf, _rfidCardId, _playMode, _trackLastPlayed); + #else + snprintf(Log_Buffer, Log_BufferLength, "Write '%s' to NVS for RFID-Card-ID %s with playmode %d and last track %u\n", prefBuf, _rfidCardId, _playMode, _trackLastPlayed); + #endif Log_Print(Log_Buffer, LOGLEVEL_INFO); Log_Println(prefBuf, LOGLEVEL_INFO); Led_SetPause(false); @@ -1020,13 +858,11 @@ size_t AudioPlayer_NvsRfidWriteWrapper(const char *_rfidCardId, const char *_tra } // Adds webstream to playlist; same like SdCard_ReturnPlaylist() but always only one entry -char **AudioPlayer_ReturnPlaylistFromWebstream(const char *_webUrl) -{ +char **AudioPlayer_ReturnPlaylistFromWebstream(const char *_webUrl) { char *webUrl = x_strdup(_webUrl); static char **url; - if (url != NULL) - { + if (url != NULL) { --url; freeMultiCharArray(url, strtoul(*url, NULL, 10)); } @@ -1041,16 +877,13 @@ char **AudioPlayer_ReturnPlaylistFromWebstream(const char *_webUrl) } // Adds new control-command to control-queue -void AudioPlayer_TrackControlToQueueSender(const uint8_t trackCommand) -{ +void AudioPlayer_TrackControlToQueueSender(const uint8_t trackCommand) { xQueueSend(gTrackControlQueue, &trackCommand, 0); } // Knuth-Fisher-Yates-algorithm to randomize playlist -void AudioPlayer_SortPlaylist(char *str[], const uint32_t count) -{ - if (count < 1) - { +void AudioPlayer_SortPlaylist(char *str[], const uint32_t count) { + if (count < 1) { return; } @@ -1058,14 +891,10 @@ void AudioPlayer_SortPlaylist(char *str[], const uint32_t count) char *swap = NULL; uint32_t max = count - 1; - for (i = 0; i < count; i++) - { - if (max > 0) - { + for (i = 0; i < count; i++) { + if (max > 0) { r = rand() % max; - } - else - { + } else { r = 0; } swap = *(str + max); @@ -1076,66 +905,64 @@ void AudioPlayer_SortPlaylist(char *str[], const uint32_t count) } // Helper to sort playlist alphabetically -static int AudioPlayer_ArrSortHelper(const void *a, const void *b) -{ +static int AudioPlayer_ArrSortHelper(const void *a, const void *b) { return strcmp(*(const char **)a, *(const char **)b); } // Sort playlist alphabetically -void AudioPlayer_SortPlaylist(const char **arr, int n) -{ +void AudioPlayer_SortPlaylist(const char **arr, int n) { qsort(arr, n, sizeof(const char *), AudioPlayer_ArrSortHelper); } // Some mp3-lib-stuff (slightly changed from default) -void audio_info(const char *info) -{ +void audio_info(const char *info) { snprintf(Log_Buffer, Log_BufferLength, "info : %s", info); Log_Println(Log_Buffer, LOGLEVEL_INFO); } -void audio_id3data(const char *info) -{ //id3 metadata + +void audio_id3data(const char *info) { //id3 metadata snprintf(Log_Buffer, Log_BufferLength, "id3data : %s", info); Log_Println(Log_Buffer, LOGLEVEL_INFO); } -void audio_eof_mp3(const char *info) -{ //end of file + +void audio_eof_mp3(const char *info) { //end of file snprintf(Log_Buffer, Log_BufferLength, "eof_mp3 : %s", info); Log_Println(Log_Buffer, LOGLEVEL_INFO); gPlayProperties.trackFinished = true; } -void audio_showstation(const char *info) -{ + +void audio_showstation(const char *info) { snprintf(Log_Buffer, Log_BufferLength, "station : %s", info); Log_Println(Log_Buffer, LOGLEVEL_NOTICE); char buf[255]; snprintf(buf, sizeof(buf) / sizeof(buf[0]), "Webradio: %s", info); -#ifdef MQTT_ENABLE - publishMqtt((char *)FPSTR(topicTrackState), buf, false); -#endif + #ifdef MQTT_ENABLE + publishMqtt((char *) FPSTR(topicTrackState), buf, false); + #endif } + void audio_showstreamtitle(const char *info) { snprintf(Log_Buffer, Log_BufferLength, "streamtitle : %s", info); Log_Println(Log_Buffer, LOGLEVEL_INFO); } -void audio_bitrate(const char *info) -{ + +void audio_bitrate(const char *info) { snprintf(Log_Buffer, Log_BufferLength, "bitrate : %s", info); Log_Println(Log_Buffer, LOGLEVEL_INFO); } -void audio_commercial(const char *info) -{ //duration in sec + +void audio_commercial(const char *info) { //duration in sec snprintf(Log_Buffer, Log_BufferLength, "commercial : %s", info); Log_Println(Log_Buffer, LOGLEVEL_INFO); } -void audio_icyurl(const char *info) -{ //homepage + +void audio_icyurl(const char *info) { //homepage snprintf(Log_Buffer, Log_BufferLength, "icyurl : %s", info); Log_Println(Log_Buffer, LOGLEVEL_INFO); } -void audio_lasthost(const char *info) -{ //stream URL played + +void audio_lasthost(const char *info) { //stream URL played snprintf(Log_Buffer, Log_BufferLength, "lasthost : %s", info); Log_Println(Log_Buffer, LOGLEVEL_INFO); -} \ No newline at end of file +} diff --git a/src/Battery.cpp b/src/Battery.cpp index 46bf440..69ce5c9 100644 --- a/src/Battery.cpp +++ b/src/Battery.cpp @@ -13,101 +13,83 @@ uint8_t voltageCheckInterval = s_voltageCheckInterval; float voltageIndicatorLow = s_voltageIndicatorLow; float voltageIndicatorHigh = s_voltageIndicatorHigh; -void Battery_Init() -{ -#ifdef MEASURE_BATTERY_VOLTAGE - // Get voltages from NVS for Neopixel - float vLowIndicator = gPrefsSettings.getFloat("vIndicatorLow", 999.99); - 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 - gPrefsSettings.putFloat("vIndicatorLow", voltageIndicatorLow); - } +void Battery_Init() { + #ifdef MEASURE_BATTERY_VOLTAGE + // Get voltages from NVS for Neopixel + float vLowIndicator = gPrefsSettings.getFloat("vIndicatorLow", 999.99); + 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 + gPrefsSettings.putFloat("vIndicatorLow", voltageIndicatorLow); + } - float vHighIndicator = gPrefsSettings.getFloat("vIndicatorHigh", 999.99); - if (vHighIndicator <= 999) - { - voltageIndicatorHigh = vHighIndicator; - snprintf(Log_Buffer, Log_BufferLength, "%s: %.2f V", (char *)FPSTR(voltageIndicatorHighFromNVS), vHighIndicator); - Log_Println(Log_Buffer, LOGLEVEL_INFO); - } - else - { - gPrefsSettings.putFloat("vIndicatorHigh", voltageIndicatorHigh); - } + float vHighIndicator = gPrefsSettings.getFloat("vIndicatorHigh", 999.99); + if (vHighIndicator <= 999) { + voltageIndicatorHigh = vHighIndicator; + snprintf(Log_Buffer, Log_BufferLength, "%s: %.2f V", (char *) FPSTR(voltageIndicatorHighFromNVS), vHighIndicator); + Log_Println(Log_Buffer, LOGLEVEL_INFO); + } else { + gPrefsSettings.putFloat("vIndicatorHigh", voltageIndicatorHigh); + } - float vLowWarning = gPrefsSettings.getFloat("wLowVoltage", 999.99); - if (vLowWarning <= 999) - { - warningLowVoltage = vLowWarning; - snprintf(Log_Buffer, Log_BufferLength, "%s: %.2f V", (char *)FPSTR(warningLowVoltageFromNVS), vLowWarning); - Log_Println(Log_Buffer, LOGLEVEL_INFO); - } - else - { - gPrefsSettings.putFloat("wLowVoltage", warningLowVoltage); - } + float vLowWarning = gPrefsSettings.getFloat("wLowVoltage", 999.99); + if (vLowWarning <= 999) { + warningLowVoltage = vLowWarning; + snprintf(Log_Buffer, Log_BufferLength, "%s: %.2f V", (char *) FPSTR(warningLowVoltageFromNVS), vLowWarning); + Log_Println(Log_Buffer, LOGLEVEL_INFO); + } else { + gPrefsSettings.putFloat("wLowVoltage", warningLowVoltage); + } - uint32_t vInterval = gPrefsSettings.getUInt("vCheckIntv", 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 - { - gPrefsSettings.putUInt("vCheckIntv", voltageCheckInterval); - } -#endif + uint32_t vInterval = gPrefsSettings.getUInt("vCheckIntv", 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 { + 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) -{ -#ifdef MEASURE_BATTERY_VOLTAGE - float factor = 1 / ((float)rdiv2 / (rdiv2 + rdiv1)); - float averagedAnalogValue = 0; - uint8_t i; - for (i = 0; i <= 19; i++) - { - averagedAnalogValue += (float)analogRead(VOLTAGE_READ_PIN); - } - averagedAnalogValue /= 20.0; - return (averagedAnalogValue / maxAnalogValue) * referenceVoltage * factor + offsetVoltage; -#endif +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++) { + averagedAnalogValue += (float) analogRead(VOLTAGE_READ_PIN); + } + averagedAnalogValue /= 20.0; + return (averagedAnalogValue / maxAnalogValue) * referenceVoltage * factor + offsetVoltage; + #endif } // Measures voltage of a battery as per interval or after bootup (after allowing a few seconds to settle down) -void Battery_Cyclic(void) -{ -#ifdef MEASURE_BATTERY_VOLTAGE - static uint32_t lastVoltageCheckTimestamp = 0; +void Battery_Cyclic(void) { + #ifdef MEASURE_BATTERY_VOLTAGE + static uint32_t lastVoltageCheckTimestamp = 0; - if ((millis() - lastVoltageCheckTimestamp >= voltageCheckInterval * 60000) || (!lastVoltageCheckTimestamp && millis() >= 10000)) - { - float voltage = Battery_GetVoltage(); + if ((millis() - lastVoltageCheckTimestamp >= voltageCheckInterval * 60000) || (!lastVoltageCheckTimestamp && millis() >= 10000)) { + float voltage = Battery_GetVoltage(); - 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); - } + 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); + } -#ifdef MQTT_ENABLE - char vstr[6]; - snprintf(vstr, 6, "%.2f", voltage); - publishMqtt((char *)FPSTR(topicBatteryVoltage), vstr, false); -#endif - snprintf(Log_Buffer, Log_BufferLength, "%s: %.2f V", (char *)FPSTR(currentVoltageMsg), voltage); - Log_Println(Log_Buffer, LOGLEVEL_INFO); - lastVoltageCheckTimestamp = millis(); - } -#endif -} \ No newline at end of file + #ifdef MQTT_ENABLE + char vstr[6]; + snprintf(vstr, 6, "%.2f", voltage); + publishMqtt((char *) FPSTR(topicBatteryVoltage), vstr, false); + #endif + snprintf(Log_Buffer, Log_BufferLength, "%s: %.2f V", (char *) FPSTR(currentVoltageMsg), voltage); + Log_Println(Log_Buffer, LOGLEVEL_INFO); + lastVoltageCheckTimestamp = millis(); + } + #endif +} diff --git a/src/Bluetooth.cpp b/src/Bluetooth.cpp index 075a065..8a5c62d 100644 --- a/src/Bluetooth.cpp +++ b/src/Bluetooth.cpp @@ -4,43 +4,37 @@ #include "System.h" #ifdef BLUETOOTH_ENABLE -#include "esp_bt.h" -#include "BluetoothA2DPSink.h" + #include "esp_bt.h" + #include "BluetoothA2DPSink.h" #endif #ifdef BLUETOOTH_ENABLE -BluetoothA2DPSink *a2dp_sink; + BluetoothA2DPSink *a2dp_sink; #endif -void Bluetooth_Init(void) -{ -#ifdef BLUETOOTH_ENABLE - if (System_GetOperationMode() == OPMODE_BLUETOOTH) - { - a2dp_sink = new BluetoothA2DPSink(); - i2s_pin_config_t pin_config = { - .bck_io_num = I2S_BCLK, - .ws_io_num = I2S_LRC, - .data_out_num = I2S_DOUT, - .data_in_num = I2S_PIN_NO_CHANGE}; - a2dp_sink->set_pin_config(pin_config); - a2dp_sink->start((char *)FPSTR(nameBluetoothDevice)); - } - else - { - esp_bt_mem_release(ESP_BT_MODE_BTDM); - } -#endif +void Bluetooth_Init(void) { + #ifdef BLUETOOTH_ENABLE + if (System_GetOperationMode() == OPMODE_BLUETOOTH) { + a2dp_sink = new BluetoothA2DPSink(); + i2s_pin_config_t pin_config = { + .bck_io_num = I2S_BCLK, + .ws_io_num = I2S_LRC, + .data_out_num = I2S_DOUT, + .data_in_num = I2S_PIN_NO_CHANGE}; + a2dp_sink->set_pin_config(pin_config); + a2dp_sink->start((char *)FPSTR(nameBluetoothDevice)); + } else { + esp_bt_mem_release(ESP_BT_MODE_BTDM); + } + #endif } -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) - { - System_UpdateActivityTimer(); - } -#endif +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) { + System_UpdateActivityTimer(); + } + #endif } diff --git a/src/Button.cpp b/src/Button.cpp index 461b6fa..eec611a 100644 --- a/src/Button.cpp +++ b/src/Button.cpp @@ -48,71 +48,69 @@ uint8_t gShutdownButton = 99; // Helper used for Neopixel: stores button-number static volatile SemaphoreHandle_t Button_TimerSemaphore; #ifndef IR_CONTROL_ENABLE -hw_timer_t *Button_Timer = NULL; + hw_timer_t *Button_Timer = NULL; #endif static void IRAM_ATTR onTimer(); - static void Button_DoButtonActions(void); -void Button_Init() -{ -#if (WAKEUP_BUTTON <= 39) - esp_sleep_enable_ext0_wakeup((gpio_num_t)WAKEUP_BUTTON, 0); -#endif +void Button_Init() { + #if (WAKEUP_BUTTON <= 39) + esp_sleep_enable_ext0_wakeup((gpio_num_t)WAKEUP_BUTTON, 0); + #endif -#ifdef NEOPIXEL_ENABLE // Try to find button that is used for shutdown via longpress-action (only necessary for Neopixel) -#if defined(BUTTON_0_ENABLE) || defined(EXPANDER_0_ENABLE) -#if (BUTTON_0_LONG == CMD_SLEEPMODE) - gShutdownButton = 0; -#endif -#endif -#if defined(BUTTON_1_ENABLE) || defined(EXPANDER_1_ENABLE) -#if (BUTTON_1_LONG == CMD_SLEEPMODE) - gShutdownButton = 1; -#endif -#endif -#if defined(BUTTON_2_ENABLE) || defined(EXPANDER_2_ENABLE) -#if (BUTTON_2_LONG == CMD_SLEEPMODE) - gShutdownButton = 2; -#endif -#endif -#if defined(BUTTON_3_ENABLE) || defined(EXPANDER_3_ENABLE) -#if (BUTTON_3_LONG == CMD_SLEEPMODE) - gShutdownButton = 3; -#endif -#endif -#if defined(BUTTON_4_ENABLE) || defined(EXPANDER_4_ENABLE) -#if (BUTTON_4_LONG == CMD_SLEEPMODE) - gShutdownButton = 4; -#endif -#endif -#if defined(BUTTON_5_ENABLE) || defined(EXPANDER_5_ENABLE) -#if (BUTTON_5_LONG == CMD_SLEEPMODE) - gShutdownButton = 5; -#endif -#endif -#endif + #ifdef NEOPIXEL_ENABLE // Try to find button that is used for shutdown via longpress-action (only necessary for Neopixel) + #if defined(BUTTON_0_ENABLE) || defined(EXPANDER_0_ENABLE) + #if (BUTTON_0_LONG == CMD_SLEEPMODE) + gShutdownButton = 0; + #endif + #endif + #if defined(BUTTON_1_ENABLE) || defined(EXPANDER_1_ENABLE) + #if (BUTTON_1_LONG == CMD_SLEEPMODE) + gShutdownButton = 1; + #endif + #endif + #if defined(BUTTON_2_ENABLE) || defined(EXPANDER_2_ENABLE) + #if (BUTTON_2_LONG == CMD_SLEEPMODE) + gShutdownButton = 2; + #endif + #endif + #if defined(BUTTON_3_ENABLE) || defined(EXPANDER_3_ENABLE) + #if (BUTTON_3_LONG == CMD_SLEEPMODE) + gShutdownButton = 3; + #endif + #endif + #if defined(BUTTON_4_ENABLE) || defined(EXPANDER_4_ENABLE) + #if (BUTTON_4_LONG == CMD_SLEEPMODE) + gShutdownButton = 4; + #endif + #endif + #if defined(BUTTON_5_ENABLE) || defined(EXPANDER_5_ENABLE) + #if (BUTTON_5_LONG == CMD_SLEEPMODE) + gShutdownButton = 5; + #endif + #endif + #endif -// Activate internal pullups for all enabled buttons -#ifdef BUTTON_0_ENABLE - pinMode(NEXT_BUTTON, INPUT_PULLUP); -#endif -#ifdef BUTTON_1_ENABLE - pinMode(PREVIOUS_BUTTON, INPUT_PULLUP); -#endif -#ifdef BUTTON_2_ENABLE - pinMode(PAUSEPLAY_BUTTON, INPUT_PULLUP); -#endif -#ifdef BUTTON_3_ENABLE - pinMode(DREHENCODER_BUTTON, INPUT_PULLUP); -#endif -#ifdef BUTTON_4_ENABLE - pinMode(BUTTON_4, INPUT_PULLUP); -#endif -#ifdef BUTTON_5_ENABLE - pinMode(BUTTON_5, INPUT_PULLUP); -#endif + // Activate internal pullups for all enabled buttons + #ifdef BUTTON_0_ENABLE + pinMode(NEXT_BUTTON, INPUT_PULLUP); + #endif + #ifdef BUTTON_1_ENABLE + pinMode(PREVIOUS_BUTTON, INPUT_PULLUP); + #endif + #ifdef BUTTON_2_ENABLE + pinMode(PAUSEPLAY_BUTTON, INPUT_PULLUP); + #endif + #ifdef BUTTON_3_ENABLE + pinMode(DREHENCODER_BUTTON, INPUT_PULLUP); + #endif + #ifdef BUTTON_4_ENABLE + pinMode(BUTTON_4, INPUT_PULLUP); + #endif + #ifdef BUTTON_5_ENABLE + pinMode(BUTTON_5, INPUT_PULLUP); + #endif // Create 1000Hz-HW-Timer (currently only used for buttons) Button_TimerSemaphore = xSemaphoreCreateBinary(); @@ -123,37 +121,34 @@ 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; } - + unsigned long currentTimestamp = millis(); -// Buttons can be mixed between GPIO and port-expander. -// But at the same time only one of them can be for example NEXT_BUTTON -#if defined(BUTTON_0_ENABLE) || defined(EXPANDER_0_ENABLE) - gButtons[0].currentState = Port_Read(NEXT_BUTTON); -#endif -#if defined(BUTTON_1_ENABLE) || defined(EXPANDER_1_ENABLE) - gButtons[1].currentState = Port_Read(PREVIOUS_BUTTON); -#endif -#if defined(BUTTON_2_ENABLE) || defined(EXPANDER_2_ENABLE) - gButtons[2].currentState = Port_Read(PAUSEPLAY_BUTTON); -#endif -#if defined(BUTTON_3_ENABLE) || defined(EXPANDER_3_ENABLE) - gButtons[3].currentState = Port_Read(DREHENCODER_BUTTON); -#endif -#if defined(BUTTON_4_ENABLE) || defined(EXPANDER_4_ENABLE) - gButtons[4].currentState = Port_Read(BUTTON_4); -#endif -#if defined(BUTTON_5_ENABLE) || defined(EXPANDER_5_ENABLE) - gButtons[5].currentState = Port_Read(BUTTON_5); -#endif + // Buttons can be mixed between GPIO and port-expander. + // But at the same time only one of them can be for example NEXT_BUTTON + #if defined(BUTTON_0_ENABLE) || defined(EXPANDER_0_ENABLE) + gButtons[0].currentState = Port_Read(NEXT_BUTTON); + #endif + #if defined(BUTTON_1_ENABLE) || defined(EXPANDER_1_ENABLE) + gButtons[1].currentState = Port_Read(PREVIOUS_BUTTON); + #endif + #if defined(BUTTON_2_ENABLE) || defined(EXPANDER_2_ENABLE) + gButtons[2].currentState = Port_Read(PAUSEPLAY_BUTTON); + #endif + #if defined(BUTTON_3_ENABLE) || defined(EXPANDER_3_ENABLE) + gButtons[3].currentState = Port_Read(DREHENCODER_BUTTON); + #endif + #if defined(BUTTON_4_ENABLE) || defined(EXPANDER_4_ENABLE) + gButtons[4].currentState = Port_Read(BUTTON_4); + #endif + #if defined(BUTTON_5_ENABLE) || defined(EXPANDER_5_ENABLE) + gButtons[5].currentState = Port_Read(BUTTON_5); + #endif // Iterate over all buttons in struct-array for (uint8_t i = 0; i < sizeof(gButtons) / sizeof(gButtons[0]); i++) @@ -180,172 +175,133 @@ 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 - { - case 0: - Cmd_Action(BUTTON_0_LONG); - gButtons[i].isPressed = false; - break; + } 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; + break; - case 1: - Cmd_Action(BUTTON_1_LONG); - gButtons[i].isPressed = false; - break; + case 1: + Cmd_Action(BUTTON_1_LONG); + gButtons[i].isPressed = false; + break; - case 2: - Cmd_Action(BUTTON_2_LONG); - gButtons[i].isPressed = false; - break; + case 2: + Cmd_Action(BUTTON_2_LONG); + gButtons[i].isPressed = false; + break; - case 3: - Cmd_Action(BUTTON_3_LONG); - gButtons[i].isPressed = false; - break; + case 3: + Cmd_Action(BUTTON_3_LONG); + gButtons[i].isPressed = false; + break; - case 4: - Cmd_Action(BUTTON_4_LONG); - gButtons[i].isPressed = false; - break; + case 4: + Cmd_Action(BUTTON_4_LONG); + gButtons[i].isPressed = false; + break; - case 5: - Cmd_Action(BUTTON_5_LONG); - gButtons[i].isPressed = false; - break; + case 5: + Cmd_Action(BUTTON_5_LONG); + gButtons[i].isPressed = false; + break; } - } - else - { - switch (i) // Short-press-actions - { - case 0: - Cmd_Action(BUTTON_0_SHORT); - gButtons[i].isPressed = false; - break; + } else { + switch (i) { // Short-press-actions + case 0: + Cmd_Action(BUTTON_0_SHORT); + gButtons[i].isPressed = false; + break; - case 1: - Cmd_Action(BUTTON_1_SHORT); - gButtons[i].isPressed = false; - break; + case 1: + Cmd_Action(BUTTON_1_SHORT); + gButtons[i].isPressed = false; + break; - case 2: - Cmd_Action(BUTTON_2_SHORT); - gButtons[i].isPressed = false; - break; + case 2: + Cmd_Action(BUTTON_2_SHORT); + gButtons[i].isPressed = false; + break; - case 3: - Cmd_Action(BUTTON_3_SHORT); - gButtons[i].isPressed = false; - break; + case 3: + Cmd_Action(BUTTON_3_SHORT); + gButtons[i].isPressed = false; + break; - case 4: - Cmd_Action(BUTTON_4_SHORT); - gButtons[i].isPressed = false; - break; + case 4: + Cmd_Action(BUTTON_4_SHORT); + gButtons[i].isPressed = false; + break; - case 5: - Cmd_Action(BUTTON_5_SHORT); - gButtons[i].isPressed = false; - break; + case 5: + Cmd_Action(BUTTON_5_SHORT); + gButtons[i].isPressed = false; + break; } } } @@ -354,7 +310,6 @@ void Button_DoButtonActions(void) } } -void IRAM_ATTR onTimer() -{ +void IRAM_ATTR onTimer() { xSemaphoreGiveFromISR(Button_TimerSemaphore, NULL); } diff --git a/src/Cmd.cpp b/src/Cmd.cpp index 034dca6..dfb0484 100644 --- a/src/Cmd.cpp +++ b/src/Cmd.cpp @@ -10,372 +10,328 @@ #include "System.h" #include "Wlan.h" -void Cmd_Action(const uint16_t mod) -{ - switch (mod) - { - case LOCK_BUTTONS_MOD: - { // Locks/unlocks all buttons - System_ToggleLockControls(); - break; - } +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 - System_SetSleepTimer(15u); + case SLEEP_TIMER_MOD_15: { // Enables/disables sleep after 15 minutes + System_SetSleepTimer(15u); - gPlayProperties.sleepAfterCurrentTrack = false; // deactivate/overwrite if already active - gPlayProperties.sleepAfterPlaylist = false; // deactivate/overwrite if already active - gPlayProperties.playUntilTrackNumber = 0; - System_IndicateOk(); - break; - } + gPlayProperties.sleepAfterCurrentTrack = false; // deactivate/overwrite if already active + gPlayProperties.sleepAfterPlaylist = false; // deactivate/overwrite if already active + gPlayProperties.playUntilTrackNumber = 0; + System_IndicateOk(); + break; + } - case SLEEP_TIMER_MOD_30: - { // Enables/disables sleep after 30 minutes - System_SetSleepTimer(30u); + case SLEEP_TIMER_MOD_30: { // Enables/disables sleep after 30 minutes + System_SetSleepTimer(30u); - gPlayProperties.sleepAfterCurrentTrack = false; // deactivate/overwrite if already active - gPlayProperties.sleepAfterPlaylist = false; // deactivate/overwrite if already active - gPlayProperties.playUntilTrackNumber = 0; - System_IndicateOk(); - break; - } + gPlayProperties.sleepAfterCurrentTrack = false; // deactivate/overwrite if already active + gPlayProperties.sleepAfterPlaylist = false; // deactivate/overwrite if already active + gPlayProperties.playUntilTrackNumber = 0; + System_IndicateOk(); + break; + } - case SLEEP_TIMER_MOD_60: - { // Enables/disables sleep after 60 minutes - System_SetSleepTimer(60u); + case SLEEP_TIMER_MOD_60: { // Enables/disables sleep after 60 minutes + System_SetSleepTimer(60u); - gPlayProperties.sleepAfterCurrentTrack = false; // deactivate/overwrite if already active - gPlayProperties.sleepAfterPlaylist = false; // deactivate/overwrite if already active - gPlayProperties.playUntilTrackNumber = 0; - System_IndicateOk(); - break; - } + gPlayProperties.sleepAfterCurrentTrack = false; // deactivate/overwrite if already active + gPlayProperties.sleepAfterPlaylist = false; // deactivate/overwrite if already active + gPlayProperties.playUntilTrackNumber = 0; + System_IndicateOk(); + break; + } - case SLEEP_TIMER_MOD_120: - { // Enables/disables sleep after 2 hrs - System_SetSleepTimer(120u); + case SLEEP_TIMER_MOD_120: { // Enables/disables sleep after 2 hrs + System_SetSleepTimer(120u); - gPlayProperties.sleepAfterCurrentTrack = false; // deactivate/overwrite if already active - gPlayProperties.sleepAfterPlaylist = false; // deactivate/overwrite if already active - gPlayProperties.playUntilTrackNumber = 0; - System_IndicateOk(); - break; - } + gPlayProperties.sleepAfterCurrentTrack = false; // deactivate/overwrite if already active + gPlayProperties.sleepAfterPlaylist = false; // deactivate/overwrite if already active + gPlayProperties.playUntilTrackNumber = 0; + System_IndicateOk(); + break; + } - 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; + 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) { + Log_Println((char *) FPSTR(modificatorSleepAtEOTd), LOGLEVEL_NOTICE); + #ifdef MQTT_ENABLE + publishMqtt((char *) FPSTR(topicSleepTimerState), "0", false); + #endif + #ifdef NEOPIXEL_ENABLE + Led_ResetToInitialBrightness(); + #endif + } + else + { + Log_Println((char *) FPSTR(modificatorSleepAtEOT), LOGLEVEL_NOTICE); + #ifdef MQTT_ENABLE + publishMqtt((char *) FPSTR(topicSleepTimerState), "EOT", false); + #endif + #ifdef NEOPIXEL_ENABLE + Led_ResetToNightBrightness(); + Log_Println((char *) FPSTR(ledsDimmedToNightmode), LOGLEVEL_INFO); + #endif + } + gPlayProperties.sleepAfterCurrentTrack = !gPlayProperties.sleepAfterCurrentTrack; + gPlayProperties.sleepAfterPlaylist = false; + System_DisableSleepTimer(); + gPlayProperties.playUntilTrackNumber = 0; + + #ifdef MQTT_ENABLE + publishMqtt((char *) FPSTR(topicLedBrightnessState), Led_GetBrightness(), false); + #endif + System_IndicateOk(); + break; } - if (gPlayProperties.sleepAfterCurrentTrack) - { - Log_Println((char *)FPSTR(modificatorSleepAtEOTd), LOGLEVEL_NOTICE); -#ifdef MQTT_ENABLE - publishMqtt((char *)FPSTR(topicSleepTimerState), "0", false); -#endif -#ifdef NEOPIXEL_ENABLE - Led_ResetToInitialBrightness(); -#endif + + 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) { + #ifdef MQTT_ENABLE + publishMqtt((char *) FPSTR(topicSleepTimerState), "0", false); + #endif + #ifdef NEOPIXEL_ENABLE + Led_ResetToInitialBrightness(); + #endif + Log_Println((char *) FPSTR(modificatorSleepAtEOPd), LOGLEVEL_NOTICE); + } else { + #ifdef NEOPIXEL_ENABLE + Led_ResetToNightBrightness(); + Log_Println((char *) FPSTR(ledsDimmedToNightmode), LOGLEVEL_INFO); + #endif + Log_Println((char *) FPSTR(modificatorSleepAtEOP), LOGLEVEL_NOTICE); + #ifdef MQTT_ENABLE + publishMqtt((char *) FPSTR(topicSleepTimerState), "EOP", false); + #endif + } + + gPlayProperties.sleepAfterCurrentTrack = false; + gPlayProperties.sleepAfterPlaylist = !gPlayProperties.sleepAfterPlaylist; + System_DisableSleepTimer(); + gPlayProperties.playUntilTrackNumber = 0; + #ifdef MQTT_ENABLE + publishMqtt((char *) FPSTR(topicLedBrightnessState), Led_GetBrightness(), false); + #endif + System_IndicateOk(); + break; } - else - { - Log_Println((char *)FPSTR(modificatorSleepAtEOT), LOGLEVEL_NOTICE); -#ifdef MQTT_ENABLE - publishMqtt((char *)FPSTR(topicSleepTimerState), "EOT", false); -#endif -#ifdef NEOPIXEL_ENABLE - Led_ResetToNightBrightness(); - Log_Println((char *)FPSTR(ledsDimmedToNightmode), LOGLEVEL_INFO); -#endif + + case SLEEP_AFTER_5_TRACKS: { + if (gPlayProperties.playMode == NO_PLAYLIST) { + Log_Println((char *) FPSTR(modificatorNotallowedWhenIdle), LOGLEVEL_NOTICE); + System_IndicateError(); + return; + } + + gPlayProperties.sleepAfterCurrentTrack = false; + gPlayProperties.sleepAfterPlaylist = false; + System_DisableSleepTimer(); + + if (gPlayProperties.playUntilTrackNumber > 0) { + gPlayProperties.playUntilTrackNumber = 0; + #ifdef MQTT_ENABLE + publishMqtt((char *) FPSTR(topicSleepTimerState), "0", false); + #endif + #ifdef NEOPIXEL_ENABLE + 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 + gPlayProperties.sleepAfterPlaylist = true; + #ifdef MQTT_ENABLE + publishMqtt((char *) FPSTR(topicSleepTimerState), "EOP", false); + #endif + } else { + gPlayProperties.playUntilTrackNumber = gPlayProperties.currentTrackNumber + 5; + #ifdef MQTT_ENABLE + publishMqtt((char *) FPSTR(topicSleepTimerState), "EO5T", false); + #endif + } + #ifdef NEOPIXEL_ENABLE + Led_ResetToNightBrightness(); + #endif + Log_Println((char *) FPSTR(sleepTimerEO5), LOGLEVEL_NOTICE); + } + + #ifdef MQTT_ENABLE + publishMqtt((char *) FPSTR(topicLedBrightnessState), Led_GetBrightness(), false); + #endif + System_IndicateOk(); + break; } - gPlayProperties.sleepAfterCurrentTrack = !gPlayProperties.sleepAfterCurrentTrack; - gPlayProperties.sleepAfterPlaylist = false; - System_DisableSleepTimer(); - gPlayProperties.playUntilTrackNumber = 0; - -#ifdef MQTT_ENABLE - publishMqtt((char *)FPSTR(topicLedBrightnessState), Led_GetBrightness(), false); -#endif - System_IndicateOk(); - 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) - { - Log_Println((char *)FPSTR(modificatorNotallowedWhenIdle), LOGLEVEL_NOTICE); - System_IndicateError(); - return; + case REPEAT_PLAYLIST: { + if (gPlayProperties.playMode == NO_PLAYLIST) { + Log_Println((char *) FPSTR(modificatorNotallowedWhenIdle), LOGLEVEL_NOTICE); + System_IndicateError(); + } else { + if (gPlayProperties.repeatPlaylist) { + Log_Println((char *) FPSTR(modificatorPlaylistLoopDeactive), LOGLEVEL_NOTICE); + } else { + Log_Println((char *) FPSTR(modificatorPlaylistLoopActive), LOGLEVEL_NOTICE); + } + gPlayProperties.repeatPlaylist = !gPlayProperties.repeatPlaylist; + char rBuf[2]; + snprintf(rBuf, 2, "%u", AudioPlayer_GetRepeatMode()); + #ifdef MQTT_ENABLE + publishMqtt((char *) FPSTR(topicRepeatModeState), rBuf, false); + #endif + System_IndicateOk(); + } + break; } - if (gPlayProperties.sleepAfterCurrentTrack) - { -#ifdef MQTT_ENABLE - publishMqtt((char *)FPSTR(topicSleepTimerState), "0", false); -#endif -#ifdef NEOPIXEL_ENABLE - Led_ResetToInitialBrightness(); -#endif - Log_Println((char *)FPSTR(modificatorSleepAtEOPd), LOGLEVEL_NOTICE); + + 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) { + Log_Println((char *) FPSTR(modificatorTrackDeactive), LOGLEVEL_NOTICE); + } else { + Log_Println((char *) FPSTR(modificatorTrackActive), LOGLEVEL_NOTICE); + } + gPlayProperties.repeatCurrentTrack = !gPlayProperties.repeatCurrentTrack; + char rBuf[2]; + snprintf(rBuf, 2, "%u", AudioPlayer_GetRepeatMode()); + #ifdef MQTT_ENABLE + publishMqtt((char *) FPSTR(topicRepeatModeState), rBuf, false); + #endif + System_IndicateOk(); + } + break; } - else - { -#ifdef NEOPIXEL_ENABLE - Led_ResetToNightBrightness(); - Log_Println((char *)FPSTR(ledsDimmedToNightmode), LOGLEVEL_INFO); -#endif - Log_Println((char *)FPSTR(modificatorSleepAtEOP), LOGLEVEL_NOTICE); -#ifdef MQTT_ENABLE - publishMqtt((char *)FPSTR(topicSleepTimerState), "EOP", false); -#endif + + case DIMM_LEDS_NIGHTMODE: { + #ifdef MQTT_ENABLE + publishMqtt((char *) FPSTR(topicLedBrightnessState), Led_GetBrightness(), false); + #endif + Log_Println((char *) FPSTR(ledsDimmedToNightmode), LOGLEVEL_INFO); + #ifdef NEOPIXEL_ENABLE + Led_ResetToNightBrightness(); + #endif + System_IndicateOk(); + break; } - gPlayProperties.sleepAfterCurrentTrack = false; - gPlayProperties.sleepAfterPlaylist = !gPlayProperties.sleepAfterPlaylist; - System_DisableSleepTimer(); - gPlayProperties.playUntilTrackNumber = 0; -#ifdef MQTT_ENABLE - publishMqtt((char *)FPSTR(topicLedBrightnessState), Led_GetBrightness(), false); -#endif - System_IndicateOk(); - break; - } + case TOGGLE_WIFI_STATUS: { + Wlan_ToggleEnable(); + System_IndicateOk(); + break; + } - case SLEEP_AFTER_5_TRACKS: - { - if (gPlayProperties.playMode == NO_PLAYLIST) - { - Log_Println((char *)FPSTR(modificatorNotallowedWhenIdle), LOGLEVEL_NOTICE); - System_IndicateError(); - return; + #ifdef BLUETOOTH_ENABLE + case TOGGLE_BLUETOOTH_MODE: { + if (System_GetOperationModeFromNvs() == OPMODE_NORMAL) { + System_IndicateOk(); + System_SetOperationMode(OPMODE_BLUETOOTH); + } else if (System_GetOperationModeFromNvs() == OPMODE_BLUETOOTH) { + System_IndicateOk(); + System_SetOperationMode(OPMODE_NORMAL); + } else { + System_IndicateError(); + } + break; + } + #endif + + #ifdef FTP_ENABLE + case ENABLE_FTP_SERVER: { + Ftp_EnableServer(); + break; + } + #endif + + case CMD_PLAYPAUSE: { + AudioPlayer_TrackControlToQueueSender(PAUSEPLAY); + break; } - gPlayProperties.sleepAfterCurrentTrack = false; - gPlayProperties.sleepAfterPlaylist = false; - System_DisableSleepTimer(); + case CMD_PREVTRACK: { + AudioPlayer_TrackControlToQueueSender(PREVIOUSTRACK); + break; + } - if (gPlayProperties.playUntilTrackNumber > 0) - { - gPlayProperties.playUntilTrackNumber = 0; -#ifdef MQTT_ENABLE - publishMqtt((char *)FPSTR(topicSleepTimerState), "0", false); -#endif -#ifdef NEOPIXEL_ENABLE - Led_ResetToInitialBrightness(); -#endif - Log_Println((char *)FPSTR(modificatorSleepd), LOGLEVEL_NOTICE); + case CMD_NEXTTRACK: { + AudioPlayer_TrackControlToQueueSender(NEXTTRACK); + break; } - 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 - { - gPlayProperties.playUntilTrackNumber = gPlayProperties.currentTrackNumber + 5; -#ifdef MQTT_ENABLE - publishMqtt((char *)FPSTR(topicSleepTimerState), "EO5T", false); -#endif - } -#ifdef NEOPIXEL_ENABLE - Led_ResetToNightBrightness(); -#endif - Log_Println((char *)FPSTR(sleepTimerEO5), LOGLEVEL_NOTICE); + + case CMD_FIRSTTRACK: { + AudioPlayer_TrackControlToQueueSender(FIRSTTRACK); + break; } -#ifdef MQTT_ENABLE - publishMqtt((char *)FPSTR(topicLedBrightnessState), Led_GetBrightness(), false); -#endif - System_IndicateOk(); - break; - } + case CMD_LASTTRACK: { + AudioPlayer_TrackControlToQueueSender(LASTTRACK); + break; + } - case REPEAT_PLAYLIST: - { - if (gPlayProperties.playMode == NO_PLAYLIST) - { - Log_Println((char *)FPSTR(modificatorNotallowedWhenIdle), LOGLEVEL_NOTICE); - System_IndicateError(); + case CMD_VOLUMEINIT: { + AudioPlayer_VolumeToQueueSender(AudioPlayer_GetInitVolume(), true); + break; } - else - { - if (gPlayProperties.repeatPlaylist) - { - Log_Println((char *)FPSTR(modificatorPlaylistLoopDeactive), LOGLEVEL_NOTICE); - } - else - { - Log_Println((char *)FPSTR(modificatorPlaylistLoopActive), LOGLEVEL_NOTICE); - } - gPlayProperties.repeatPlaylist = !gPlayProperties.repeatPlaylist; - char rBuf[2]; - snprintf(rBuf, 2, "%u", AudioPlayer_GetRepeatMode()); -#ifdef MQTT_ENABLE - publishMqtt((char *)FPSTR(topicRepeatModeState), rBuf, false); -#endif - System_IndicateOk(); + + case CMD_VOLUMEUP: { + AudioPlayer_VolumeToQueueSender(AudioPlayer_GetCurrentVolume() + 1, true); + break; } - break; - } - case REPEAT_TRACK: - { // Introduces looping for track-mode - if (gPlayProperties.playMode == NO_PLAYLIST) - { - Log_Println((char *)FPSTR(modificatorNotallowedWhenIdle), LOGLEVEL_NOTICE); - System_IndicateError(); + case CMD_VOLUMEDOWN:{ + AudioPlayer_VolumeToQueueSender(AudioPlayer_GetCurrentVolume() - 1, true); + break; } - else - { - if (gPlayProperties.repeatCurrentTrack) - { - Log_Println((char *)FPSTR(modificatorTrackDeactive), LOGLEVEL_NOTICE); - } - else - { - Log_Println((char *)FPSTR(modificatorTrackActive), LOGLEVEL_NOTICE); - } - gPlayProperties.repeatCurrentTrack = !gPlayProperties.repeatCurrentTrack; - char rBuf[2]; - snprintf(rBuf, 2, "%u", AudioPlayer_GetRepeatMode()); -#ifdef MQTT_ENABLE - publishMqtt((char *)FPSTR(topicRepeatModeState), rBuf, false); -#endif - System_IndicateOk(); + + case CMD_MEASUREBATTERY: { + #ifdef MEASURE_BATTERY_VOLTAGE + float voltage = Battery_GetVoltage(); + snprintf(Log_Buffer, Log_BufferLength, "%s: %.2f V", (char *) FPSTR(currentVoltageMsg), voltage); + Log_Println(Log_Buffer, LOGLEVEL_INFO); + Led_Indicate(LedIndicatorType::Voltage); + #ifdef MQTT_ENABLE + char vstr[6]; + snprintf(vstr, 6, "%.2f", voltage); + publishMqtt((char *) FPSTR(topicBatteryVoltage), vstr, false); + #endif + #endif + break; } - break; - } - case DIMM_LEDS_NIGHTMODE: - { -#ifdef MQTT_ENABLE - publishMqtt((char *)FPSTR(topicLedBrightnessState), Led_GetBrightness(), false); -#endif - Log_Println((char *)FPSTR(ledsDimmedToNightmode), LOGLEVEL_INFO); -#ifdef NEOPIXEL_ENABLE - Led_ResetToNightBrightness(); -#endif - System_IndicateOk(); - break; - } + case CMD_SLEEPMODE: { + System_RequestSleep(); + break; + } - case TOGGLE_WIFI_STATUS: - { - Wlan_ToggleEnable(); - System_IndicateOk(); - break; - } -#ifdef BLUETOOTH_ENABLE - case TOGGLE_BLUETOOTH_MODE: - { - if (System_GetOperationModeFromNvs() == OPMODE_NORMAL) - { - System_IndicateOk(); - System_SetOperationMode(OPMODE_BLUETOOTH); + case CMD_SEEK_FORWARDS: { + gPlayProperties.seekmode = SEEK_FORWARDS; + break; } - else if (System_GetOperationModeFromNvs() == OPMODE_BLUETOOTH) - { - System_IndicateOk(); - System_SetOperationMode(OPMODE_NORMAL); + + case CMD_SEEK_BACKWARDS: { + gPlayProperties.seekmode = SEEK_BACKWARDS; + break; } - else - { + + default: { + snprintf(Log_Buffer, Log_BufferLength, "%s %d !", (char *) FPSTR(modificatorDoesNotExist), mod); + Log_Println(Log_Buffer, LOGLEVEL_ERROR); System_IndicateError(); } - break; - } -#endif -#ifdef FTP_ENABLE - case ENABLE_FTP_SERVER: - { - Ftp_EnableServer(); - break; - } -#endif - case CMD_PLAYPAUSE: - { - AudioPlayer_TrackControlToQueueSender(PAUSEPLAY); - break; - } - case CMD_PREVTRACK: - { - AudioPlayer_TrackControlToQueueSender(PREVIOUSTRACK); - break; - } - case CMD_NEXTTRACK: - { - AudioPlayer_TrackControlToQueueSender(NEXTTRACK); - break; - } - case CMD_FIRSTTRACK: - { - AudioPlayer_TrackControlToQueueSender(FIRSTTRACK); - break; - } - case CMD_LASTTRACK: - { - AudioPlayer_TrackControlToQueueSender(LASTTRACK); - break; - } - case CMD_VOLUMEINIT: - { - AudioPlayer_VolumeToQueueSender(AudioPlayer_GetInitVolume(), true); - break; - } - case CMD_VOLUMEUP: - { - AudioPlayer_VolumeToQueueSender(AudioPlayer_GetCurrentVolume() + 1, true); - break; - } - case CMD_VOLUMEDOWN: - { - AudioPlayer_VolumeToQueueSender(AudioPlayer_GetCurrentVolume() - 1, true); - break; - } - case CMD_MEASUREBATTERY: - { -#ifdef MEASURE_BATTERY_VOLTAGE - float voltage = Battery_GetVoltage(); - snprintf(Log_Buffer, Log_BufferLength, "%s: %.2f V", (char *)FPSTR(currentVoltageMsg), voltage); - Log_Println(Log_Buffer, LOGLEVEL_INFO); - Led_Indicate(LedIndicatorType::Voltage); -#ifdef MQTT_ENABLE - char vstr[6]; - snprintf(vstr, 6, "%.2f", voltage); - publishMqtt((char *)FPSTR(topicBatteryVoltage), vstr, false); -#endif -#endif - break; - } - case CMD_SLEEPMODE: - { - System_RequestSleep(); - break; - } - case CMD_SEEK_FORWARDS: - { - gPlayProperties.seekmode = SEEK_FORWARDS; - break; - } - case CMD_SEEK_BACKWARDS: - { - gPlayProperties.seekmode = SEEK_BACKWARDS; - break; - } - default: - { - snprintf(Log_Buffer, Log_BufferLength, "%s %d !", (char *)FPSTR(modificatorDoesNotExist), mod); - Log_Println(Log_Buffer, LOGLEVEL_ERROR); - System_IndicateError(); - } } } diff --git a/src/Common.h b/src/Common.h index 76f7d3e..8091221 100644 --- a/src/Common.h +++ b/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,68 +35,58 @@ 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]) - { - case 0x84: - asciiString[k++] = 0x8e; - break; // Ä - case 0xa4: - asciiString[k++] = 0x84; - break; // ä - case 0x9c: - asciiString[k++] = 0x9a; - break; // Ü - case 0xbc: - asciiString[k++] = 0x81; - break; // ü - case 0x96: - asciiString[k++] = 0x99; - break; // Ö - case 0xb6: - asciiString[k++] = 0x94; - break; // ö - case 0x9f: - asciiString[k++] = 0xe1; - break; // ß - default: - asciiString[k++] = 0xdb; // Unknow... + switch (utf8String[i]) { + case 0x84: + asciiString[k++] = 0x8e; + break; // Ä + case 0xa4: + asciiString[k++] = 0x84; + break; // ä + case 0x9c: + asciiString[k++] = 0x9a; + break; // Ü + case 0xbc: + asciiString[k++] = 0x81; + break; // ü + case 0x96: + asciiString[k++] = 0x99; + break; // Ö + case 0xb6: + asciiString[k++] = 0x94; + break; // ö + case 0x9f: + asciiString[k++] = 0xe1; + break; // ß + default: + asciiString[k++] = 0xdb; // Unknown... } - } - else - { + } else { asciiString[k++] = utf8String[i]; } } @@ -112,46 +95,43 @@ 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++) - { - - switch (asciiString[i]) - { - case 0x8e: - utf8String[k++] = 0xc3; - utf8String[k++] = 0x84; - break; // Ä - case 0x84: - utf8String[k++] = 0xc3; - utf8String[k++] = 0xa4; - break; // ä - case 0x9a: - utf8String[k++] = 0xc3; - utf8String[k++] = 0x9c; - break; // Ü - case 0x81: - utf8String[k++] = 0xc3; - utf8String[k++] = 0xbc; - break; // ü - case 0x99: - utf8String[k++] = 0xc3; - utf8String[k++] = 0x96; - break; // Ö - case 0x94: - utf8String[k++] = 0xc3; - utf8String[k++] = 0xb6; - break; // ö - case 0xe1: - utf8String[k++] = 0xc3; - utf8String[k++] = 0x9f; - break; // ß - default: - utf8String[k++] = asciiString[i]; + for (int i = 0; i < asciiString.length() && k < MAX_FILEPATH_LENTGH - 2; i++) { + + switch (asciiString[i]) { + case 0x8e: + utf8String[k++] = 0xc3; + utf8String[k++] = 0x84; + break; // Ä + case 0x84: + utf8String[k++] = 0xc3; + utf8String[k++] = 0xa4; + break; // ä + case 0x9a: + utf8String[k++] = 0xc3; + utf8String[k++] = 0x9c; + break; // Ü + case 0x81: + utf8String[k++] = 0xc3; + utf8String[k++] = 0xbc; + break; // ü + case 0x99: + utf8String[k++] = 0xc3; + utf8String[k++] = 0x96; + break; // Ö + case 0x94: + utf8String[k++] = 0xc3; + utf8String[k++] = 0xb6; + break; // ö + case 0xe1: + utf8String[k++] = 0xc3; + utf8String[k++] = 0x9f; + break; // ß + default: + utf8String[k++] = asciiString[i]; } } @@ -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)); diff --git a/src/Ftp.cpp b/src/Ftp.cpp index a95e48e..8d2f5d9 100644 --- a/src/Ftp.cpp +++ b/src/Ftp.cpp @@ -9,12 +9,12 @@ #include "Wlan.h" #ifdef FTP_ENABLE -#include "ESP32FtpServer.h" + #include "ESP32FtpServer.h" #endif // FTP -char *Ftp_User = x_strndup((char *)"esp32", ftpUserLength); // FTP-user (default; can be changed later via GUI) -char *Ftp_Password = x_strndup((char *)"esp32", ftpPasswordLength); // FTP-password (default; can be changed later via GUI) +char *Ftp_User = x_strndup((char *) "esp32", ftpUserLength); // FTP-user (default; can be changed later via GUI) +char *Ftp_Password = x_strndup((char *) "esp32", ftpPasswordLength); // FTP-password (default; can be changed later via GUI) // FTP #ifdef FTP_ENABLE @@ -25,92 +25,74 @@ 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 - { + Log_Println((char *) FPSTR(wroteFtpUserToNvs), LOGLEVEL_ERROR); + } else { strncpy(Ftp_User, nvsFtpUser.c_str(), ftpUserLength); - snprintf(Log_Buffer, Log_BufferLength, "%s: %s", (char *)FPSTR(restoredFtpUserFromNvs), nvsFtpUser.c_str()); + snprintf(Log_Buffer, Log_BufferLength, "%s: %s", (char *) FPSTR(restoredFtpUserFromNvs), nvsFtpUser.c_str()); Log_Println(Log_Buffer, LOGLEVEL_INFO); } // 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 - { + Log_Println((char *) FPSTR(wroteFtpPwdToNvs), LOGLEVEL_ERROR); + } else { strncpy(Ftp_Password, nvsFtpPassword.c_str(), ftpPasswordLength); - snprintf(Log_Buffer, Log_BufferLength, "%s: %s", (char *)FPSTR(restoredFtpPwdFromNvs), nvsFtpPassword.c_str()); + snprintf(Log_Buffer, Log_BufferLength, "%s: %s", (char *) FPSTR(restoredFtpPwdFromNvs), nvsFtpPassword.c_str()); Log_Println(Log_Buffer, LOGLEVEL_INFO); } } -void Ftp_Cyclic(void) -{ -#ifdef FTP_ENABLE - ftpManager(); +void Ftp_Cyclic(void) { + #ifdef FTP_ENABLE + ftpManager(); - if (WL_CONNECTED == WiFi.status()) - { - if (ftpEnableLastStatus && ftpEnableCurrentStatus) - { - ftpSrv->handleFTP(); + if (WL_CONNECTED == WiFi.status()) { + if (ftpEnableLastStatus && ftpEnableCurrentStatus) { + ftpSrv->handleFTP(); + } } - } - if (ftpEnableLastStatus && ftpEnableCurrentStatus) - { - if (ftpSrv->isConnected()) - { - System_UpdateActivityTimer(); // Re-adjust timer while client is connected to avoid ESP falling asleep + if (ftpEnableLastStatus && ftpEnableCurrentStatus) { + if (ftpSrv->isConnected()) { + System_UpdateActivityTimer(); // Re-adjust timer while client is connected to avoid ESP falling asleep + } } - } -#endif + #endif } -void Ftp_EnableServer(void) -{ - if (Wlan_IsConnected() && !ftpEnableLastStatus && !ftpEnableCurrentStatus) - { +void Ftp_EnableServer(void) { + if (Wlan_IsConnected() && !ftpEnableLastStatus && !ftpEnableCurrentStatus) { ftpEnableLastStatus = true; System_IndicateOk(); - } - else - { - Log_Println((char *)FPSTR(unableToStartFtpServer), LOGLEVEL_ERROR); + } else { + Log_Println((char *) FPSTR(unableToStartFtpServer), LOGLEVEL_ERROR); System_IndicateError(); } } // Creates FTP-instance only when requested -void ftpManager(void) -{ -#ifdef FTP_ENABLE - if (ftpEnableLastStatus && !ftpEnableCurrentStatus) - { - snprintf(Log_Buffer, Log_BufferLength, "%s: %u", (char *)FPSTR(freeHeapWithoutFtp), ESP.getFreeHeap()); - Log_Println(Log_Buffer, LOGLEVEL_DEBUG); - ftpEnableCurrentStatus = true; - ftpSrv = new FtpServer(); - ftpSrv->begin(gFSystem, Ftp_User, Ftp_Password); - snprintf(Log_Buffer, Log_BufferLength, "%s: %u", (char *)FPSTR(freeHeapWithFtp), ESP.getFreeHeap()); - Log_Println(Log_Buffer, LOGLEVEL_DEBUG); -#if (LANGUAGE == 1) - Serial.println(F("FTP-Server gestartet")); -#else - Serial.println(F("FTP-server started")); -#endif - } -#endif +void ftpManager(void) { + #ifdef FTP_ENABLE + if (ftpEnableLastStatus && !ftpEnableCurrentStatus) { + snprintf(Log_Buffer, Log_BufferLength, "%s: %u", (char *) FPSTR(freeHeapWithoutFtp), ESP.getFreeHeap()); + Log_Println(Log_Buffer, LOGLEVEL_DEBUG); + ftpEnableCurrentStatus = true; + ftpSrv = new FtpServer(); + ftpSrv->begin(gFSystem, Ftp_User, Ftp_Password); + snprintf(Log_Buffer, Log_BufferLength, "%s: %u", (char *) FPSTR(freeHeapWithFtp), ESP.getFreeHeap()); + Log_Println(Log_Buffer, LOGLEVEL_DEBUG); + #if (LANGUAGE == 1) + Serial.println(F("FTP-Server gestartet")); + #else + Serial.println(F("FTP-server started")); + #endif + } + #endif } diff --git a/src/HTMLaccesspoint.h b/src/HTMLaccesspoint.h new file mode 100644 index 0000000..4405e10 --- /dev/null +++ b/src/HTMLaccesspoint.h @@ -0,0 +1,64 @@ +static const char accesspoint_HTML[] PROGMEM = "\ +\ + \ + WLAN-Einrichtung\ + \ + \ + \ +
\ +

WLAN-Einrichtung

\ +
\ +
\ +
\ +
\ +
\ +

\ + \ +
\ +
\ +

Fertig?

\ + \ +
\ + \ +"; \ No newline at end of file diff --git a/src/HTMLaccesspoint_DE.h b/src/HTMLaccesspoint_DE.h index ae64193..fc8acb9 100644 --- a/src/HTMLaccesspoint_DE.h +++ b/src/HTMLaccesspoint_DE.h @@ -1,68 +1,64 @@ -#if (LANGUAGE == 1) - static const char accesspoint_HTML[] PROGMEM = "\ -\ - \ - WLAN-Einrichtung\ - \ - \ - \ -
\ -

WLAN-Einrichtung

\ -
\ -
\ -
\ -
\ -
\ -

\ - \ -
\ -
\ -

Fertig?

\ - \ -
\ - \ -"; - -#endif + \ + \ + WLAN-Einrichtung\ + \ + \ + \ +
\ +

WLAN-Einrichtung

\ +
\ +
\ +
\ +
\ +
\ +

\ + \ +
\ +
\ +

Fertig?

\ + \ +
\ + \ + "; diff --git a/src/HTMLaccesspoint_EN.h b/src/HTMLaccesspoint_EN.h index a5187eb..3b7ceba 100644 --- a/src/HTMLaccesspoint_EN.h +++ b/src/HTMLaccesspoint_EN.h @@ -1,5 +1,3 @@ -#if (LANGUAGE == 2) - static const char accesspoint_HTML[] PROGMEM = "\ \ \ @@ -63,6 +61,4 @@ static const char accesspoint_HTML[] PROGMEM = "\ \ \ \ -"; - -#endif +"; \ No newline at end of file diff --git a/src/HTMLmanagement.h b/src/HTMLmanagement.h new file mode 100644 index 0000000..2322da5 --- /dev/null +++ b/src/HTMLmanagement.h @@ -0,0 +1,1111 @@ +static const char management_HTML[] PROGMEM = "\ +\ +\ + ESPuino-Konfiguration\ + \ + \ + \ + \ + \ + \ + \ + \ + \ + \ + \ + \ + \ + \ + \ + \ +\ +\ +\ +
\ + \ +
\ +
\ +
\ +
\ +
\ +
\ + WLAN-Einstellungen\ + \ + \ +
\ + Bitte SSID des WLANs eintragen.\ +
\ + \ + \ + \ + \ +
\ +
\ +
\ + \ + \ +
\ +
\ +
\ +
\ +
\ +
\ +
\ + Steuerung\ +
\ + \ + \ + \ + \ + \ +
\ +
\ +
\ +
\ + Lautstärke\ + \ +
\ +
\ +
\ +
\ +
\ +
\ +
\ + Dateien\ +
\ +
\ +
\ +
\ +
\ +
\ +
\ + \ + \ + Browse\ + Upload\ + \ + \ +
\ +
\ +
\ +
\ +
\ +
\ +
\ +
\ +
\ +
\ +
\ +
\ +
\ + RFID-Zuweisungen\ +
\ +
\ + \ + \ +
\ + \ +
\ +
\ +
\ + \ + \ + \ + \ +
\ +
\ + \ + \ +
\ +
\ +
\ +
\ +
\ + \ + \ +
\ +
\ +
\ +
\ +
\ +
\ +
\ +
\ +\ +
\ +
\ + MQTT-Einstellungen\ + \ + \ +
\ +
\ + \ + \ + \ + \ + \ + \ + \ + \ +
\ +
\ +
\ + \ + \ +
\ +
\ +
\ +
\ +
\ +
\ +\ +
\ +
\ + FTP-Einstellungen\ + \ + \ + \ + \ +
\ +
\ +
\ + \ + \ +
\ +
\ +
\ +
\ +\ +
\ +
\ +\ +
\ +
\ +
\ + Lautstärke\ + \ +
\ +
\ +
\ + \ +
\ + \ +
\ +
\ + \ +
\ + \ +
\ +
\ +
\ +
\ +
\ +
\ + Neopixel (Helligkeit)\ + \ +
\ + \ + \ +
\ +\ + \ +
\ + \ +
\ +
\ +
\ +
\ +
\ +
\ + Deep Sleep\ +\ + \ +
\ +
\ +
\ +
\ +\ +
\ +
\ + Batterie\ +
Status über Neopixel anzeigen
\ +
\ + \ +
\ + \ +
\ +
\ + \ +
\ + \ +
\ +
\ + \ +\ +
\ + \ +
\ +\ +
\ + \ +
\ + \ +
\ +\ +
\ +
\ +
\ +
\ + \ + \ +
\ +
\ +
\ +
\ +
\ +
\ +
\ + NVS-Importer\ +
\ +
\ + \ + \ +
\ + \ +
\ +
\ +
\ +
\ +
\ + Forum\ +

Du hast Probleme mit ESPuino oder bist an einem Erfahrungsaustausch interessiert?
\ + Dann schaue doch mal im ESPuino-Forum vorbei! Insbesondere gibt es dort auch einen
\ + Bereich, in dem reichlich Dokumentation hinterlegt ist. Wir freuen uns auf deinen Besuch!\ +

\ +
\ +
\ +
\ +\ +\ +"; \ No newline at end of file diff --git a/src/HTMLmanagement_DE.h b/src/HTMLmanagement_DE.h index ac4b7f4..f151edb 100644 --- a/src/HTMLmanagement_DE.h +++ b/src/HTMLmanagement_DE.h @@ -1,5 +1,3 @@ -#if (LANGUAGE == 1) - static const char management_HTML[] PROGMEM = "\ \ \ @@ -47,7 +45,7 @@ static const char management_HTML[] PROGMEM = "\ .icon-pos{\ top: 0.3em;\ position: relative;\ - }\ + }\ .reboot{\ color:white;\ }\ @@ -133,7 +131,7 @@ static const char management_HTML[] PROGMEM = "\
\ \ \"\"/\ + width=\"35\" height=\"35\" class=\"d-inline-block align-top\" alt=\"\"/>\ ESPuino\ \ Neustart\ @@ -169,7 +167,7 @@ static const char management_HTML[] PROGMEM = "\ \ \ \ + value=\"%HOSTNAME%\" pattern=\"^[^-\\.]{2,32}\" required>\
\
\
\ @@ -214,12 +212,12 @@ static const char management_HTML[] PROGMEM = "\
\
\ Dateien\ -
\ -
\ -
\ -
\ -
\ -
\ +
\ +
\ +
\ +
\ +
\ + \
\ \ \ @@ -235,7 +233,7 @@ static const char management_HTML[] PROGMEM = "\
\
\
\ -
\ +
\
\
\
\ @@ -245,7 +243,7 @@ static const char management_HTML[] PROGMEM = "\
\ \ \ + placeholder=\"%RFID_TAG_ID%\" name=\"rfidIdMusic\" required>\
\
    \
  • \ @@ -311,7 +309,7 @@ static const char management_HTML[] PROGMEM = "\
    \ \ \ + onsubmit=\"mqttSettings('mqttConfig'); return false\">\
    \ MQTT-Einstellungen\ \ @@ -322,13 +320,13 @@ static const char management_HTML[] PROGMEM = "\
    \ \ \ + placeholder=\"z.B. 192.168.2.89\" name=\"mqttServer\" value=\"%MQTT_SERVER%\">\ \ \ + placeholder=\"Benutzername\" name=\"mqttUser\" value=\"%MQTT_USER%\">\ \ \ + placeholder=\"Passwort\" name=\"mqttPwd\" value=\"%MQTT_PWD%\">\ \ \ @@ -349,10 +347,10 @@ static const char management_HTML[] PROGMEM = "\ FTP-Einstellungen\ \ \ + placeholder=\"Benutzername\" name=\"ftpUser\" value=\"%FTP_USER%\" required>\ \ \ + name=\"ftpPwd\" value=\"%FTP_PWD%\" required>\
    \
    \
    \ @@ -377,14 +375,14 @@ static const char management_HTML[] PROGMEM = "\
    \ \
    \ - \
    \
    \ \
    \ \ + data-slider-value=\"%MAX_VOLUME_HEADPHONE%\" value=\"%MAX_VOLUME_HEADPHONE%\" required> \
    \ \
    \ @@ -396,7 +394,7 @@ static const char management_HTML[] PROGMEM = "\
    \ \ \ + data-slider-value=\"%INIT_LED_BRIGHTNESS%\" value=\"%INIT_LED_BRIGHTNESS%\" required>\
    \ \ \ @@ -412,7 +410,7 @@ static const char management_HTML[] PROGMEM = "\ \ \
    \ + data-slider-value=\"%MAX_INACTIVITY%\" value=\"%MAX_INACTIVITY%\" required>
    \ \
    \
    \ @@ -433,21 +431,21 @@ static const char management_HTML[] PROGMEM = "\ \
    \ \ + data-slider-value=\"%VOLTAGE_INDICATOR_LOW%\" value=\"%VOLTAGE_INDICATOR_LOW%\" pattern=\"^\\d{1,2}(\\.\\d{1,3})?\" required> \
    \
    \ \ \
    \ \ + data-slider-value=\"%VOLTAGE_INDICATOR_HIGH%\" value=\"%VOLTAGE_INDICATOR_HIGH%\" pattern=\"^\\d{1,2}(\\.\\d{1,3})?\" required> \
    \ \
    \ \
    \ \ + data-slider-value=\"%VOLTAGE_CHECK_INTERVAL%\" name=\"voltageCheckInterval\" value=\"%VOLTAGE_CHECK_INTERVAL%\" required>\
    \ \ \ @@ -577,353 +575,353 @@ static const char management_HTML[] PROGMEM = "\ }\ \ }\ - lastSelectedNodePath = data.node.data.path;\ + lastSelectedNodePath = data.node.data.path;\ }\ \ \ });\ \ - function doRest(path, callback, obj) {\ - obj.url = path;\ - obj.dataType = \"json\";\ - obj.contentType= \"application/json;charset=IBM437\",\ + function doRest(path, callback, obj) {\ + obj.url = path;\ + obj.dataType = \"json\";\ + obj.contentType= \"application/json;charset=IBM437\",\ obj.scriptCharset= \"IBM437\",\ obj.success = function(data, textStatus, jqXHR) {\ - if (callback) {\ - callback(data);\ - }\ - };\ - obj.error = function(jqXHR, textStatus, errorThrown) {\ - console.log(\"AJAX error\");\ - /*debugger; */\ - };\ - jQuery.ajax(obj);\ - } /* doRest */\ -\ - function getData(path, callback) {\ - doRest(path, callback, {\ - method : \"GET\"\ - });\ - } /* getData */\ -\ - function deleteData(path, callback, _data) {\ - doRest(path, callback, {\ - method : \"DELETE\",\ - data: _data\ - });\ - } /* deleteData */\ -\ - function patchData(path, callback, _data) {\ - doRest(path, callback, {\ - method : \"PATCH\",\ - data: _data\ - });\ - } /* patchData */\ -\ - function postData(path, callback, _data) {\ - doRest(path, callback, {\ - method : \"POST\",\ - data: _data\ - });\ - } /* postData */\ -\ -\ - function putData(path, callback, _data) {\ - doRest(path, callback, {\ - method : \"PUT\",\ - data: _data\ - });\ - } /* putData */\ -\ -\ - /* File Upload */\ - $('#explorerUploadForm').submit(function(e){\ - e.preventDefault();\ - console.log(\"Upload!\");\ - var data = new FormData(this);\ -\ - var ref = $('#explorerTree').jstree(true),\ - sel = ref.get_selected(),\ - path = \"/\";\ + if (callback) {\ + callback(data);\ + }\ + };\ + obj.error = function(jqXHR, textStatus, errorThrown) {\ + console.log(\"AJAX error\");\ + /*debugger; */\ + };\ + jQuery.ajax(obj);\ + } /* doRest */\ +\ + function getData(path, callback) {\ + doRest(path, callback, {\ + method : \"GET\"\ + });\ + } /* getData */\ +\ + function deleteData(path, callback, _data) {\ + doRest(path, callback, {\ + method : \"DELETE\",\ + data: _data\ + });\ + } /* deleteData */\ +\ + function patchData(path, callback, _data) {\ + doRest(path, callback, {\ + method : \"PATCH\",\ + data: _data\ + });\ + } /* patchData */\ +\ + function postData(path, callback, _data) {\ + doRest(path, callback, {\ + method : \"POST\",\ + data: _data\ + });\ + } /* postData */\ +\ +\ + function putData(path, callback, _data) {\ + doRest(path, callback, {\ + method : \"PUT\",\ + data: _data\ + });\ + } /* putData */\ +\ +\ + /* File Upload */\ + $('#explorerUploadForm').submit(function(e){\ + e.preventDefault();\ + console.log(\"Upload!\");\ + var data = new FormData(this);\ +\ + var ref = $('#explorerTree').jstree(true),\ + sel = ref.get_selected(),\ + path = \"/\";\ if(!sel.length) { alert(\"Please select the upload location!\");return false; }\ if(!document.getElementById('uploaded_file').files.length > 0) { alert(\"Please select files to upload!\");return false; }\ - sel = sel[0];\ - selectedNode = ref.get_node(sel);\ - if(selectedNode.data.directory){\ - path = selectedNode.data.path\ - } else {\ - /* remap sel to parent folder */\ - sel = ref.get_node(ref.get_parent(sel));\ - path = parentNode.data.path;\ - console.log(\"Parent path: \" + path);\ - }\ -\ - $.ajax({\ - url: '/explorer?path=' + path,\ + sel = sel[0];\ + selectedNode = ref.get_node(sel);\ + if(selectedNode.data.directory){\ + path = selectedNode.data.path\ + } else {\ + /* remap sel to parent folder */\ + sel = ref.get_node(ref.get_parent(sel));\ + path = parentNode.data.path;\ + console.log(\"Parent path: \" + path);\ + }\ +\ + $.ajax({\ + url: '/explorer?path=' + path,\ type: 'POST',\ data: data,\ contentType: false,\ processData:false,\ - xhr: function() {\ - var xhr = new window.XMLHttpRequest();\ + xhr: function() {\ + var xhr = new window.XMLHttpRequest();\ \ - xhr.upload.addEventListener(\"progress\", function(evt) {\ - if (evt.lengthComputable) {\ - var percentComplete = evt.loaded / evt.total;\ - percentComplete = parseInt(percentComplete * 100);\ + xhr.upload.addEventListener(\"progress\", function(evt) {\ + if (evt.lengthComputable) {\ + var percentComplete = evt.loaded / evt.total;\ + percentComplete = parseInt(percentComplete * 100);\ console.log(percentComplete);\ var percent = percentComplete + '%';\ $(\"#explorerUploadProgress\").css('width', percent).text(percent);\ - }\ - }, false);\ + }\ + }, false);\ \ - return xhr;\ - },\ - success: function(data, textStatus, jqXHR) {\ + return xhr;\ + },\ + success: function(data, textStatus, jqXHR) {\ console.log(\"Upload success!\");\ $(\"#explorerUploadProgress\").text(\"Upload success!\");\ document.getElementById('uploaded_file').value = '';\ document.getElementById('uploaded_file_text').innerHTML = '';\ \ - getData(\"/explorer?path=\" + path, function(data) {\ - /* We now have data! */\ - deleteChildrenNodes(sel);\ - addFileDirectory(sel, data);\ - ref.open_node(sel);\ + getData(\"/explorer?path=\" + path, function(data) {\ + /* We now have data! */\ + deleteChildrenNodes(sel);\ + addFileDirectory(sel, data);\ + ref.open_node(sel);\ +\ +\ + });\ +\ + }\ + });\ + });\ +\ + /* File Delete */\ + function handleDeleteData(nodeId) {\ + var ref = $('#explorerTree').jstree(true);\ + var node = ref.get_node(nodeId);\ + console.log(\"call delete request: \" + node.data.path);\ + deleteData(\"/explorer?path=\" + node.data.path);\ + }\ +\ + function fileNameSort( a, b ) {\ + if ( a.dir && !b.dir ) {\ + return -1\ + }\ + if ( !a.dir && b.dir ) {\ + return 1\ + }\ + if ( a.name < b.name ){\ + return -1;\ + }\ + if ( a.name > b.name ){\ + return 1;\ + }\ + return 0;\ + }\ +\ + function createChild(nodeId, data) {\ + var ref = $('#explorerTree').jstree(true);\ + var node = ref.get_node(nodeId);\ + var parentNodePath = node.data.path;\ + /* In case of root node remove leading '/' to avoid '//' */\ + if(parentNodePath == \"/\"){\ + parentNodePath = \"\";\ + }\ + var child = {\ + text: data.name,\ + type: getType(data),\ + data: {\ + path: parentNodePath + \"/\" + data.name,\ + directory: data.dir\ + }\ + };\ +\ + return child;\ +\ + }\ +\ + function deleteChildrenNodes(nodeId) {\ + var ref = $('#explorerTree').jstree(true);\ + var children = $(\"#explorerTree\").jstree(\"get_children_dom\",nodeId);\ + for(var i=0;i b.name ){\ - return 1;\ - }\ - return 0;\ - }\ -\ - function createChild(nodeId, data) {\ - var ref = $('#explorerTree').jstree(true);\ - var node = ref.get_node(nodeId);\ - var parentNodePath = node.data.path;\ - /* In case of root node remove leading '/' to avoid '//' */\ - if(parentNodePath == \"/\"){\ - parentNodePath = \"\";\ - }\ - var child = {\ - text: data.name,\ - type: getType(data),\ - data: {\ - path: parentNodePath + \"/\" + data.name,\ - directory: data.dir\ - }\ - };\ -\ - return child;\ -\ - }\ -\ - function deleteChildrenNodes(nodeId) {\ - var ref = $('#explorerTree').jstree(true);\ - var children = $(\"#explorerTree\").jstree(\"get_children_dom\",nodeId);\ - for(var i=0;i\ \ @@ -1110,6 +1108,4 @@ static const char management_HTML[] PROGMEM = "\ });\ \ \ -"; - -#endif +"; \ No newline at end of file diff --git a/src/IrReceiver.cpp b/src/IrReceiver.cpp index 6465496..039743a 100644 --- a/src/IrReceiver.cpp +++ b/src/IrReceiver.cpp @@ -7,163 +7,131 @@ #include "System.h" #ifdef IR_CONTROL_ENABLE -#include + #include #endif // HW-Timer #ifdef IR_CONTROL_ENABLE -uint32_t IrReceiver_LastRcCmdTimestamp = 0u; + uint32_t IrReceiver_LastRcCmdTimestamp = 0u; #endif -void IrReceiver_Init() -{ -#ifdef IR_CONTROL_ENABLE - IrReceiver.begin(IRLED_PIN); -#endif +void IrReceiver_Init() { + #ifdef IR_CONTROL_ENABLE + IrReceiver.begin(IRLED_PIN); + #endif } -void IrReceiver_Cyclic() -{ -#ifdef IR_CONTROL_ENABLE - static uint8_t lastVolume = 0; +void IrReceiver_Cyclic() { + #ifdef IR_CONTROL_ENABLE + static uint8_t lastVolume = 0; - 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) - { - rcActionOk = true; // not used for volume up/down - IrReceiver_LastRcCmdTimestamp = millis(); - } + if (IrReceiver.decode()){ - switch (IrReceiver.decodedIRData.command) - { - case RC_PLAY: - { - if (rcActionOk) - { - Cmd_Action(CMD_PLAYPAUSE); - Serial.println(F("RC: Play")); - } - break; - } - case RC_PAUSE: - { - if (rcActionOk) - { - Cmd_Action(CMD_PLAYPAUSE); - Serial.println(F("RC: Pause")); - } - break; - } - case RC_NEXT: - { - if (rcActionOk) - { - Cmd_Action(CMD_NEXTTRACK); - Serial.println(F("RC: Next")); - } - break; - } - case RC_PREVIOUS: - { - if (rcActionOk) - { - Cmd_Action(CMD_PREVTRACK); - Serial.println(F("RC: Previous")); - } - break; - } - case RC_FIRST: - { - if (rcActionOk) - { - Cmd_Action(CMD_FIRSTTRACK); - Serial.println(F("RC: First")); - } - break; - } - case RC_LAST: - { - if (rcActionOk) - { - Cmd_Action(CMD_LASTTRACK); - Serial.println(F("RC: Last")); + // 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) { + rcActionOk = true; // not used for volume up/down + IrReceiver_LastRcCmdTimestamp = millis(); } - break; - } - case RC_MUTE: - { - if (rcActionOk) - { - if (AudioPlayer_GetCurrentVolume() > 0) - { - lastVolume = AudioPlayer_GetCurrentVolume(); - AudioPlayer_SetCurrentVolume(0u); + + switch (IrReceiver.decodedIRData.command) { + case RC_PLAY: { + if (rcActionOk) { + Cmd_Action(CMD_PLAYPAUSE); + Serial.println(F("RC: Play")); + } + break; + } + case RC_PAUSE: { + if (rcActionOk) { + Cmd_Action(CMD_PLAYPAUSE); + Serial.println(F("RC: Pause")); + } + break; + } + case RC_NEXT: { + if (rcActionOk) { + Cmd_Action(CMD_NEXTTRACK); + Serial.println(F("RC: Next")); + } + break; + } + case RC_PREVIOUS: { + if (rcActionOk) { + Cmd_Action(CMD_PREVTRACK); + Serial.println(F("RC: Previous")); + } + break; } - else - { - AudioPlayer_SetCurrentVolume(lastVolume); // Remember last volume if mute is pressed again + case RC_FIRST: { + if (rcActionOk) { + Cmd_Action(CMD_FIRSTTRACK); + Serial.println(F("RC: First")); + } + break; } + case RC_LAST: { + if (rcActionOk) { + Cmd_Action(CMD_LASTTRACK); + Serial.println(F("RC: Last")); + } + break; + } + case RC_MUTE: { + if (rcActionOk) { + if (AudioPlayer_GetCurrentVolume() > 0) { + lastVolume = AudioPlayer_GetCurrentVolume(); + AudioPlayer_SetCurrentVolume(0u); + } else { + AudioPlayer_SetCurrentVolume(lastVolume); // Remember last volume if mute is pressed again + } - uint8_t currentVolume = AudioPlayer_GetCurrentVolume(); - xQueueSend(gVolumeQueue, ¤tVolume, 0); - Serial.println(F("RC: Mute")); - } - break; - } - case RC_BLUETOOTH: - { - if (rcActionOk) - { - Cmd_Action(TOGGLE_BLUETOOTH_MODE); - Serial.println(F("RC: Bluetooth")); - } - break; - } - case RC_FTP: - { - if (rcActionOk) - { - Cmd_Action(ENABLE_FTP_SERVER); - Serial.println(F("RC: FTP")); - } - break; - } - case RC_SHUTDOWN: - { - if (rcActionOk) - { - System_RequestSleep(); - Serial.println(F("RC: Shutdown")); - } - break; - } - case RC_VOL_DOWN: - { - Cmd_Action(CMD_VOLUMEDOWN); - Serial.println(F("RC: Volume down")); - break; - } - case RC_VOL_UP: - { - Cmd_Action(CMD_VOLUMEUP); - Serial.println(F("RC: Volume up")); - break; - } - default: - { - if (rcActionOk) - { - Serial.println(F("RC: unknown")); + uint8_t currentVolume = AudioPlayer_GetCurrentVolume(); + xQueueSend(gVolumeQueue, ¤tVolume, 0); + Serial.println(F("RC: Mute")); + } + break; + } + case RC_BLUETOOTH: { + if (rcActionOk) { + Cmd_Action(TOGGLE_BLUETOOTH_MODE); + Serial.println(F("RC: Bluetooth")); + } + break; + } + case RC_FTP: { + if (rcActionOk) { + Cmd_Action(ENABLE_FTP_SERVER); + Serial.println(F("RC: FTP")); + } + break; + } + case RC_SHUTDOWN: { + if (rcActionOk) { + System_RequestSleep(); + Serial.println(F("RC: Shutdown")); + } + break; + } + case RC_VOL_DOWN: { + Cmd_Action(CMD_VOLUMEDOWN); + Serial.println(F("RC: Volume down")); + break; + } + case RC_VOL_UP: { + Cmd_Action(CMD_VOLUMEUP); + Serial.println(F("RC: Volume up")); + break; + } + default: { + if (rcActionOk) { + Serial.println(F("RC: unknown")); + } + } } } - } - } -#endif + #endif } \ No newline at end of file diff --git a/src/Led.cpp b/src/Led.cpp index 2e3adc3..18da742 100644 --- a/src/Led.cpp +++ b/src/Led.cpp @@ -11,376 +11,309 @@ #include "Wlan.h" #ifdef NEOPIXEL_ENABLE -#include + #include -#define LED_INITIAL_BRIGHTNESS 16u -#define LED_INITIAL_NIGHT_BRIGHTNESS 2u + #define LED_INITIAL_BRIGHTNESS 16u + #define LED_INITIAL_NIGHT_BRIGHTNESS 2u -#define LED_INDICATOR_SET(indicator) ((Led_Indicators) |= (1u << ((uint8_t)indicator))) -#define LED_INDICATOR_IS_SET(indicator) (((Led_Indicators) & (1u << ((uint8_t)indicator))) > 0u) -#define LED_INDICATOR_CLEAR(indicator) ((Led_Indicators) &= ~(1u << ((uint8_t)indicator))) + #define LED_INDICATOR_SET(indicator) ((Led_Indicators) |= (1u << ((uint8_t)indicator))) + #define LED_INDICATOR_IS_SET(indicator) (((Led_Indicators) & (1u << ((uint8_t)indicator))) > 0u) + #define LED_INDICATOR_CLEAR(indicator) ((Led_Indicators) &= ~(1u << ((uint8_t)indicator))) -extern t_button gButtons[7]; // next + prev + pplay + rotEnc + button4 + button5 + dummy-button -extern uint8_t gShutdownButton; + extern t_button gButtons[7]; // next + prev + pplay + rotEnc + button4 + button5 + dummy-button + extern uint8_t gShutdownButton; -static uint32_t Led_Indicators = 0u; + static uint32_t Led_Indicators = 0u; -static bool Led_Pause = false; // Used to pause Neopixel-signalisation (while NVS-writes as this leads to exceptions; don't know why) + static bool Led_Pause = false; // Used to pause Neopixel-signalisation (while NVS-writes as this leads to exceptions; don't know why) -static uint8_t Led_InitialBrightness = LED_INITIAL_BRIGHTNESS; -static uint8_t Led_Brightness = LED_INITIAL_BRIGHTNESS; -static uint8_t Led_NightBrightness = LED_INITIAL_NIGHT_BRIGHTNESS; - -static void Led_Task(void *parameter); -static uint8_t Led_Address(uint8_t number); + static uint8_t Led_InitialBrightness = LED_INITIAL_BRIGHTNESS; + static uint8_t Led_Brightness = LED_INITIAL_BRIGHTNESS; + 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) -{ -#ifdef NEOPIXEL_ENABLE - // Get some stuff from NVS... - // Get initial LED-brightness from NVS - uint8_t nvsILedBrightness = gPrefsSettings.getUChar("iLedBrightness", 0); - 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 - { - 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) - { - Led_NightBrightness = nvsNLedBrightness; - snprintf(Log_Buffer, Log_BufferLength, "%s: %d", (char *)FPSTR(restoredInitialBrightnessForNmFromNvs), nvsNLedBrightness); - Log_Println(Log_Buffer, LOGLEVEL_INFO); - } - else - { - gPrefsSettings.putUChar("nLedBrightness", Led_NightBrightness); - Log_Println((char *)FPSTR(wroteNmBrightnessToNvs), LOGLEVEL_ERROR); - } - - xTaskCreatePinnedToCore( - Led_Task, /* Function to implement the task */ - "Led_Task", /* Name of the task */ - 2000, /* Stack size in words */ - NULL, /* Task input parameter */ - 1, /* Priority of the task */ - NULL, /* Task handle. */ - 0 /* Core where the task should run */ - ); -#endif +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) { + Led_InitialBrightness = nvsILedBrightness; + Led_Brightness = nvsILedBrightness; + snprintf(Log_Buffer, Log_BufferLength, "%s: %d", (char *) FPSTR(initialBrightnessfromNvs), nvsILedBrightness); + Log_Println(Log_Buffer, LOGLEVEL_INFO); + } 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) { + Led_NightBrightness = nvsNLedBrightness; + snprintf(Log_Buffer, Log_BufferLength, "%s: %d", (char *) FPSTR(restoredInitialBrightnessForNmFromNvs), nvsNLedBrightness); + Log_Println(Log_Buffer, LOGLEVEL_INFO); + } else { + gPrefsSettings.putUChar("nLedBrightness", Led_NightBrightness); + Log_Println((char *) FPSTR(wroteNmBrightnessToNvs), LOGLEVEL_ERROR); + } + + xTaskCreatePinnedToCore( + Led_Task, /* Function to implement the task */ + "Led_Task", /* Name of the task */ + 2000, /* Stack size in words */ + NULL, /* Task input parameter */ + 1, /* Priority of the task */ + NULL, /* Task handle. */ + 0 /* Core where the task should run */ + ); + #endif } -void Led_Exit(void) -{ -#ifdef NEOPIXEL_ENABLE - FastLED.clear(); - FastLED.show(); -#endif +void Led_Exit(void) { + #ifdef NEOPIXEL_ENABLE + FastLED.clear(); + FastLED.show(); + #endif } -void Led_Indicate(LedIndicatorType value) -{ -#ifdef NEOPIXEL_ENABLE - LED_INDICATOR_SET(value); -#endif +void Led_Indicate(LedIndicatorType value) { + #ifdef NEOPIXEL_ENABLE + LED_INDICATOR_SET(value); + #endif } -void Led_SetPause(boolean value) -{ -#ifdef NEOPIXEL_ENABLE - Led_Pause = value; -#endif +void Led_SetPause(boolean value) { + #ifdef NEOPIXEL_ENABLE + Led_Pause = value; + #endif } -void Led_ResetToInitialBrightness(void) -{ -#ifdef NEOPIXEL_ENABLE - Led_Brightness = Led_InitialBrightness; -#endif +void Led_ResetToInitialBrightness(void) { + #ifdef NEOPIXEL_ENABLE + Led_Brightness = Led_InitialBrightness; + #endif } -void Led_ResetToNightBrightness(void) -{ -#ifdef NEOPIXEL_ENABLE - Led_Brightness = Led_NightBrightness; - Log_Println((char *)FPSTR(ledsDimmedToNightmode), LOGLEVEL_INFO); -#endif +void Led_ResetToNightBrightness(void) { + #ifdef NEOPIXEL_ENABLE + Led_Brightness = Led_NightBrightness; + Log_Println((char *) FPSTR(ledsDimmedToNightmode), LOGLEVEL_INFO); + #endif } -uint8_t Led_GetBrightness(void) -{ -#ifdef NEOPIXEL_ENABLE - return Led_Brightness; -#else - return 0u; -#endif +uint8_t Led_GetBrightness(void) { + #ifdef NEOPIXEL_ENABLE + return Led_Brightness; + #else + return 0u; + #endif } -void Led_SetBrightness(uint8_t value) -{ -#ifdef NEOPIXEL_ENABLE - Led_Brightness = value; -#endif +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) -{ -#ifdef NEOPIXEL_REVERSE_ROTATION - return NUM_LEDS - 1 - number; -#else - return number; -#endif +uint8_t Led_Address(uint8_t number) { + #ifdef NEOPIXEL_REVERSE_ROTATION + return NUM_LEDS - 1 - number; + #else + return number; + #endif } -static void Led_Task(void *parameter) -{ -#ifdef NEOPIXEL_ENABLE - static uint8_t hlastVolume = AudioPlayer_GetCurrentVolume(); - static uint8_t lastPos = gPlayProperties.currentRelPos; - static bool lastPlayState = false; - static bool lastLockState = false; - static bool ledBusyShown = false; - static bool notificationShown = false; - static bool volumeChangeShown = false; - static bool showEvenError = false; - static bool turnedOffLeds = false; - static uint8_t ledPosWebstream = 0; - static uint8_t ledSwitchInterval = 5; // time in secs (webstream-only) - static uint8_t webstreamColor = 0; - static unsigned long lastSwitchTimestamp = 0; - static bool redrawProgress = false; - static uint8_t lastLedBrightness = Led_Brightness; - static CRGB::HTMLColorCode idleColor; - static CRGB leds[NUM_LEDS]; - FastLED.addLeds(leds, NUM_LEDS).setCorrection(TypicalSMD5050); - FastLED.setBrightness(Led_Brightness); - - 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) - { - FastLED.clear(true); - turnedOffLeds = true; +static void Led_Task(void *parameter) { + #ifdef NEOPIXEL_ENABLE + static uint8_t hlastVolume = AudioPlayer_GetCurrentVolume(); + static uint8_t lastPos = gPlayProperties.currentRelPos; + static bool lastPlayState = false; + static bool lastLockState = false; + static bool ledBusyShown = false; + static bool notificationShown = false; + static bool volumeChangeShown = false; + static bool showEvenError = false; + static bool turnedOffLeds = false; + static uint8_t ledPosWebstream = 0; + static uint8_t ledSwitchInterval = 5; // time in secs (webstream-only) + static uint8_t webstreamColor = 0; + static unsigned long lastSwitchTimestamp = 0; + static bool redrawProgress = false; + static uint8_t lastLedBrightness = Led_Brightness; + static CRGB::HTMLColorCode idleColor; + static CRGB leds[NUM_LEDS]; + FastLED.addLeds(leds, NUM_LEDS).setCorrection(TypicalSMD5050); + FastLED.setBrightness(Led_Brightness); + + 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) { + FastLED.clear(true); + turnedOffLeds = true; + } - vTaskDelay(portTICK_RATE_MS * 10); - continue; - } - 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) - { - leds[Led_Address(led)] = CRGB::Orange; + vTaskDelay(portTICK_RATE_MS * 10); + continue; + } + 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) { + leds[Led_Address(led)] = CRGB::Orange; + } else { + leds[Led_Address(led)] = CRGB::Red; + } } - else - { + } 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) { + leds[Led_Address(led)] = CRGB::Orange; + } } } } - 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) - { - leds[Led_Address(led)] = CRGB::Orange; - } - } - } + FastLED.show(); + showEvenError = !showEvenError; + vTaskDelay(portTICK_RATE_MS * 500); + esp_task_wdt_reset(); + continue; } - FastLED.show(); - showEvenError = !showEvenError; - vTaskDelay(portTICK_RATE_MS * 500); - esp_task_wdt_reset(); - continue; - } - if (lastLedBrightness != Led_Brightness) - { - FastLED.setBrightness(Led_Brightness); - 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) - { - FastLED.clear(); - for (uint8_t led = 0; led < NUM_LEDS; led++) - { - leds[Led_Address(led)] = CRGB::Red; - if (gButtons[gShutdownButton].currentState) - { + // 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) { + FastLED.clear(); + for (uint8_t led = 0; led < NUM_LEDS; led++) { + leds[Led_Address(led)] = CRGB::Red; + if (gButtons[gShutdownButton].currentState) { + FastLED.show(); + delay(5); + break; + } FastLED.show(); - delay(5); - break; + vTaskDelay(intervalToLongPress / NUM_LEDS * portTICK_RATE_MS); } - FastLED.show(); - vTaskDelay(intervalToLongPress / NUM_LEDS * portTICK_RATE_MS); + } + } 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) { + gButtons[gShutdownButton].currentState = true; } } - } - 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) - { - gButtons[gShutdownButton].currentState = true; - } - } - - 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++) - { - leds[Led_Address(led)] = CRGB::Red; - } - FastLED.show(); - vTaskDelay(portTICK_RATE_MS * 200); - } - 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++) - { - leds[Led_Address(led)] = CRGB::Green; - } - FastLED.show(); - vTaskDelay(portTICK_RATE_MS * 400); - } - -#ifdef MEASURE_BATTERY_VOLTAGE - 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++) - { + 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 + LED_INDICATOR_CLEAR(LedIndicatorType::Ok); + notificationShown = true; FastLED.clear(); - for (uint8_t led = 0; led < NUM_LEDS; led++) - { - leds[Led_Address(led)] = CRGB::Black; + for (uint8_t led = 0; led < NUM_LEDS; led++) { + leds[Led_Address(led)] = CRGB::Green; } FastLED.show(); - vTaskDelay(portTICK_RATE_MS * 200); + vTaskDelay(portTICK_RATE_MS * 400); } - } - if (LED_INDICATOR_IS_SET(LedIndicatorType::Voltage)) - { - LED_INDICATOR_CLEAR(LedIndicatorType::Voltage); - float currentVoltage = Battery_GetVoltage(); - float vDiffIndicatorRange = voltageIndicatorHigh - voltageIndicatorLow; - float vDiffCurrent = currentVoltage - voltageIndicatorLow; + #ifdef MEASURE_BATTERY_VOLTAGE + 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++) { + FastLED.clear(); - if (vDiffCurrent < 0) - { // If voltage is too low or no battery is connected - LED_INDICATOR_SET(LedIndicatorType::Error); - break; - } - 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) - { - leds[Led_Address(led)] = CRGB::Green; - } - else if (((float)numLedsToLight / NUM_LEDS) <= 0.6 && ((float)numLedsToLight / NUM_LEDS) >= 0.3) - { - leds[Led_Address(led)] = CRGB::Orange; - } - else - { + for (uint8_t led = 0; led < NUM_LEDS; led++) { leds[Led_Address(led)] = CRGB::Red; } FastLED.show(); - vTaskDelay(portTICK_RATE_MS * 20); + vTaskDelay(portTICK_RATE_MS * 200); + FastLED.clear(); + + for (uint8_t led = 0; led < NUM_LEDS; led++) { + leds[Led_Address(led)] = CRGB::Black; + } + FastLED.show(); + vTaskDelay(portTICK_RATE_MS * 200); } + } - 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; + 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 + LED_INDICATOR_SET(LedIndicatorType::Error); + break; + } 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) { + leds[Led_Address(led)] = CRGB::Green; + } else if (((float)numLedsToLight / NUM_LEDS) <= 0.6 && ((float)numLedsToLight / NUM_LEDS) >= 0.3) { + leds[Led_Address(led)] = CRGB::Orange; + } else { + leds[Led_Address(led)] = CRGB::Red; + } + FastLED.show(); + vTaskDelay(portTICK_RATE_MS * 20); } - 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()) { + break; + } + + vTaskDelay(portTICK_RATE_MS * 20); + } } } - } -#endif + #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,265 +323,202 @@ 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()) - { -#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()) - { -#endif + #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()) { + #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()) { + #endif break; - } - else - { + } else { vTaskDelay(portTICK_RATE_MS * 30); } } - 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()) - { -#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()) - { -#endif + 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()) { + #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()) { + #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()) - { -#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()) - { -#endif + #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()) { + #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()) { + #endif break; } - else - { + else { vTaskDelay(portTICK_RATE_MS * 30); } } } } - switch (gPlayProperties.playMode) - { - case NO_PLAYLIST: // If no playlist is active (idle) - if (System_GetOperationMode() == OPMODE_BLUETOOTH) - { - idleColor = CRGB::Blue; - } - else - { - if (Wlan_IsConnected()) - { - idleColor = CRGB::White; + switch (gPlayProperties.playMode) { + case NO_PLAYLIST: // If no playlist is active (idle) + if (System_GetOperationMode() == OPMODE_BLUETOOTH) { + idleColor = CRGB::Blue; + } else { + if (Wlan_IsConnected()) { + idleColor = CRGB::White; + } else { + idleColor = CRGB::Green; + } } - else - { - idleColor = CRGB::Green; + 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 + leds[0] = idleColor; + leds[NUM_LEDS / 4] = idleColor; + leds[NUM_LEDS / 2] = idleColor; + leds[NUM_LEDS / 4 * 3] = idleColor; + } 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++) { + #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()) { + #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()) { + #endif + break; + } else { + vTaskDelay(portTICK_RATE_MS * 10); + } + } + } } - } - if (hlastVolume == AudioPlayer_GetCurrentVolume() && lastLedBrightness == Led_Brightness) - { - for (uint8_t i = 0; i < NUM_LEDS; i++) - { + break; + + case BUSY: // If uC is busy (parsing SD-card) + ledBusyShown = true; + 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 - leds[0] = idleColor; - leds[NUM_LEDS / 4] = idleColor; - leds[NUM_LEDS / 2] = idleColor; - leds[NUM_LEDS / 4 * 3] = idleColor; - } - 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; + 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 { + 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(); - 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()) - { -#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()) - { -#endif - break; - } - else - { - vTaskDelay(portTICK_RATE_MS * 10); - } + if (gPlayProperties.playMode != BUSY) { + break; } + vTaskDelay(portTICK_RATE_MS * 50); } - } - break; + break; - case BUSY: // If uC is busy (parsing SD-card) - ledBusyShown = true; - for (uint8_t i = 0; i < NUM_LEDS; i++) - { - FastLED.clear(); - 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 - { - 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) - { - break; - } - vTaskDelay(portTICK_RATE_MS * 50); - } - break; - - default: // If playlist is active (doesn't matter which type) - 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()) - { -#else - 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) - { - ledBusyShown = false; - FastLED.clear(); - FastLED.show(); + default: // If playlist is active (doesn't matter which type) + 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()) { + #else + 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) { + ledBusyShown = false; + FastLED.clear(); + FastLED.show(); + } + redrawProgress = true; } - redrawProgress = true; - } - 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()) - { - leds[Led_Address(led)] = CRGB::Red; + 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()) { + leds[Led_Address(led)] = CRGB::Red; + } else if (!gPlayProperties.pausePlay) { // Hue-rainbow + leds[Led_Address(led)].setHue((uint8_t)(85 - ((double)95 / NUM_LEDS) * led)); + } } - else if (!gPlayProperties.pausePlay) - { // Hue-rainbow - leds[Led_Address(led)].setHue((uint8_t)(85 - ((double)95 / NUM_LEDS) * led)); + 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; + leds[(Led_Address(NUM_LEDS / 4 * 3)) % NUM_LEDS] = CRGB::Orange; + break; } } - 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; - leds[(Led_Address(NUM_LEDS / 4 * 3)) % NUM_LEDS] = CRGB::Orange; - break; - } } - } - 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) - { - ledPosWebstream++; - } - else - { - ledPosWebstream = 0; - } - if (System_AreControlsLocked()) - { - leds[Led_Address(ledPosWebstream)] = CRGB::Red; - leds[(Led_Address(ledPosWebstream) + NUM_LEDS / 2) % NUM_LEDS] = CRGB::Red; - } - 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) - { - leds[Led_Address(ledPosWebstream)] = CRGB::Orange; - leds[(Led_Address(ledPosWebstream) + NUM_LEDS / 2) % NUM_LEDS] = CRGB::Orange; + 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) { + ledPosWebstream++; + } else { + ledPosWebstream = 0; + } + if (System_AreControlsLocked()) { + leds[Led_Address(ledPosWebstream)] = CRGB::Red; + leds[(Led_Address(ledPosWebstream) + NUM_LEDS / 2) % NUM_LEDS] = CRGB::Red; + } 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) + { + leds[Led_Address(ledPosWebstream)] = CRGB::Orange; + leds[(Led_Address(ledPosWebstream) + NUM_LEDS / 2) % NUM_LEDS] = CRGB::Orange; + } } } + FastLED.show(); + vTaskDelay(portTICK_RATE_MS * 5); } - FastLED.show(); - vTaskDelay(portTICK_RATE_MS * 5); } + //vTaskDelay(portTICK_RATE_MS * 10); + esp_task_wdt_reset(); } - //vTaskDelay(portTICK_RATE_MS * 10); - esp_task_wdt_reset(); - } - vTaskDelete(NULL); -#endif + vTaskDelete(NULL); + #endif } diff --git a/src/Log.cpp b/src/Log.cpp index f7bed28..2b7ec83 100644 --- a/src/Log.cpp +++ b/src/Log.cpp @@ -6,14 +6,13 @@ // Serial-logging buffer uint8_t Log_BufferLength = 200; -char *Log_Buffer = (char *)calloc(Log_BufferLength, sizeof(char)); // Buffer for all log-messages +char *Log_Buffer = (char *) calloc(Log_BufferLength, sizeof(char)); // Buffer for all log-messages 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 + Log_Buffer = (char *) x_calloc(Log_BufferLength, sizeof(char)); // Buffer for all log-messages } /* Wrapper-function for serial-logging (with newline) @@ -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(); } \ No newline at end of file diff --git a/src/LogMessages_DE.cpp b/src/LogMessages_DE.cpp index fa01162..80cf732 100644 --- a/src/LogMessages_DE.cpp +++ b/src/LogMessages_DE.cpp @@ -2,188 +2,188 @@ #include "settings.h" #if (LANGUAGE == 1) -#include "Log.h" + #include "Log.h" -const char stillOnlineMqtt[] PROGMEM = "MQTT: Bin noch online."; -const char tryConnectMqttS[] PROGMEM = "Versuche Verbindung zu MQTT-Broker aufzubauen"; -const char mqttOk[] PROGMEM = "MQTT-Session aufgebaut."; -const char sleepTimerEOP[] PROGMEM = "Sleep-Timer: Nach dem letzten Track der Playlist."; -const char sleepTimerEOT[] PROGMEM = "Sleep-Timer: Nach dem Ende des laufenden Tracks."; -const char sleepTimerStop[] PROGMEM = "Sleep-Timer wurde deaktiviert."; -const char sleepTimerEO5[] PROGMEM = "Sleep Timer: Nach Ende des Titels oder, wenn früher, Ende der Playlist"; -const char sleepTimerAlreadyStopped[] PROGMEM = "Sleep-Timer ist bereits deaktiviert."; -const char sleepTimerSetTo[] PROGMEM = "Sleep-Timer gesetzt auf"; -const char allowButtons[] PROGMEM = "Alle Tasten werden freigegeben."; -const char lockButtons[] PROGMEM = "Alle Tasten werden gesperrt."; -const char noPlaylistNotAllowedMqtt[] PROGMEM = "Playmode kann nicht auf 'Keine Playlist' gesetzt werden via MQTT."; -const char playmodeChangedMQtt[] PROGMEM = "Playmode per MQTT angepasst."; -const char noPlaymodeChangeIfIdle[] PROGMEM = "Playmode kann nicht verändert werden, wenn keine Playlist aktiv ist."; -const char noValidTopic[] PROGMEM = "Kein gültiges Topic"; -const char freePtr[] PROGMEM = "Ptr-Freigabe"; -const char freeMemory[] PROGMEM = "Freier Speicher"; -const char writeEntryToNvs[] PROGMEM = "Schreibe Eintrag in NVS"; -const char freeMemoryAfterFree[] PROGMEM = "Freier Speicher nach Aufräumen"; -const char releaseMemoryOfOldPlaylist[] PROGMEM = "Gebe Speicher der alten Playlist frei."; -const char dirOrFileDoesNotExist[] PROGMEM = "Datei oder Verzeichnis existiert nicht "; -const char unableToAllocateMemForPlaylist[] PROGMEM = "Speicher für Playlist konnte nicht allokiert werden!"; -const char unableToAllocateMem[] PROGMEM = "Speicher konnte nicht allokiert werden!"; -const char fileModeDetected[] PROGMEM = "Dateimodus erkannt."; -const char nameOfFileFound[] PROGMEM = "Gefundenes File"; -const char reallocCalled[] PROGMEM = "Speicher reallokiert."; -const char unableToAllocateMemForLinearPlaylist[] PROGMEM = "Speicher für lineare Playlist konnte nicht allokiert werden!"; -const char numberOfValidFiles[] PROGMEM = "Anzahl gültiger Files"; -const char newLoudnessReceivedQueue[] PROGMEM = "Neue Lautstärke empfangen via Queue"; -const char newCntrlReceivedQueue[] PROGMEM = "Kontroll-Kommando empfangen via Queue"; -const char newPlaylistReceived[] PROGMEM = "Neue Playlist empfangen"; -const char repeatTrackDueToPlaymode[] PROGMEM = "Wiederhole Titel aufgrund von Playmode."; -const char repeatPlaylistDueToPlaymode[] PROGMEM = "Wiederhole Playlist aufgrund von Playmode."; -const char cmndStop[] PROGMEM = "Kommando: Stop"; -const char cmndPause[] PROGMEM = "Kommando: Pause"; -const char cmndNextTrack[] PROGMEM = "Kommando: Nächster Titel"; -const char cmndPrevTrack[] PROGMEM = "Kommando: Vorheriger Titel"; -const char cmndFirstTrack[] PROGMEM = "Kommando: Erster Titel von Playlist"; -const char cmndLastTrack[] PROGMEM = "Kommando: Letzter Titel von Playlist"; -const char cmndDoesNotExist[] PROGMEM = "Dieses Kommando existiert nicht."; -const char lastTrackAlreadyActive[] PROGMEM = "Es wird bereits der letzte Track gespielt."; -const char firstTrackAlreadyActive[] PROGMEM = "Es wird bereits der erste Track gespielt."; -const char trackStartAudiobook[] PROGMEM = "Titel wird im Hörspielmodus von vorne gespielt."; -const char trackStart[] PROGMEM = "Titel wird von vorne gespielt."; -const char trackChangeWebstream[] PROGMEM = "Im Webradio-Modus kann nicht an den Anfang gesprungen werden."; -const char endOfPlaylistReached[] PROGMEM = "Ende der Playlist erreicht."; -const char trackStartatPos[] PROGMEM = "Titel wird abgespielt ab Position"; -const char rfidScannerReady[] PROGMEM = "RFID-Tags koennen jetzt gescannt werden..."; -const char rfidTagDetected[] PROGMEM = "RFID-Karte erkannt: "; -const char rfid15693TagDetected[] PROGMEM = "RFID-Karte (ISO-15693) erkannt: "; -const char rfidTagReceived[] PROGMEM = "RFID-Karte empfangen"; -const char rfidTagUnknownInNvs[] PROGMEM = "RFID-Karte ist im NVS nicht hinterlegt."; -const char goToSleepDueToIdle[] PROGMEM = "Gehe in Deep Sleep wegen Inaktivität..."; -const char goToSleepDueToTimer[] PROGMEM = "Gehe in Deep Sleep wegen Sleep Timer..."; -const char goToSleepNow[] PROGMEM = "Gehe jetzt in Deep Sleep!"; -const char maxLoudnessReached[] PROGMEM = "Maximale Lautstärke bereits erreicht!"; -const char minLoudnessReached[] PROGMEM = "Minimale Lautstärke bereits erreicht!"; -const char errorOccured[] PROGMEM = "Fehler aufgetreten!"; -const char noMp3FilesInDir[] PROGMEM = "Verzeichnis beinhaltet keine mp3-Files."; -const char modeSingleTrack[] PROGMEM = "Modus: Einzelner Track"; -const char modeSingleTrackLoop[] PROGMEM = "Modus: Einzelner Track in Endlosschleife"; -const char modeSingleAudiobook[] PROGMEM = "Modus: Hoerspiel"; -const char modeSingleAudiobookLoop[] PROGMEM = "Modus: Hoerspiel in Endlosschleife"; -const char modeAllTrackAlphSorted[] PROGMEM = "Modus: Spiele alle Tracks (alphabetisch sortiert) des Ordners"; -const char modeAllTrackRandom[] PROGMEM = "Modus: Alle Tracks eines Ordners zufällig"; -const char modeAllTrackAlphSortedLoop[] PROGMEM = "Modus: Alle Tracks eines Ordners sortiert (alphabetisch) in Endlosschleife"; -const char modeAllTrackRandomLoop[] PROGMEM = "Modus: Alle Tracks eines Ordners zufällig in Endlosschleife"; -const char modeWebstream[] PROGMEM = "Modus: Webstream"; -const char webstreamNotAvailable[] PROGMEM = "Aktuell kein Webstream möglich, da keine WLAN-Verbindung vorhanden!"; -const char modeDoesNotExist[] PROGMEM = "Abspielmodus existiert nicht!"; -const char modeRepeatNone[] PROGMEM = "Repeatmodus: Kein Repeat"; -const char modeRepeatTrack[] PROGMEM = "Repeatmodus: Aktueller Titel"; -const char modeRepeatPlaylist[] PROGMEM = "Repeatmodus: Gesamte Playlist"; -const char modeRepeatTracknPlaylist[] PROGMEM = "Repeatmodus: Track und Playlist"; -const char modificatorAllButtonsLocked[] PROGMEM = "Modifikator: Alle Tasten werden per RFID gesperrt."; -const char modificatorAllButtonsUnlocked[] PROGMEM = "Modifikator: Alle Tasten werden per RFID freigegeben."; -const char modificatorSleepd[] PROGMEM = "Modifikator: Sleep-Timer wieder deaktiviert."; -const char modificatorSleepTimer15[] PROGMEM = "Modifikator: Sleep-Timer per RFID aktiviert (15 Minuten)."; -const char modificatorSleepTimer30[] PROGMEM = "Modifikator: Sleep-Timer per RFID aktiviert (30 Minuten)."; -const char modificatorSleepTimer60[] PROGMEM = "Modifikator: Sleep-Timer per RFID aktiviert (60 Minuten)."; -const char modificatorSleepTimer120[] PROGMEM = "Modifikator: Sleep-Timer per RFID aktiviert (2 Stunden)."; -const char ledsDimmedToNightmode[] PROGMEM = "LEDs wurden auf Nachtmodus gedimmt."; -const char modificatorNotallowedWhenIdle[] PROGMEM = "Modifikator kann bei nicht aktivierter Playlist nicht angewendet werden."; -const char modificatorSleepAtEOT[] PROGMEM = "Modifikator: Sleep-Timer am Ende des Titels aktiviert."; -const char modificatorSleepAtEOTd[] PROGMEM = "Modifikator: Sleep-Timer am Ende des Titels deaktiviert."; -const char modificatorSleepAtEOP[] PROGMEM = "Modifikator: Sleep-Timer am Ende der Playlist aktiviert."; -const char modificatorSleepAtEOPd[] PROGMEM = "Modifikator: Sleep-Timer am Ende der Playlist deaktiviert."; -const char modificatorAllTrackAlphSortedLoop[] PROGMEM = "Modifikator: Alle Titel (alphabetisch sortiert) in Endlosschleife."; -const char modificatorAllTrackRandomLoop[] PROGMEM = "Modifikator: Alle Titel (zufällige Reihenfolge) in Endlosschleife."; -const char modificatorCurTrackLoop[] PROGMEM = "Modifikator: Aktueller Titel in Endlosschleife."; -const char modificatorCurAudiobookLoop[] PROGMEM = "Modifikator: Aktuelles Hörspiel in Endlosschleife."; -const char modificatorPlaylistLoopActive[] PROGMEM = "Modifikator: Alle Titel in Endlosschleife aktiviert."; -const char modificatorPlaylistLoopDeactive[] PROGMEM = "Modifikator: Alle Titel in Endlosschleife deaktiviert."; -const char modificatorTrackActive[] PROGMEM = "Modifikator: Titel in Endlosschleife aktiviert."; -const char modificatorTrackDeactive[] PROGMEM = "Modifikator: Titel in Endlosschleife deaktiviert."; -const char modificatorNotAllowed[] PROGMEM = "Modifikator konnte nicht angewendet werden."; -const char modificatorLoopRev[] PROGMEM = "Modifikator: Endlosschleife beendet."; -const char modificatorDoesNotExist[] PROGMEM = "Ein Karten-Modifikator existiert nicht vom Typ"; -const char errorOccuredNvs[] PROGMEM = "Es ist ein Fehler aufgetreten beim Lesen aus dem NVS!"; -const char statementsReceivedByServer[] PROGMEM = "Vom Server wurde Folgendes empfangen"; -const char savedSsidInNvs[] PROGMEM = "Speichere SSID in NVS"; -const char savedWifiPwdInNvs[] PROGMEM = "Speichere WLAN-Password in NVS"; -const char apReady[] PROGMEM = "Access-Point geöffnet"; -const char httpReady[] PROGMEM = "HTTP-Server gestartet."; -const char unableToMountSd[] PROGMEM = "SD-Karte konnte nicht gemountet werden."; -const char unableToCreateVolQ[] PROGMEM = "Konnte Volume-Queue nicht anlegen."; -const char unableToCreateRfidQ[] PROGMEM = "Konnte RFID-Queue nicht anlegen."; -const char unableToCreateMgmtQ[] PROGMEM = "Konnte Play-Management-Queue nicht anlegen."; -const char unableToCreatePlayQ[] PROGMEM = "Konnte Track-Queue nicht anlegen.."; -const char initialBrightnessfromNvs[] PROGMEM = "Initiale LED-Helligkeit wurde aus NVS geladen"; -const char wroteInitialBrightnessToNvs[] PROGMEM = "Initiale LED-Helligkeit wurde ins NVS geschrieben."; -const char restoredInitialBrightnessForNmFromNvs[] PROGMEM = "LED-Helligkeit für Nachtmodus wurde aus NVS geladen"; -const char wroteNmBrightnessToNvs[] PROGMEM = "LED-Helligkeit für Nachtmodus wurde ins NVS geschrieben."; -const char wroteFtpUserToNvs[] PROGMEM = "FTP-User wurde ins NVS geschrieben."; -const char restoredFtpUserFromNvs[] PROGMEM = "FTP-User wurde aus NVS geladen"; -const char wroteFtpPwdToNvs[] PROGMEM = "FTP-Passwort wurde ins NVS geschrieben."; -const char restoredFtpPwdFromNvs[] PROGMEM = "FTP-Passwort wurde aus NVS geladen"; -const char restoredMaxInactivityFromNvs[] PROGMEM = "Maximale Inaktivitätszeit wurde aus NVS geladen"; -const char wroteMaxInactivityToNvs[] PROGMEM = "Maximale Inaktivitätszeit wurde ins NVS geschrieben."; -const char restoredInitialLoudnessFromNvs[] PROGMEM = "Initiale Lautstärke wurde aus NVS geladen"; -const char wroteInitialLoudnessToNvs[] PROGMEM = "Initiale Lautstärke wurde ins NVS geschrieben."; -const char restoredMaxLoudnessForSpeakerFromNvs[] PROGMEM = "Maximale Lautstärke für Lautsprecher wurde aus NVS geladen"; -const char restoredMaxLoudnessForHeadphoneFromNvs[] PROGMEM = "Maximale Lautstärke für Kopfhörer wurde aus NVS geladen"; -const char wroteMaxLoudnessForSpeakerToNvs[] PROGMEM = "Maximale Lautstärke für Lautsprecher wurde ins NVS geschrieben."; -const char wroteMaxLoudnessForHeadphoneToNvs[] PROGMEM = "Maximale Lautstärke für Kopfhörer wurde ins NVS geschrieben."; -const char maxVolumeSet[] PROGMEM = "Maximale Lautstärke wurde gesetzt auf"; -const char wroteMqttFlagToNvs[] PROGMEM = "MQTT-Flag wurde ins NVS geschrieben."; -const char restoredMqttActiveFromNvs[] PROGMEM = "MQTT-Flag (aktiviert) wurde aus NVS geladen"; -const char restoredMqttDeactiveFromNvs[] PROGMEM = "MQTT-Flag (deaktiviert) wurde aus NVS geladen"; -const char wroteMqttServerToNvs[] PROGMEM = "MQTT-Server wurde ins NVS geschrieben."; -const char restoredMqttServerFromNvs[] PROGMEM = "MQTT-Server wurde aus NVS geladen"; -const char wroteMqttUserToNvs[] PROGMEM = "MQTT-User wurde ins NVS geschrieben."; -const char restoredMqttUserFromNvs[] PROGMEM = "MQTT-User wurde aus NVS geladen"; -const char wroteMqttPwdToNvs[] PROGMEM = "MQTT-Passwort wurde ins NVS geschrieben."; -const char restoredMqttPwdFromNvs[] PROGMEM = "MQTT-Passwort wurde aus NVS geladen"; -const char restoredMqttPortFromNvs[] PROGMEM = "MQTT-Port wurde aus NVS geladen"; -const char mqttWithPwd[] PROGMEM = "Verbinde zu MQTT-Server mit User und Passwort"; -const char mqttWithoutPwd[] PROGMEM = "Verbinde zu MQTT-Server ohne User und Passwort"; -const char ssidNotFoundInNvs[] PROGMEM = "SSID wurde im NVS nicht gefunden."; -const char wifiPwdNotFoundInNvs[] PROGMEM = "WLAN-Passwort wurde im NVS nicht gefunden."; -const char wifiStaticIpConfigNotFoundInNvs[] PROGMEM = "Statische WLAN-IP-Konfiguration wurde im NVS nicht gefunden."; -const char wifiHostnameNotSet[] PROGMEM = "Keine Hostname-Konfiguration im NVS gefunden."; -const char mqttConnFailed[] PROGMEM = "Verbindung fehlgeschlagen, versuche in Kürze erneut"; -const char restoredHostnameFromNvs[] PROGMEM = "Hostname aus NVS geladen"; -const char currentVoltageMsg[] PROGMEM = "Aktuelle Batteriespannung"; -const char voltageTooLow[] PROGMEM = "Batteriespannung niedrig"; -const char sdBootFailedDeepsleep[] PROGMEM = "Bootgang wegen SD fehlgeschlagen. Gehe in Deepsleep..."; -const char wifiEnabledAfterRestart[] PROGMEM = "WLAN wird aktiviert."; -const char wifiDisabledAfterRestart[] PROGMEM = "WLAN wird deaktiviert."; -const char voltageIndicatorLowFromNVS[] PROGMEM = "Unterer Spannungslevel (Batterie) fuer Neopixel-Anzeige aus NVS geladen"; -const char voltageIndicatorHighFromNVS[] PROGMEM = "Oberer Spannungslevel (Batterie) fuer Neopixel-Anzeige aus NVS geladen"; -const char voltageCheckIntervalFromNVS[] PROGMEM = "Zyklus für Spannungsmessung (Batterie) fuer Neopixel-Anzeige aus NVS geladen"; -const char warningLowVoltageFromNVS[] PROGMEM = "Spannungslevel (Batterie) fuer Warnung via Neopixel aus NVS geladen"; -const char unableToRestoreLastRfidFromNVS[] PROGMEM = "Letzte RFID konnte nicht aus NVS geladen werden"; -const char restoredLastRfidFromNVS[] PROGMEM = "Letzte RFID wurde aus NVS geladen"; -const char failedOpenFileForWrite[] PROGMEM = "Öffnen der Datei für den Schreibvorgang fehlgeschlagen"; -const char fileWritten[] PROGMEM = "Datei geschrieben"; -const char writeFailed[] PROGMEM = "Schreibvorgang fehlgeschlagen"; -const char writingFile[] PROGMEM = "Schreibe Datei"; -const char failedToOpenFileForAppending[] PROGMEM = "Öffnen der Datei zum Schreiben der JSON-Datei fehlgeschlagen"; -const char listingDirectory[] PROGMEM = "Verzeichnisinhalt anzeigen"; -const char failedToOpenDirectory[] PROGMEM = "Öffnen des Verzeichnisses fehlgeschlagen"; -const char notADirectory[] PROGMEM = "Kein Verzeichnis"; -const char sdMountedMmc1BitMode[] PROGMEM = "Versuche SD-Karte wird im SD_MMC-Modus (1 Bit) zu mounten..."; -const char sdMountedSpiMode[] PROGMEM = "Versuche SD-Karte wird im SPI-Modus zu mounten..."; -const char backupRecoveryWebsite[] PROGMEM = "

    Das Backup-File wird eingespielt...
    Zur letzten Seite zurückkehren.

    "; -const char restartWebsite[] PROGMEM = "

    Der ESPuino wird neu gestartet...
    Zur letzten Seite zurückkehren.

    "; -const char shutdownWebsite[] PROGMEM = "

    Der ESPuino wird ausgeschaltet...

    "; -const char mqttMsgReceived[] PROGMEM = "MQTT-Nachricht empfangen"; -const char trackPausedAtPos[] PROGMEM = "Titel pausiert bei Position"; -const char freeHeapWithoutFtp[] PROGMEM = "Freier Heap-Speicher vor FTP-Instanzierung"; -const char freeHeapWithFtp[] PROGMEM = "Freier Heap-Speicher nach FTP-Instanzierung"; -const char freeHeapAfterSetup[] PROGMEM = "Freier Heap-Speicher nach Setup-Routine"; -const char tryStaticIpConfig[] PROGMEM = "Statische IP-Konfiguration wird durchgeführt..."; -const char staticIPConfigFailed[] PROGMEM = "Statische IP-Konfiguration fehlgeschlagen"; -const char wakeUpRfidNoIso14443[] PROGMEM = "ESP32 wurde vom Kartenleser aus dem Deepsleep aufgeweckt. Allerdings wurde keine ISO-14443-Karte gefunden. Gehe zurück in den Deepsleep..."; -const char lowPowerCardSuccess[] PROGMEM = "Kartenerkennung via 'low power' erfolgreich durchgeführt"; -const char rememberLastVolume[] PROGMEM = "Lautstärke vor dem letzten Shutdown wird wiederhergestellt. Dies überschreibt die Einstellung der initialen Lautstärke aus der GUI."; -const char unableToStartFtpServer[] PROGMEM = "Der FTP-Server konnte nicht gestartet werden. Entweder weil er ist bereits gestartet oder kein WLAN verfügbar ist."; -const char newPlayModeStereo[] PROGMEM = "Neuer Modus: stereo"; -const char newPlayModeMono[] PROGMEM = "Neuer Modus: mono"; + const char stillOnlineMqtt[] PROGMEM = "MQTT: Bin noch online."; + const char tryConnectMqttS[] PROGMEM = "Versuche Verbindung zu MQTT-Broker aufzubauen"; + const char mqttOk[] PROGMEM = "MQTT-Session aufgebaut."; + const char sleepTimerEOP[] PROGMEM = "Sleep-Timer: Nach dem letzten Track der Playlist."; + const char sleepTimerEOT[] PROGMEM = "Sleep-Timer: Nach dem Ende des laufenden Tracks."; + const char sleepTimerStop[] PROGMEM = "Sleep-Timer wurde deaktiviert."; + const char sleepTimerEO5[] PROGMEM = "Sleep Timer: Nach Ende des Titels oder, wenn früher, Ende der Playlist"; + const char sleepTimerAlreadyStopped[] PROGMEM = "Sleep-Timer ist bereits deaktiviert."; + const char sleepTimerSetTo[] PROGMEM = "Sleep-Timer gesetzt auf"; + const char allowButtons[] PROGMEM = "Alle Tasten werden freigegeben."; + const char lockButtons[] PROGMEM = "Alle Tasten werden gesperrt."; + const char noPlaylistNotAllowedMqtt[] PROGMEM = "Playmode kann nicht auf 'Keine Playlist' gesetzt werden via MQTT."; + const char playmodeChangedMQtt[] PROGMEM = "Playmode per MQTT angepasst."; + const char noPlaymodeChangeIfIdle[] PROGMEM = "Playmode kann nicht verändert werden, wenn keine Playlist aktiv ist."; + const char noValidTopic[] PROGMEM = "Kein gültiges Topic"; + const char freePtr[] PROGMEM = "Ptr-Freigabe"; + const char freeMemory[] PROGMEM = "Freier Speicher"; + const char writeEntryToNvs[] PROGMEM = "Schreibe Eintrag in NVS"; + const char freeMemoryAfterFree[] PROGMEM = "Freier Speicher nach Aufräumen"; + const char releaseMemoryOfOldPlaylist[] PROGMEM = "Gebe Speicher der alten Playlist frei."; + const char dirOrFileDoesNotExist[] PROGMEM = "Datei oder Verzeichnis existiert nicht "; + const char unableToAllocateMemForPlaylist[] PROGMEM = "Speicher für Playlist konnte nicht allokiert werden!"; + const char unableToAllocateMem[] PROGMEM = "Speicher konnte nicht allokiert werden!"; + const char fileModeDetected[] PROGMEM = "Dateimodus erkannt."; + const char nameOfFileFound[] PROGMEM = "Gefundenes File"; + const char reallocCalled[] PROGMEM = "Speicher reallokiert."; + const char unableToAllocateMemForLinearPlaylist[] PROGMEM = "Speicher für lineare Playlist konnte nicht allokiert werden!"; + const char numberOfValidFiles[] PROGMEM = "Anzahl gültiger Files"; + const char newLoudnessReceivedQueue[] PROGMEM = "Neue Lautstärke empfangen via Queue"; + const char newCntrlReceivedQueue[] PROGMEM = "Kontroll-Kommando empfangen via Queue"; + const char newPlaylistReceived[] PROGMEM = "Neue Playlist empfangen"; + const char repeatTrackDueToPlaymode[] PROGMEM = "Wiederhole Titel aufgrund von Playmode."; + const char repeatPlaylistDueToPlaymode[] PROGMEM = "Wiederhole Playlist aufgrund von Playmode."; + const char cmndStop[] PROGMEM = "Kommando: Stop"; + const char cmndPause[] PROGMEM = "Kommando: Pause"; + const char cmndNextTrack[] PROGMEM = "Kommando: Nächster Titel"; + const char cmndPrevTrack[] PROGMEM = "Kommando: Vorheriger Titel"; + const char cmndFirstTrack[] PROGMEM = "Kommando: Erster Titel von Playlist"; + const char cmndLastTrack[] PROGMEM = "Kommando: Letzter Titel von Playlist"; + const char cmndDoesNotExist[] PROGMEM = "Dieses Kommando existiert nicht."; + const char lastTrackAlreadyActive[] PROGMEM = "Es wird bereits der letzte Track gespielt."; + const char firstTrackAlreadyActive[] PROGMEM = "Es wird bereits der erste Track gespielt."; + const char trackStartAudiobook[] PROGMEM = "Titel wird im Hörspielmodus von vorne gespielt."; + const char trackStart[] PROGMEM = "Titel wird von vorne gespielt."; + const char trackChangeWebstream[] PROGMEM = "Im Webradio-Modus kann nicht an den Anfang gesprungen werden."; + const char endOfPlaylistReached[] PROGMEM = "Ende der Playlist erreicht."; + const char trackStartatPos[] PROGMEM = "Titel wird abgespielt ab Position"; + const char rfidScannerReady[] PROGMEM = "RFID-Tags koennen jetzt gescannt werden..."; + const char rfidTagDetected[] PROGMEM = "RFID-Karte erkannt: "; + const char rfid15693TagDetected[] PROGMEM = "RFID-Karte (ISO-15693) erkannt: "; + const char rfidTagReceived[] PROGMEM = "RFID-Karte empfangen"; + const char rfidTagUnknownInNvs[] PROGMEM = "RFID-Karte ist im NVS nicht hinterlegt."; + const char goToSleepDueToIdle[] PROGMEM = "Gehe in Deep Sleep wegen Inaktivität..."; + const char goToSleepDueToTimer[] PROGMEM = "Gehe in Deep Sleep wegen Sleep Timer..."; + const char goToSleepNow[] PROGMEM = "Gehe jetzt in Deep Sleep!"; + const char maxLoudnessReached[] PROGMEM = "Maximale Lautstärke bereits erreicht!"; + const char minLoudnessReached[] PROGMEM = "Minimale Lautstärke bereits erreicht!"; + const char errorOccured[] PROGMEM = "Fehler aufgetreten!"; + const char noMp3FilesInDir[] PROGMEM = "Verzeichnis beinhaltet keine mp3-Files."; + const char modeSingleTrack[] PROGMEM = "Modus: Einzelner Track"; + const char modeSingleTrackLoop[] PROGMEM = "Modus: Einzelner Track in Endlosschleife"; + const char modeSingleAudiobook[] PROGMEM = "Modus: Hoerspiel"; + const char modeSingleAudiobookLoop[] PROGMEM = "Modus: Hoerspiel in Endlosschleife"; + const char modeAllTrackAlphSorted[] PROGMEM = "Modus: Spiele alle Tracks (alphabetisch sortiert) des Ordners"; + const char modeAllTrackRandom[] PROGMEM = "Modus: Alle Tracks eines Ordners zufällig"; + const char modeAllTrackAlphSortedLoop[] PROGMEM = "Modus: Alle Tracks eines Ordners sortiert (alphabetisch) in Endlosschleife"; + const char modeAllTrackRandomLoop[] PROGMEM = "Modus: Alle Tracks eines Ordners zufällig in Endlosschleife"; + const char modeWebstream[] PROGMEM = "Modus: Webstream"; + const char webstreamNotAvailable[] PROGMEM = "Aktuell kein Webstream möglich, da keine WLAN-Verbindung vorhanden!"; + const char modeDoesNotExist[] PROGMEM = "Abspielmodus existiert nicht!"; + const char modeRepeatNone[] PROGMEM = "Repeatmodus: Kein Repeat"; + const char modeRepeatTrack[] PROGMEM = "Repeatmodus: Aktueller Titel"; + const char modeRepeatPlaylist[] PROGMEM = "Repeatmodus: Gesamte Playlist"; + const char modeRepeatTracknPlaylist[] PROGMEM = "Repeatmodus: Track und Playlist"; + const char modificatorAllButtonsLocked[] PROGMEM = "Modifikator: Alle Tasten werden per RFID gesperrt."; + const char modificatorAllButtonsUnlocked[] PROGMEM = "Modifikator: Alle Tasten werden per RFID freigegeben."; + const char modificatorSleepd[] PROGMEM = "Modifikator: Sleep-Timer wieder deaktiviert."; + const char modificatorSleepTimer15[] PROGMEM = "Modifikator: Sleep-Timer per RFID aktiviert (15 Minuten)."; + const char modificatorSleepTimer30[] PROGMEM = "Modifikator: Sleep-Timer per RFID aktiviert (30 Minuten)."; + const char modificatorSleepTimer60[] PROGMEM = "Modifikator: Sleep-Timer per RFID aktiviert (60 Minuten)."; + const char modificatorSleepTimer120[] PROGMEM = "Modifikator: Sleep-Timer per RFID aktiviert (2 Stunden)."; + const char ledsDimmedToNightmode[] PROGMEM = "LEDs wurden auf Nachtmodus gedimmt."; + const char modificatorNotallowedWhenIdle[] PROGMEM = "Modifikator kann bei nicht aktivierter Playlist nicht angewendet werden."; + const char modificatorSleepAtEOT[] PROGMEM = "Modifikator: Sleep-Timer am Ende des Titels aktiviert."; + const char modificatorSleepAtEOTd[] PROGMEM = "Modifikator: Sleep-Timer am Ende des Titels deaktiviert."; + const char modificatorSleepAtEOP[] PROGMEM = "Modifikator: Sleep-Timer am Ende der Playlist aktiviert."; + const char modificatorSleepAtEOPd[] PROGMEM = "Modifikator: Sleep-Timer am Ende der Playlist deaktiviert."; + const char modificatorAllTrackAlphSortedLoop[] PROGMEM = "Modifikator: Alle Titel (alphabetisch sortiert) in Endlosschleife."; + const char modificatorAllTrackRandomLoop[] PROGMEM = "Modifikator: Alle Titel (zufällige Reihenfolge) in Endlosschleife."; + const char modificatorCurTrackLoop[] PROGMEM = "Modifikator: Aktueller Titel in Endlosschleife."; + const char modificatorCurAudiobookLoop[] PROGMEM = "Modifikator: Aktuelles Hörspiel in Endlosschleife."; + const char modificatorPlaylistLoopActive[] PROGMEM = "Modifikator: Alle Titel in Endlosschleife aktiviert."; + const char modificatorPlaylistLoopDeactive[] PROGMEM = "Modifikator: Alle Titel in Endlosschleife deaktiviert."; + const char modificatorTrackActive[] PROGMEM = "Modifikator: Titel in Endlosschleife aktiviert."; + const char modificatorTrackDeactive[] PROGMEM = "Modifikator: Titel in Endlosschleife deaktiviert."; + const char modificatorNotAllowed[] PROGMEM = "Modifikator konnte nicht angewendet werden."; + const char modificatorLoopRev[] PROGMEM = "Modifikator: Endlosschleife beendet."; + const char modificatorDoesNotExist[] PROGMEM = "Ein Karten-Modifikator existiert nicht vom Typ"; + const char errorOccuredNvs[] PROGMEM = "Es ist ein Fehler aufgetreten beim Lesen aus dem NVS!"; + const char statementsReceivedByServer[] PROGMEM = "Vom Server wurde Folgendes empfangen"; + const char savedSsidInNvs[] PROGMEM = "Speichere SSID in NVS"; + const char savedWifiPwdInNvs[] PROGMEM = "Speichere WLAN-Password in NVS"; + const char apReady[] PROGMEM = "Access-Point geöffnet"; + const char httpReady[] PROGMEM = "HTTP-Server gestartet."; + const char unableToMountSd[] PROGMEM = "SD-Karte konnte nicht gemountet werden."; + const char unableToCreateVolQ[] PROGMEM = "Konnte Volume-Queue nicht anlegen."; + const char unableToCreateRfidQ[] PROGMEM = "Konnte RFID-Queue nicht anlegen."; + const char unableToCreateMgmtQ[] PROGMEM = "Konnte Play-Management-Queue nicht anlegen."; + const char unableToCreatePlayQ[] PROGMEM = "Konnte Track-Queue nicht anlegen.."; + const char initialBrightnessfromNvs[] PROGMEM = "Initiale LED-Helligkeit wurde aus NVS geladen"; + const char wroteInitialBrightnessToNvs[] PROGMEM = "Initiale LED-Helligkeit wurde ins NVS geschrieben."; + const char restoredInitialBrightnessForNmFromNvs[] PROGMEM = "LED-Helligkeit für Nachtmodus wurde aus NVS geladen"; + const char wroteNmBrightnessToNvs[] PROGMEM = "LED-Helligkeit für Nachtmodus wurde ins NVS geschrieben."; + const char wroteFtpUserToNvs[] PROGMEM = "FTP-User wurde ins NVS geschrieben."; + const char restoredFtpUserFromNvs[] PROGMEM = "FTP-User wurde aus NVS geladen"; + const char wroteFtpPwdToNvs[] PROGMEM = "FTP-Passwort wurde ins NVS geschrieben."; + const char restoredFtpPwdFromNvs[] PROGMEM = "FTP-Passwort wurde aus NVS geladen"; + const char restoredMaxInactivityFromNvs[] PROGMEM = "Maximale Inaktivitätszeit wurde aus NVS geladen"; + const char wroteMaxInactivityToNvs[] PROGMEM = "Maximale Inaktivitätszeit wurde ins NVS geschrieben."; + const char restoredInitialLoudnessFromNvs[] PROGMEM = "Initiale Lautstärke wurde aus NVS geladen"; + const char wroteInitialLoudnessToNvs[] PROGMEM = "Initiale Lautstärke wurde ins NVS geschrieben."; + const char restoredMaxLoudnessForSpeakerFromNvs[] PROGMEM = "Maximale Lautstärke für Lautsprecher wurde aus NVS geladen"; + const char restoredMaxLoudnessForHeadphoneFromNvs[] PROGMEM = "Maximale Lautstärke für Kopfhörer wurde aus NVS geladen"; + const char wroteMaxLoudnessForSpeakerToNvs[] PROGMEM = "Maximale Lautstärke für Lautsprecher wurde ins NVS geschrieben."; + const char wroteMaxLoudnessForHeadphoneToNvs[] PROGMEM = "Maximale Lautstärke für Kopfhörer wurde ins NVS geschrieben."; + const char maxVolumeSet[] PROGMEM = "Maximale Lautstärke wurde gesetzt auf"; + const char wroteMqttFlagToNvs[] PROGMEM = "MQTT-Flag wurde ins NVS geschrieben."; + const char restoredMqttActiveFromNvs[] PROGMEM = "MQTT-Flag (aktiviert) wurde aus NVS geladen"; + const char restoredMqttDeactiveFromNvs[] PROGMEM = "MQTT-Flag (deaktiviert) wurde aus NVS geladen"; + const char wroteMqttServerToNvs[] PROGMEM = "MQTT-Server wurde ins NVS geschrieben."; + const char restoredMqttServerFromNvs[] PROGMEM = "MQTT-Server wurde aus NVS geladen"; + const char wroteMqttUserToNvs[] PROGMEM = "MQTT-User wurde ins NVS geschrieben."; + const char restoredMqttUserFromNvs[] PROGMEM = "MQTT-User wurde aus NVS geladen"; + const char wroteMqttPwdToNvs[] PROGMEM = "MQTT-Passwort wurde ins NVS geschrieben."; + const char restoredMqttPwdFromNvs[] PROGMEM = "MQTT-Passwort wurde aus NVS geladen"; + const char restoredMqttPortFromNvs[] PROGMEM = "MQTT-Port wurde aus NVS geladen"; + const char mqttWithPwd[] PROGMEM = "Verbinde zu MQTT-Server mit User und Passwort"; + const char mqttWithoutPwd[] PROGMEM = "Verbinde zu MQTT-Server ohne User und Passwort"; + const char ssidNotFoundInNvs[] PROGMEM = "SSID wurde im NVS nicht gefunden."; + const char wifiPwdNotFoundInNvs[] PROGMEM = "WLAN-Passwort wurde im NVS nicht gefunden."; + const char wifiStaticIpConfigNotFoundInNvs[] PROGMEM = "Statische WLAN-IP-Konfiguration wurde im NVS nicht gefunden."; + const char wifiHostnameNotSet[] PROGMEM = "Keine Hostname-Konfiguration im NVS gefunden."; + const char mqttConnFailed[] PROGMEM = "Verbindung fehlgeschlagen, versuche in Kürze erneut"; + const char restoredHostnameFromNvs[] PROGMEM = "Hostname aus NVS geladen"; + const char currentVoltageMsg[] PROGMEM = "Aktuelle Batteriespannung"; + const char voltageTooLow[] PROGMEM = "Batteriespannung niedrig"; + const char sdBootFailedDeepsleep[] PROGMEM = "Bootgang wegen SD fehlgeschlagen. Gehe in Deepsleep..."; + const char wifiEnabledAfterRestart[] PROGMEM = "WLAN wird aktiviert."; + const char wifiDisabledAfterRestart[] PROGMEM = "WLAN wird deaktiviert."; + const char voltageIndicatorLowFromNVS[] PROGMEM = "Unterer Spannungslevel (Batterie) fuer Neopixel-Anzeige aus NVS geladen"; + const char voltageIndicatorHighFromNVS[] PROGMEM = "Oberer Spannungslevel (Batterie) fuer Neopixel-Anzeige aus NVS geladen"; + const char voltageCheckIntervalFromNVS[] PROGMEM = "Zyklus für Spannungsmessung (Batterie) fuer Neopixel-Anzeige aus NVS geladen"; + const char warningLowVoltageFromNVS[] PROGMEM = "Spannungslevel (Batterie) fuer Warnung via Neopixel aus NVS geladen"; + const char unableToRestoreLastRfidFromNVS[] PROGMEM = "Letzte RFID konnte nicht aus NVS geladen werden"; + const char restoredLastRfidFromNVS[] PROGMEM = "Letzte RFID wurde aus NVS geladen"; + const char failedOpenFileForWrite[] PROGMEM = "Öffnen der Datei für den Schreibvorgang fehlgeschlagen"; + const char fileWritten[] PROGMEM = "Datei geschrieben"; + const char writeFailed[] PROGMEM = "Schreibvorgang fehlgeschlagen"; + const char writingFile[] PROGMEM = "Schreibe Datei"; + const char failedToOpenFileForAppending[] PROGMEM = "Öffnen der Datei zum Schreiben der JSON-Datei fehlgeschlagen"; + const char listingDirectory[] PROGMEM = "Verzeichnisinhalt anzeigen"; + const char failedToOpenDirectory[] PROGMEM = "Öffnen des Verzeichnisses fehlgeschlagen"; + const char notADirectory[] PROGMEM = "Kein Verzeichnis"; + const char sdMountedMmc1BitMode[] PROGMEM = "Versuche SD-Karte wird im SD_MMC-Modus (1 Bit) zu mounten..."; + const char sdMountedSpiMode[] PROGMEM = "Versuche SD-Karte wird im SPI-Modus zu mounten..."; + const char backupRecoveryWebsite[] PROGMEM = "

    Das Backup-File wird eingespielt...
    Zur letzten Seite zurückkehren.

    "; + const char restartWebsite[] PROGMEM = "

    Der ESPuino wird neu gestartet...
    Zur letzten Seite zurückkehren.

    "; + const char shutdownWebsite[] PROGMEM = "

    Der ESPuino wird ausgeschaltet...

    "; + const char mqttMsgReceived[] PROGMEM = "MQTT-Nachricht empfangen"; + const char trackPausedAtPos[] PROGMEM = "Titel pausiert bei Position"; + const char freeHeapWithoutFtp[] PROGMEM = "Freier Heap-Speicher vor FTP-Instanzierung"; + const char freeHeapWithFtp[] PROGMEM = "Freier Heap-Speicher nach FTP-Instanzierung"; + const char freeHeapAfterSetup[] PROGMEM = "Freier Heap-Speicher nach Setup-Routine"; + const char tryStaticIpConfig[] PROGMEM = "Statische IP-Konfiguration wird durchgeführt..."; + const char staticIPConfigFailed[] PROGMEM = "Statische IP-Konfiguration fehlgeschlagen"; + const char wakeUpRfidNoIso14443[] PROGMEM = "ESP32 wurde vom Kartenleser aus dem Deepsleep aufgeweckt. Allerdings wurde keine ISO-14443-Karte gefunden. Gehe zurück in den Deepsleep..."; + const char lowPowerCardSuccess[] PROGMEM = "Kartenerkennung via 'low power' erfolgreich durchgeführt"; + const char rememberLastVolume[] PROGMEM = "Lautstärke vor dem letzten Shutdown wird wiederhergestellt. Dies überschreibt die Einstellung der initialen Lautstärke aus der GUI."; + const char unableToStartFtpServer[] PROGMEM = "Der FTP-Server konnte nicht gestartet werden. Entweder weil er ist bereits gestartet oder kein WLAN verfügbar ist."; + const char newPlayModeStereo[] PROGMEM = "Neuer Modus: stereo"; + const char newPlayModeMono[] PROGMEM = "Neuer Modus: mono"; #endif diff --git a/src/LogMessages_EN.cpp b/src/LogMessages_EN.cpp index d0ec5bb..42062ff 100644 --- a/src/LogMessages_EN.cpp +++ b/src/LogMessages_EN.cpp @@ -1,189 +1,189 @@ - + #include "settings.h" #if (LANGUAGE == 2) -#include "Log.h" + #include "Log.h" -const char stillOnlineMqtt[] PROGMEM = "MQTT: still online."; -const char tryConnectMqttS[] PROGMEM = "Trying to connect to MQTT-broker"; -const char mqttOk[] PROGMEM = "MQTT-connection established."; -const char sleepTimerEOP[] PROGMEM = "Sleep-timer: after last track of playlist."; -const char sleepTimerEOT[] PROGMEM = "Sleep-timer: after end of current track."; -const char sleepTimerStop[] PROGMEM = "Sleep-timer has been disabled."; -const char sleepTimerEO5[] PROGMEM = "Sleep-timer: after five track or end of playlist - whatever is reached first"; -const char sleepTimerAlreadyStopped[] PROGMEM = "sleep-timer is already disabled."; -const char sleepTimerSetTo[] PROGMEM = "sleep-timer adjusted to"; -const char allowButtons[] PROGMEM = "Unlocking all keys."; -const char lockButtons[] PROGMEM = "Locking all keys."; -const char noPlaylistNotAllowedMqtt[] PROGMEM = "Playmode cannot be adjusted to 'no playlist' via MQTT."; -const char playmodeChangedMQtt[] PROGMEM = "Playlist adjusted via MQTT."; -const char noPlaymodeChangeIfIdle[] PROGMEM = "Playlist cannot be adjusted while no playlist is active."; -const char noValidTopic[] PROGMEM = "No valid MQTT-topic"; -const char freePtr[] PROGMEM = "Releasing Pointer"; -const char freeMemory[] PROGMEM = "Free memory"; -const char writeEntryToNvs[] PROGMEM = "Storing data to NVS"; -const char freeMemoryAfterFree[] PROGMEM = "Free memory after cleaning"; -const char releaseMemoryOfOldPlaylist[] PROGMEM = "Releasing memory of old playlist."; -const char dirOrFileDoesNotExist[] PROGMEM = "File of directory does not exist"; -const char unableToAllocateMemForPlaylist[] PROGMEM = "Unable to allocate memory for playlist!"; -const char unableToAllocateMem[] PROGMEM = "Unable to allocate memory!"; -const char fileModeDetected[] PROGMEM = "File-mode detected."; -const char nameOfFileFound[] PROGMEM = "File found"; -const char reallocCalled[] PROGMEM = "Reallocated memory."; -const char unableToAllocateMemForLinearPlaylist[] PROGMEM = "Unable to allocate memory for linear playlist!"; -const char numberOfValidFiles[] PROGMEM = "Number of valid files"; -const char newLoudnessReceivedQueue[] PROGMEM = "New volume received via queue"; -const char newCntrlReceivedQueue[] PROGMEM = "Control-command received via queue"; -const char newPlaylistReceived[] PROGMEM = "New playlist received"; -const char repeatTrackDueToPlaymode[] PROGMEM = "Repeating track due to playmode configured."; -const char repeatPlaylistDueToPlaymode[] PROGMEM = "Repeating playlist due to playmode configured."; -const char cmndStop[] PROGMEM = "Command: stop"; -const char cmndPause[] PROGMEM = "Command: pause"; -const char cmndNextTrack[] PROGMEM = "Command: next track"; -const char cmndPrevTrack[] PROGMEM = "Command: previous track"; -const char cmndFirstTrack[] PROGMEM = "Command: first track of playlist"; -const char cmndLastTrack[] PROGMEM = "Command: last track of playlist"; -const char cmndDoesNotExist[] PROGMEM = "Command requested does not exist."; -const char lastTrackAlreadyActive[] PROGMEM = "Already playing last track."; -const char firstTrackAlreadyActive[] PROGMEM = "Already playing first track."; -const char trackStartAudiobook[] PROGMEM = "Starting track in playmode from the very beginning."; -const char trackStart[] PROGMEM = "Starting track from the very beginning."; -const char trackChangeWebstream[] PROGMEM = "Playing from the very beginning is not possible while webradio-mode is active."; -const char endOfPlaylistReached[] PROGMEM = "Reached end of playlist."; -const char trackStartatPos[] PROGMEM = "Starting track at position"; -const char rfidScannerReady[] PROGMEM = "RFID-tags can now be applied..."; -const char rfidTagDetected[] PROGMEM = "RFID-tag detected: "; -const char rfid15693TagDetected[] PROGMEM = "RFID-ta (ISO-15693) detected: "; -const char rfidTagReceived[] PROGMEM = "RFID-tag received"; -const char rfidTagUnknownInNvs[] PROGMEM = "RFID-tag is unkown to NVS."; -const char goToSleepDueToIdle[] PROGMEM = "Going to deepsleep due to inactivity-timer..."; -const char goToSleepDueToTimer[] PROGMEM = "Going to deepsleep due to sleep timer..."; -const char goToSleepNow[] PROGMEM = "Going to deepsleep now!"; -const char maxLoudnessReached[] PROGMEM = "Already reached max volume!"; -const char minLoudnessReached[] PROGMEM = "Already reached min volume!"; -const char errorOccured[] PROGMEM = "Error occured!"; -const char noMp3FilesInDir[] PROGMEM = "Directory does not contain mp3-files."; -const char modeSingleTrack[] PROGMEM = "Mode: Single track"; -const char modeSingleTrackLoop[] PROGMEM = "Mode: single track as infinite loop"; -const char modeSingleAudiobook[] PROGMEM = "Mode: audiobook"; -const char modeSingleAudiobookLoop[] PROGMEM = "Mode: audiobook as infinite loop"; -const char modeAllTrackAlphSorted[] PROGMEM = "Mode: all tracks (in alph. order) of directory"; -const char modeAllTrackRandom[] PROGMEM = "Mode: all tracks (in random. order) of directory"; -const char modeAllTrackAlphSortedLoop[] PROGMEM = "Mode: all tracks (in alph. order) of directory as infinite loop"; -const char modeAllTrackRandomLoop[] PROGMEM = "Mode: all tracks (in random order) of directory as infinite loop"; -const char modeWebstream[] PROGMEM = "Mode: webstream"; -const char webstreamNotAvailable[] PROGMEM = "Unable to access webstream as no wifi-connection is available!"; -const char modeDoesNotExist[] PROGMEM = "Playmode does not exist!"; -const char modeRepeatNone[] PROGMEM = "Repeatmode: no repeat"; -const char modeRepeatTrack[] PROGMEM = "Repeatmode: current track"; -const char modeRepeatPlaylist[] PROGMEM = "Repeatmode: whole playlist"; -const char modeRepeatTracknPlaylist[] PROGMEM = "Repeatmode: track and playlist"; -const char modificatorAllButtonsLocked[] PROGMEM = "Modificator: locking all keys via RFID-tag."; -const char modificatorAllButtonsUnlocked[] PROGMEM = "Modificator: unlocking all keys via RFID-tag."; -const char modificatorSleepd[] PROGMEM = "Modificator: sleep-Timer deactivated."; -const char modificatorSleepTimer15[] PROGMEM = "Modificator: sleep-Timer enabled via RFID (15 minutes)."; -const char modificatorSleepTimer30[] PROGMEM = "Modificator: sleep-Timer enabled via RFID (30 minutes)."; -const char modificatorSleepTimer60[] PROGMEM = "Modificator: sleep-Timer enabled via RFID (60 minutes)."; -const char modificatorSleepTimer120[] PROGMEM = "Modificator: sleep-Timer enabled via RFID (2 hours)."; -const char ledsDimmedToNightmode[] PROGMEM = "Dimmed LEDs to nightmode."; -const char modificatorNotallowedWhenIdle[] PROGMEM = "Modificator cannot be applied while playlist is inactive."; -const char modificatorSleepAtEOT[] PROGMEM = "Modificator: adjusted sleep-timer to after end of current track."; -const char modificatorSleepAtEOTd[] PROGMEM = "Modificator: disabled sleep-timer after end of current track."; -const char modificatorSleepAtEOP[] PROGMEM = "Modificator: adjusted sleep-timer to after end of playlist."; -const char modificatorSleepAtEOPd[] PROGMEM = "Modificator: disabled sleep-timer after end of playlist."; -const char modificatorAllTrackAlphSortedLoop[] PROGMEM = "Modificator: adjusted to all tracks (in alph. order) as infinite loop."; -const char modificatorAllTrackRandomLoop[] PROGMEM = "Modificator: adjusted to all tracks (in random order) as infinite loop."; -const char modificatorCurTrackLoop[] PROGMEM = "Modificator: adjusted to current track as infinite loop."; -const char modificatorCurAudiobookLoop[] PROGMEM = "Modificator: adjusted to current audiobook as infinite loop."; -const char modificatorPlaylistLoopActive[] PROGMEM = "Modificator: adjusted to all tracks as infinite loop."; -const char modificatorPlaylistLoopDeactive[] PROGMEM = "Modificator: disabled all tracks as infinite loop."; -const char modificatorTrackActive[] PROGMEM = "Modificator: adjusted to current track as infinite loop."; -const char modificatorTrackDeactive[] PROGMEM = "Modificator: disabled current track as infinite loop."; -const char modificatorNotAllowed[] PROGMEM = "Unable to apply modificator."; -const char modificatorLoopRev[] PROGMEM = "Modificator: infinite loop ended."; -const char modificatorDoesNotExist[] PROGMEM = "This type of card-modificator does not exist"; -const char errorOccuredNvs[] PROGMEM = "Error occured while reading from NVS!"; -const char statementsReceivedByServer[] PROGMEM = "Data received from server"; -const char savedSsidInNvs[] PROGMEM = "Storing SSID to NVS"; -const char savedWifiPwdInNvs[] PROGMEM = "Storing wifi-password to NVS"; -const char apReady[] PROGMEM = "Started wifi-access-point"; -const char httpReady[] PROGMEM = "Started HTTP-server."; -const char unableToMountSd[] PROGMEM = "Unable to mount sd-card."; -const char unableToCreateVolQ[] PROGMEM = "Unable to create volume-queue."; -const char unableToCreateRfidQ[] PROGMEM = "Unable to create RFID-queue."; -const char unableToCreateMgmtQ[] PROGMEM = "Unable to play-management-queue."; -const char unableToCreatePlayQ[] PROGMEM = "Unable to create track-queue.."; -const char initialBrightnessfromNvs[] PROGMEM = "Restoring initial LED-brightness from NVS"; -const char wroteInitialBrightnessToNvs[] PROGMEM = "Storing initial LED-brightness to NVS."; -const char restoredInitialBrightnessForNmFromNvs[] PROGMEM = "Restored LED-brightness for nightmode from NVS"; -const char wroteNmBrightnessToNvs[] PROGMEM = "Stored LED-brightness for nightmode to NVS."; -const char wroteFtpUserToNvs[] PROGMEM = "Stored FTP-user to NVS."; -const char restoredFtpUserFromNvs[] PROGMEM = "Restored FTP-user from NVS"; -const char wroteFtpPwdToNvs[] PROGMEM = "Stored FTP-password to NVS."; -const char restoredFtpPwdFromNvs[] PROGMEM = "Restored FTP-password from NVS"; -const char restoredMaxInactivityFromNvs[] PROGMEM = "Restored maximum inactivity-time from NVS."; -const char wroteMaxInactivityToNvs[] PROGMEM = "Stored maximum inactivity-time to NVS."; -const char restoredInitialLoudnessFromNvs[] PROGMEM = "Restored initial volume from NVS"; -const char wroteInitialLoudnessToNvs[] PROGMEM = "Stored initial volume to NVS."; -const char restoredMaxLoudnessForSpeakerFromNvs[] PROGMEM = "Restored maximum volume for speaker from NVS"; -const char restoredMaxLoudnessForHeadphoneFromNvs[] PROGMEM = "Restored maximum volume for headphone from NVS"; -const char wroteMaxLoudnessForSpeakerToNvs[] PROGMEM = "Wrote maximum volume for speaker to NVS."; -const char wroteMaxLoudnessForHeadphoneToNvs[] PROGMEM = "Wrote maximum volume for headphone to NVS."; -const char maxVolumeSet[] PROGMEM = "Maximum volume set to"; -const char wroteMqttFlagToNvs[] PROGMEM = "Stored MQTT-flag to NVS."; -const char restoredMqttActiveFromNvs[] PROGMEM = "Restored MQTT-flag (enabled) from NVS"; -const char restoredMqttDeactiveFromNvs[] PROGMEM = "Restored MQTT-flag (disabled) from NVS"; -const char wroteMqttServerToNvs[] PROGMEM = "Stored MQTT-server to NVS."; -const char restoredMqttServerFromNvs[] PROGMEM = "Restored MQTT-Server from NVS"; -const char wroteMqttUserToNvs[] PROGMEM = "Stored MQTT-user to NVS."; -const char restoredMqttUserFromNvs[] PROGMEM = "Restored MQTT-user from NVS"; -const char wroteMqttPwdToNvs[] PROGMEM = "Stored MQTT-password to NVS."; -const char restoredMqttPwdFromNvs[] PROGMEM = "Restored MQTT-password from NVS"; -const char restoredMqttPortFromNvs[] PROGMEM = "Restored MQTT-port from NVS"; -const char mqttWithPwd[] PROGMEM = "Try to connect to MQTT-server with user und password"; -const char mqttWithoutPwd[] PROGMEM = "Try to connect to MQTT-server without user und password"; -const char ssidNotFoundInNvs[] PROGMEM = "Unable to find SSID to NVS."; -const char wifiPwdNotFoundInNvs[] PROGMEM = "Unable to find wifi-password to NVS."; -const char wifiStaticIpConfigNotFoundInNvs[] PROGMEM = "Unable to find wifi-ip-configuration to NVS."; -const char wifiHostnameNotSet[] PROGMEM = "Unable to find hostname-configuration to NVS."; -const char mqttConnFailed[] PROGMEM = "Unable to establish mqtt-connection, trying again..."; -const char restoredHostnameFromNvs[] PROGMEM = "Restored hostname from NVS"; -const char currentVoltageMsg[] PROGMEM = "Current battery-voltage"; -const char voltageTooLow[] PROGMEM = "Low battery-voltage"; -const char sdBootFailedDeepsleep[] PROGMEM = "Failed to boot due to SD. Will go to deepsleep..."; -const char wifiEnabledAfterRestart[] PROGMEM = "WiFi will be enabled."; -const char wifiDisabledAfterRestart[] PROGMEM = "WiFi will be disabled ."; -const char voltageIndicatorLowFromNVS[] PROGMEM = "Restored lower voltage-level for Neopixel-display from NVS"; -const char voltageIndicatorHighFromNVS[] PROGMEM = "Restored upper voltage-level for Neopixel-display from NVS"; -const char voltageCheckIntervalFromNVS[] PROGMEM = "Restored interval of battery-measurement or Neopixel-display from NVS"; -const char warningLowVoltageFromNVS[] PROGMEM = "Restored battery-voltage-level for warning via Neopixel from NVS"; -const char unableToRestoreLastRfidFromNVS[] PROGMEM = "Unable to restore last RFID from NVS"; -const char restoredLastRfidFromNVS[] PROGMEM = "Restored last RFID from NVS"; -const char failedOpenFileForWrite[] PROGMEM = "Failed to open file for writing"; -const char fileWritten[] PROGMEM = "File written"; -const char writeFailed[] PROGMEM = "Write failed"; -const char writingFile[] PROGMEM = "Writing file"; -const char failedToOpenFileForAppending[] PROGMEM = "Failed to open file for appending"; -const char listingDirectory[] PROGMEM = "Listing directory"; -const char failedToOpenDirectory[] PROGMEM = "Failed to open directory"; -const char notADirectory[] PROGMEM = "Not a directory"; -const char sdMountedMmc1BitMode[] PROGMEM = "SD card mounted in SPI-mode configured..."; -const char sdMountedSpiMode[] PROGMEM = "Mounting SD card in SPI-mode..."; -const char backupRecoveryWebsite[] PROGMEM = "

    Backup-file is being applied...
    Back to last page.

    "; -const char restartWebsite[] PROGMEM = "

    ESPuino is being restarted...
    Back to last page.

    "; -const char shutdownWebsite[] PROGMEM = "

    Der ESPuino is being shutdown...

    "; -const char mqttMsgReceived[] PROGMEM = "MQTT-message received"; -const char trackPausedAtPos[] PROGMEM = "Track paused at position"; -const char freeHeapWithoutFtp[] PROGMEM = "Free heap before FTP-allocation"; -const char freeHeapWithFtp[] PROGMEM = "Free heap after FTP-allocation"; -const char freeHeapAfterSetup[] PROGMEM = "Free heap after setup"; -const char tryStaticIpConfig[] PROGMEM = "Performing IP-configuration..."; -const char staticIPConfigFailed[] PROGMEM = "IP-configuration failed"; -const char wakeUpRfidNoIso14443[] PROGMEM = "Wakeup caused by low power card-detection. RF-field changed but no ISO-14443 card on reader was found. So I'll return back to sleep now..."; -const char lowPowerCardSuccess[] PROGMEM = "Switch to low power card-detection: success"; -const char rememberLastVolume[] PROGMEM = "Restored volume used before last shutdown. This overwrites the initial volume configured via webgui."; -const char unableToStartFtpServer[] PROGMEM = "FTP-server cannot be started. This is because FTP-service is already active of because WiFi is unavailable."; -const char newPlayModeStereo[] PROGMEM = "New mode: stereo"; -const char newPlayModeMono[] PROGMEM = "New mode: mono"; + const char stillOnlineMqtt[] PROGMEM = "MQTT: still online."; + const char tryConnectMqttS[] PROGMEM = "Trying to connect to MQTT-broker"; + const char mqttOk[] PROGMEM = "MQTT-connection established."; + const char sleepTimerEOP[] PROGMEM = "Sleep-timer: after last track of playlist."; + const char sleepTimerEOT[] PROGMEM = "Sleep-timer: after end of current track."; + const char sleepTimerStop[] PROGMEM = "Sleep-timer has been disabled."; + const char sleepTimerEO5[] PROGMEM = "Sleep-timer: after five track or end of playlist - whatever is reached first"; + const char sleepTimerAlreadyStopped[] PROGMEM = "sleep-timer is already disabled."; + const char sleepTimerSetTo[] PROGMEM = "sleep-timer adjusted to"; + const char allowButtons[] PROGMEM = "Unlocking all keys."; + const char lockButtons[] PROGMEM = "Locking all keys."; + const char noPlaylistNotAllowedMqtt[] PROGMEM = "Playmode cannot be adjusted to 'no playlist' via MQTT."; + const char playmodeChangedMQtt[] PROGMEM = "Playlist adjusted via MQTT."; + const char noPlaymodeChangeIfIdle[] PROGMEM = "Playlist cannot be adjusted while no playlist is active."; + const char noValidTopic[] PROGMEM = "No valid MQTT-topic"; + const char freePtr[] PROGMEM = "Releasing Pointer"; + const char freeMemory[] PROGMEM = "Free memory"; + const char writeEntryToNvs[] PROGMEM = "Storing data to NVS"; + const char freeMemoryAfterFree[] PROGMEM = "Free memory after cleaning"; + const char releaseMemoryOfOldPlaylist[] PROGMEM = "Releasing memory of old playlist."; + const char dirOrFileDoesNotExist[] PROGMEM = "File of directory does not exist"; + const char unableToAllocateMemForPlaylist[] PROGMEM = "Unable to allocate memory for playlist!"; + const char unableToAllocateMem[] PROGMEM = "Unable to allocate memory!"; + const char fileModeDetected[] PROGMEM = "File-mode detected."; + const char nameOfFileFound[] PROGMEM = "File found"; + const char reallocCalled[] PROGMEM = "Reallocated memory."; + const char unableToAllocateMemForLinearPlaylist[] PROGMEM = "Unable to allocate memory for linear playlist!"; + const char numberOfValidFiles[] PROGMEM = "Number of valid files"; + const char newLoudnessReceivedQueue[] PROGMEM = "New volume received via queue"; + const char newCntrlReceivedQueue[] PROGMEM = "Control-command received via queue"; + const char newPlaylistReceived[] PROGMEM = "New playlist received"; + const char repeatTrackDueToPlaymode[] PROGMEM = "Repeating track due to playmode configured."; + const char repeatPlaylistDueToPlaymode[] PROGMEM = "Repeating playlist due to playmode configured."; + const char cmndStop[] PROGMEM = "Command: stop"; + const char cmndPause[] PROGMEM = "Command: pause"; + const char cmndNextTrack[] PROGMEM = "Command: next track"; + const char cmndPrevTrack[] PROGMEM = "Command: previous track"; + const char cmndFirstTrack[] PROGMEM = "Command: first track of playlist"; + const char cmndLastTrack[] PROGMEM = "Command: last track of playlist"; + const char cmndDoesNotExist[] PROGMEM = "Command requested does not exist."; + const char lastTrackAlreadyActive[] PROGMEM = "Already playing last track."; + const char firstTrackAlreadyActive[] PROGMEM = "Already playing first track."; + const char trackStartAudiobook[] PROGMEM = "Starting track in playmode from the very beginning."; + const char trackStart[] PROGMEM = "Starting track from the very beginning."; + const char trackChangeWebstream[] PROGMEM = "Playing from the very beginning is not possible while webradio-mode is active."; + const char endOfPlaylistReached[] PROGMEM = "Reached end of playlist."; + const char trackStartatPos[] PROGMEM = "Starting track at position"; + const char rfidScannerReady[] PROGMEM = "RFID-tags can now be applied..."; + const char rfidTagDetected[] PROGMEM = "RFID-tag detected: "; + const char rfid15693TagDetected[] PROGMEM = "RFID-ta (ISO-15693) detected: "; + const char rfidTagReceived[] PROGMEM = "RFID-tag received"; + const char rfidTagUnknownInNvs[] PROGMEM = "RFID-tag is unkown to NVS."; + const char goToSleepDueToIdle[] PROGMEM = "Going to deepsleep due to inactivity-timer..."; + const char goToSleepDueToTimer[] PROGMEM = "Going to deepsleep due to sleep timer..."; + const char goToSleepNow[] PROGMEM = "Going to deepsleep now!"; + const char maxLoudnessReached[] PROGMEM = "Already reached max volume!"; + const char minLoudnessReached[] PROGMEM = "Already reached min volume!"; + const char errorOccured[] PROGMEM = "Error occured!"; + const char noMp3FilesInDir[] PROGMEM = "Directory does not contain mp3-files."; + const char modeSingleTrack[] PROGMEM = "Mode: Single track"; + const char modeSingleTrackLoop[] PROGMEM = "Mode: single track as infinite loop"; + const char modeSingleAudiobook[] PROGMEM = "Mode: audiobook"; + const char modeSingleAudiobookLoop[] PROGMEM = "Mode: audiobook as infinite loop"; + const char modeAllTrackAlphSorted[] PROGMEM = "Mode: all tracks (in alph. order) of directory"; + const char modeAllTrackRandom[] PROGMEM = "Mode: all tracks (in random. order) of directory"; + const char modeAllTrackAlphSortedLoop[] PROGMEM = "Mode: all tracks (in alph. order) of directory as infinite loop"; + const char modeAllTrackRandomLoop[] PROGMEM = "Mode: all tracks (in random order) of directory as infinite loop"; + const char modeWebstream[] PROGMEM = "Mode: webstream"; + const char webstreamNotAvailable[] PROGMEM = "Unable to access webstream as no wifi-connection is available!"; + const char modeDoesNotExist[] PROGMEM = "Playmode does not exist!"; + const char modeRepeatNone[] PROGMEM = "Repeatmode: no repeat"; + const char modeRepeatTrack[] PROGMEM = "Repeatmode: current track"; + const char modeRepeatPlaylist[] PROGMEM = "Repeatmode: whole playlist"; + const char modeRepeatTracknPlaylist[] PROGMEM = "Repeatmode: track and playlist"; + const char modificatorAllButtonsLocked[] PROGMEM = "Modificator: locking all keys via RFID-tag."; + const char modificatorAllButtonsUnlocked[] PROGMEM = "Modificator: unlocking all keys via RFID-tag."; + const char modificatorSleepd[] PROGMEM = "Modificator: sleep-Timer deactivated."; + const char modificatorSleepTimer15[] PROGMEM = "Modificator: sleep-Timer enabled via RFID (15 minutes)."; + const char modificatorSleepTimer30[] PROGMEM = "Modificator: sleep-Timer enabled via RFID (30 minutes)."; + const char modificatorSleepTimer60[] PROGMEM = "Modificator: sleep-Timer enabled via RFID (60 minutes)."; + const char modificatorSleepTimer120[] PROGMEM = "Modificator: sleep-Timer enabled via RFID (2 hours)."; + const char ledsDimmedToNightmode[] PROGMEM = "Dimmed LEDs to nightmode."; + const char modificatorNotallowedWhenIdle[] PROGMEM = "Modificator cannot be applied while playlist is inactive."; + const char modificatorSleepAtEOT[] PROGMEM = "Modificator: adjusted sleep-timer to after end of current track."; + const char modificatorSleepAtEOTd[] PROGMEM = "Modificator: disabled sleep-timer after end of current track."; + const char modificatorSleepAtEOP[] PROGMEM = "Modificator: adjusted sleep-timer to after end of playlist."; + const char modificatorSleepAtEOPd[] PROGMEM = "Modificator: disabled sleep-timer after end of playlist."; + const char modificatorAllTrackAlphSortedLoop[] PROGMEM = "Modificator: adjusted to all tracks (in alph. order) as infinite loop."; + const char modificatorAllTrackRandomLoop[] PROGMEM = "Modificator: adjusted to all tracks (in random order) as infinite loop."; + const char modificatorCurTrackLoop[] PROGMEM = "Modificator: adjusted to current track as infinite loop."; + const char modificatorCurAudiobookLoop[] PROGMEM = "Modificator: adjusted to current audiobook as infinite loop."; + const char modificatorPlaylistLoopActive[] PROGMEM = "Modificator: adjusted to all tracks as infinite loop."; + const char modificatorPlaylistLoopDeactive[] PROGMEM = "Modificator: disabled all tracks as infinite loop."; + const char modificatorTrackActive[] PROGMEM = "Modificator: adjusted to current track as infinite loop."; + const char modificatorTrackDeactive[] PROGMEM = "Modificator: disabled current track as infinite loop."; + const char modificatorNotAllowed[] PROGMEM = "Unable to apply modificator."; + const char modificatorLoopRev[] PROGMEM = "Modificator: infinite loop ended."; + const char modificatorDoesNotExist[] PROGMEM = "This type of card-modificator does not exist"; + const char errorOccuredNvs[] PROGMEM = "Error occured while reading from NVS!"; + const char statementsReceivedByServer[] PROGMEM = "Data received from server"; + const char savedSsidInNvs[] PROGMEM = "Storing SSID to NVS"; + const char savedWifiPwdInNvs[] PROGMEM = "Storing wifi-password to NVS"; + const char apReady[] PROGMEM = "Started wifi-access-point"; + const char httpReady[] PROGMEM = "Started HTTP-server."; + const char unableToMountSd[] PROGMEM = "Unable to mount sd-card."; + const char unableToCreateVolQ[] PROGMEM = "Unable to create volume-queue."; + const char unableToCreateRfidQ[] PROGMEM = "Unable to create RFID-queue."; + const char unableToCreateMgmtQ[] PROGMEM = "Unable to play-management-queue."; + const char unableToCreatePlayQ[] PROGMEM = "Unable to create track-queue.."; + const char initialBrightnessfromNvs[] PROGMEM = "Restoring initial LED-brightness from NVS"; + const char wroteInitialBrightnessToNvs[] PROGMEM = "Storing initial LED-brightness to NVS."; + const char restoredInitialBrightnessForNmFromNvs[] PROGMEM = "Restored LED-brightness for nightmode from NVS"; + const char wroteNmBrightnessToNvs[] PROGMEM = "Stored LED-brightness for nightmode to NVS."; + const char wroteFtpUserToNvs[] PROGMEM = "Stored FTP-user to NVS."; + const char restoredFtpUserFromNvs[] PROGMEM = "Restored FTP-user from NVS"; + const char wroteFtpPwdToNvs[] PROGMEM = "Stored FTP-password to NVS."; + const char restoredFtpPwdFromNvs[] PROGMEM = "Restored FTP-password from NVS"; + const char restoredMaxInactivityFromNvs[] PROGMEM = "Restored maximum inactivity-time from NVS."; + const char wroteMaxInactivityToNvs[] PROGMEM = "Stored maximum inactivity-time to NVS."; + const char restoredInitialLoudnessFromNvs[] PROGMEM = "Restored initial volume from NVS"; + const char wroteInitialLoudnessToNvs[] PROGMEM = "Stored initial volume to NVS."; + const char restoredMaxLoudnessForSpeakerFromNvs[] PROGMEM = "Restored maximum volume for speaker from NVS"; + const char restoredMaxLoudnessForHeadphoneFromNvs[] PROGMEM = "Restored maximum volume for headphone from NVS"; + const char wroteMaxLoudnessForSpeakerToNvs[] PROGMEM = "Wrote maximum volume for speaker to NVS."; + const char wroteMaxLoudnessForHeadphoneToNvs[] PROGMEM = "Wrote maximum volume for headphone to NVS."; + const char maxVolumeSet[] PROGMEM = "Maximum volume set to"; + const char wroteMqttFlagToNvs[] PROGMEM = "Stored MQTT-flag to NVS."; + const char restoredMqttActiveFromNvs[] PROGMEM = "Restored MQTT-flag (enabled) from NVS"; + const char restoredMqttDeactiveFromNvs[] PROGMEM = "Restored MQTT-flag (disabled) from NVS"; + const char wroteMqttServerToNvs[] PROGMEM = "Stored MQTT-server to NVS."; + const char restoredMqttServerFromNvs[] PROGMEM = "Restored MQTT-Server from NVS"; + const char wroteMqttUserToNvs[] PROGMEM = "Stored MQTT-user to NVS."; + const char restoredMqttUserFromNvs[] PROGMEM = "Restored MQTT-user from NVS"; + const char wroteMqttPwdToNvs[] PROGMEM = "Stored MQTT-password to NVS."; + const char restoredMqttPwdFromNvs[] PROGMEM = "Restored MQTT-password from NVS"; + const char restoredMqttPortFromNvs[] PROGMEM = "Restored MQTT-port from NVS"; + const char mqttWithPwd[] PROGMEM = "Try to connect to MQTT-server with user und password"; + const char mqttWithoutPwd[] PROGMEM = "Try to connect to MQTT-server without user und password"; + const char ssidNotFoundInNvs[] PROGMEM = "Unable to find SSID to NVS."; + const char wifiPwdNotFoundInNvs[] PROGMEM = "Unable to find wifi-password to NVS."; + const char wifiStaticIpConfigNotFoundInNvs[] PROGMEM = "Unable to find wifi-ip-configuration to NVS."; + const char wifiHostnameNotSet[] PROGMEM = "Unable to find hostname-configuration to NVS."; + const char mqttConnFailed[] PROGMEM = "Unable to establish mqtt-connection, trying again..."; + const char restoredHostnameFromNvs[] PROGMEM = "Restored hostname from NVS"; + const char currentVoltageMsg[] PROGMEM = "Current battery-voltage"; + const char voltageTooLow[] PROGMEM = "Low battery-voltage"; + const char sdBootFailedDeepsleep[] PROGMEM = "Failed to boot due to SD. Will go to deepsleep..."; + const char wifiEnabledAfterRestart[] PROGMEM = "WiFi will be enabled."; + const char wifiDisabledAfterRestart[] PROGMEM = "WiFi will be disabled ."; + const char voltageIndicatorLowFromNVS[] PROGMEM = "Restored lower voltage-level for Neopixel-display from NVS"; + const char voltageIndicatorHighFromNVS[] PROGMEM = "Restored upper voltage-level for Neopixel-display from NVS"; + const char voltageCheckIntervalFromNVS[] PROGMEM = "Restored interval of battery-measurement or Neopixel-display from NVS"; + const char warningLowVoltageFromNVS[] PROGMEM = "Restored battery-voltage-level for warning via Neopixel from NVS"; + const char unableToRestoreLastRfidFromNVS[] PROGMEM = "Unable to restore last RFID from NVS"; + const char restoredLastRfidFromNVS[] PROGMEM = "Restored last RFID from NVS"; + const char failedOpenFileForWrite[] PROGMEM = "Failed to open file for writing"; + const char fileWritten[] PROGMEM = "File written"; + const char writeFailed[] PROGMEM = "Write failed"; + const char writingFile[] PROGMEM = "Writing file"; + const char failedToOpenFileForAppending[] PROGMEM = "Failed to open file for appending"; + const char listingDirectory[] PROGMEM = "Listing directory"; + const char failedToOpenDirectory[] PROGMEM = "Failed to open directory"; + const char notADirectory[] PROGMEM = "Not a directory"; + const char sdMountedMmc1BitMode[] PROGMEM = "SD card mounted in SPI-mode configured..."; + const char sdMountedSpiMode[] PROGMEM = "Mounting SD card in SPI-mode..."; + const char backupRecoveryWebsite[] PROGMEM = "

    Backup-file is being applied...
    Back to last page.

    "; + const char restartWebsite[] PROGMEM = "

    ESPuino is being restarted...
    Back to last page.

    "; + const char shutdownWebsite[] PROGMEM = "

    Der ESPuino is being shutdown...

    "; + const char mqttMsgReceived[] PROGMEM = "MQTT-message received"; + const char trackPausedAtPos[] PROGMEM = "Track paused at position"; + const char freeHeapWithoutFtp[] PROGMEM = "Free heap before FTP-allocation"; + const char freeHeapWithFtp[] PROGMEM = "Free heap after FTP-allocation"; + const char freeHeapAfterSetup[] PROGMEM = "Free heap after setup"; + const char tryStaticIpConfig[] PROGMEM = "Performing IP-configuration..."; + const char staticIPConfigFailed[] PROGMEM = "IP-configuration failed"; + const char wakeUpRfidNoIso14443[] PROGMEM = "Wakeup caused by low power card-detection. RF-field changed but no ISO-14443 card on reader was found. So I'll return back to sleep now..."; + const char lowPowerCardSuccess[] PROGMEM = "Switch to low power card-detection: success"; + const char rememberLastVolume[] PROGMEM = "Restored volume used before last shutdown. This overwrites the initial volume configured via webgui."; + const char unableToStartFtpServer[] PROGMEM = "FTP-server cannot be started. This is because FTP-service is already active of because WiFi is unavailable."; + const char newPlayModeStereo[] PROGMEM = "New mode: stereo"; + const char newPlayModeMono[] PROGMEM = "New mode: mono"; #endif diff --git a/src/Mqtt.cpp b/src/Mqtt.cpp index 3a3eabe..4e79b16 100644 --- a/src/Mqtt.cpp +++ b/src/Mqtt.cpp @@ -19,14 +19,14 @@ constexpr uint8_t stillOnlineInterval = 60u; // Interval 'I'm still alive' is se // MQTT-helper #ifdef MQTT_ENABLE -static WiFiClient Mqtt_WifiClient; -static PubSubClient Mqtt_PubSubClient(Mqtt_WifiClient); + static WiFiClient Mqtt_WifiClient; + static PubSubClient Mqtt_PubSubClient(Mqtt_WifiClient); #endif // Please note: all of them are defaults that can be changed later via GUI -char *gMqttServer = x_strndup((char *)"192.168.2.43", mqttServerLength); // IP-address of MQTT-server (if not found in NVS this one will be taken) -char *gMqttUser = x_strndup((char *)"mqtt-user", mqttUserLength); // MQTT-user -char *gMqttPassword = x_strndup((char *)"mqtt-password", mqttPasswordLength); // MQTT-password*/ +char *gMqttServer = x_strndup((char *) "192.168.2.43", mqttServerLength); // IP-address of MQTT-server (if not found in NVS this one will be taken) +char *gMqttUser = x_strndup((char *) "mqtt-user", mqttUserLength); // MQTT-user +char *gMqttPassword = x_strndup((char *) "mqtt-password", mqttPasswordLength); // MQTT-password*/ uint16_t gMqttPort = 1883; // MQTT-Port // MQTT @@ -36,481 +36,406 @@ 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() -{ -#ifdef MQTT_ENABLE - // Get MQTT-enable from NVS - uint8_t nvsEnableMqtt = gPrefsSettings.getUChar("enableMQTT", 99); - switch (nvsEnableMqtt) - { - case 99: - gPrefsSettings.putUChar("enableMQTT", Mqtt_Enabled); - Log_Println((char *)FPSTR(wroteMqttFlagToNvs), LOGLEVEL_ERROR); - break; - case 1: - Mqtt_Enabled = nvsEnableMqtt; - snprintf(Log_Buffer, Log_BufferLength, "%s: %u", (char *)FPSTR(restoredMqttActiveFromNvs), nvsEnableMqtt); - Log_Println(Log_Buffer, LOGLEVEL_INFO); - break; - case 0: - Mqtt_Enabled = nvsEnableMqtt; - snprintf(Log_Buffer, Log_BufferLength, "%s: %u", (char *)FPSTR(restoredMqttDeactiveFromNvs), nvsEnableMqtt); - Log_Println(Log_Buffer, LOGLEVEL_INFO); - break; - } - - // Get MQTT-server from NVS - String nvsMqttServer = gPrefsSettings.getString("mqttServer", "-1"); - if (!nvsMqttServer.compareTo("-1")) - { - gPrefsSettings.putString("mqttServer", (String)gMqttServer); - Log_Println((char *)FPSTR(wroteMqttServerToNvs), LOGLEVEL_ERROR); - } - 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); - } - - // Get MQTT-user from NVS - String nvsMqttUser = gPrefsSettings.getString("mqttUser", "-1"); - if (!nvsMqttUser.compareTo("-1")) - { - gPrefsSettings.putString("mqttUser", (String)gMqttUser); - Log_Println((char *)FPSTR(wroteMqttUserToNvs), LOGLEVEL_ERROR); - } - 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); - } - - // Get MQTT-password from NVS - String nvsMqttPassword = gPrefsSettings.getString("mqttPassword", "-1"); - if (!nvsMqttPassword.compareTo("-1")) - { - gPrefsSettings.putString("mqttPassword", (String)gMqttPassword); - Log_Println((char *)FPSTR(wroteMqttPwdToNvs), LOGLEVEL_ERROR); - } - 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); - } - - // Get MQTT-password from NVS - uint32_t nvsMqttPort = gPrefsSettings.getUInt("mqttPort", 99999); - if (nvsMqttPort == 99999) - { - gPrefsSettings.putUInt("mqttPort", gMqttPort); - } - 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) - { - Mqtt_PubSubClient.setServer(gMqttServer, gMqttPort); - Mqtt_PubSubClient.setCallback(Mqtt_ClientCallback); - } -#endif +void Mqtt_Init() { + #ifdef MQTT_ENABLE + // Get MQTT-enable from NVS + uint8_t nvsEnableMqtt = gPrefsSettings.getUChar("enableMQTT", 99); + switch (nvsEnableMqtt) { + case 99: + gPrefsSettings.putUChar("enableMQTT", Mqtt_Enabled); + Log_Println((char *) FPSTR(wroteMqttFlagToNvs), LOGLEVEL_ERROR); + break; + case 1: + Mqtt_Enabled = nvsEnableMqtt; + snprintf(Log_Buffer, Log_BufferLength, "%s: %u", (char *) FPSTR(restoredMqttActiveFromNvs), nvsEnableMqtt); + Log_Println(Log_Buffer, LOGLEVEL_INFO); + break; + case 0: + Mqtt_Enabled = nvsEnableMqtt; + snprintf(Log_Buffer, Log_BufferLength, "%s: %u", (char *) FPSTR(restoredMqttDeactiveFromNvs), nvsEnableMqtt); + Log_Println(Log_Buffer, LOGLEVEL_INFO); + break; + } + + // Get MQTT-server from NVS + String nvsMqttServer = gPrefsSettings.getString("mqttServer", "-1"); + if (!nvsMqttServer.compareTo("-1")) { + gPrefsSettings.putString("mqttServer", (String)gMqttServer); + Log_Println((char *) FPSTR(wroteMqttServerToNvs), LOGLEVEL_ERROR); + } 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); + } + + // Get MQTT-user from NVS + String nvsMqttUser = gPrefsSettings.getString("mqttUser", "-1"); + if (!nvsMqttUser.compareTo("-1")) { + gPrefsSettings.putString("mqttUser", (String)gMqttUser); + Log_Println((char *) FPSTR(wroteMqttUserToNvs), LOGLEVEL_ERROR); + } 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); + } + + // Get MQTT-password from NVS + String nvsMqttPassword = gPrefsSettings.getString("mqttPassword", "-1"); + if (!nvsMqttPassword.compareTo("-1")) { + gPrefsSettings.putString("mqttPassword", (String)gMqttPassword); + Log_Println((char *) FPSTR(wroteMqttPwdToNvs), LOGLEVEL_ERROR); + } 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); + } + + // Get MQTT-password from NVS + uint32_t nvsMqttPort = gPrefsSettings.getUInt("mqttPort", 99999); + if (nvsMqttPort == 99999) { + gPrefsSettings.putUInt("mqttPort", gMqttPort); + } 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) { + Mqtt_PubSubClient.setServer(gMqttServer, gMqttPort); + Mqtt_PubSubClient.setCallback(Mqtt_ClientCallback); + } + #endif } -void Mqtt_Cyclic(void) -{ -#ifdef MQTT_ENABLE - if (Mqtt_Enabled && Wlan_IsConnected()) - { - Mqtt_Reconnect(); - Mqtt_PubSubClient.loop(); - Mqtt_PostHeartbeatViaMqtt(); - } -#endif +void Mqtt_Cyclic(void) { + #ifdef MQTT_ENABLE + if (Mqtt_Enabled && Wlan_IsConnected()) { + Mqtt_Reconnect(); + Mqtt_PubSubClient.loop(); + Mqtt_PostHeartbeatViaMqtt(); + } + #endif } -void Mqtt_Exit(void) -{ -#ifdef MQTT_ENABLE - publishMqtt((char *)FPSTR(topicState), "Offline", false); - publishMqtt((char *)FPSTR(topicTrackState), "---", false); - Mqtt_PubSubClient.disconnect(); -#endif +void Mqtt_Exit(void) { + #ifdef MQTT_ENABLE + publishMqtt((char *) FPSTR(topicState), "Offline", false); + publishMqtt((char *) FPSTR(topicTrackState), "---", false); + Mqtt_PubSubClient.disconnect(); + #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) -{ -#ifdef MQTT_ENABLE - if (strcmp(topic, "") != 0) - { - if (Mqtt_PubSubClient.connected()) - { - Mqtt_PubSubClient.publish(topic, payload, retained); - delay(100); - return true; +bool publishMqtt(const char *topic, const char *payload, bool retained) { + #ifdef MQTT_ENABLE + if (strcmp(topic, "") != 0) { + if (Mqtt_PubSubClient.connected()) { + Mqtt_PubSubClient.publish(topic, payload, retained); + delay(100); + return true; + } } - } -#endif + #endif + return false; } -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); - return publishMqtt(topic, buf, retained); -#else - return false; -#endif +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); + return publishMqtt(topic, buf, retained); + #else + return false; + #endif } -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); - return publishMqtt(topic, buf, retained); -#else - return false; -#endif +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); + return publishMqtt(topic, buf, retained); + #else + return false; + #endif } -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); - return publishMqtt(topic, buf, retained); -#else - return false; -#endif +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); + return publishMqtt(topic, buf, retained); + #else + return false; + #endif } /* Cyclic posting via MQTT that ESP is still alive. Use case: when ESPuino is switched off, it will post via 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) -{ -#ifdef MQTT_ENABLE - static unsigned long lastOnlineTimestamp = 0u; - - if (millis() - lastOnlineTimestamp >= stillOnlineInterval * 1000) - { - lastOnlineTimestamp = millis(); - if (publishMqtt((char *)FPSTR(topicState), "Online", false)) - { - Log_Println((char *)FPSTR(stillOnlineMqtt), LOGLEVEL_DEBUG); +void Mqtt_PostHeartbeatViaMqtt(void) { + #ifdef MQTT_ENABLE + static unsigned long lastOnlineTimestamp = 0u; + + if (millis() - lastOnlineTimestamp >= stillOnlineInterval * 1000) { + lastOnlineTimestamp = millis(); + if (publishMqtt((char *) FPSTR(topicState), "Online", false)) { + Log_Println((char *) FPSTR(stillOnlineMqtt), LOGLEVEL_DEBUG); + } } - } -#endif + #endif } /* Connects/reconnects to MQTT-Broker unless connection is not already available. Manages MQTT-subscriptions. */ -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) - { - mqttLastRetryTimestamp = millis(); - } - else - { - return false; - } - - 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) - { - Log_Println((char *)FPSTR(mqttWithoutPwd), LOGLEVEL_NOTICE); - if (Mqtt_PubSubClient.connect(DEVICE_HOSTNAME)) - { - connect = true; - } +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) { + mqttLastRetryTimestamp = millis(); + } else { + return false; } - else - { - Log_Println((char *)FPSTR(mqttWithPwd), LOGLEVEL_NOTICE); - if (Mqtt_PubSubClient.connect(DEVICE_HOSTNAME, gMqttUser, gMqttPassword)) - { - connect = true; + + 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) { + Log_Println((char *) FPSTR(mqttWithoutPwd), LOGLEVEL_NOTICE); + if (Mqtt_PubSubClient.connect(DEVICE_HOSTNAME)) { + connect = true; + } + } else { + Log_Println((char *) FPSTR(mqttWithPwd), LOGLEVEL_NOTICE); + if (Mqtt_PubSubClient.connect(DEVICE_HOSTNAME, gMqttUser, gMqttPassword)) { + connect = true; + } } - } - if (connect) - { - Log_Println((char *)FPSTR(mqttOk), LOGLEVEL_NOTICE); + if (connect) { + Log_Println((char *) FPSTR(mqttOk), LOGLEVEL_NOTICE); - // Deepsleep-subscription - Mqtt_PubSubClient.subscribe((char *)FPSTR(topicSleepCmnd)); + // Deepsleep-subscription + Mqtt_PubSubClient.subscribe((char *) FPSTR(topicSleepCmnd)); - // RFID-Tag-ID-subscription - Mqtt_PubSubClient.subscribe((char *)FPSTR(topicRfidCmnd)); + // RFID-Tag-ID-subscription + Mqtt_PubSubClient.subscribe((char *) FPSTR(topicRfidCmnd)); - // Loudness-subscription - Mqtt_PubSubClient.subscribe((char *)FPSTR(topicLoudnessCmnd)); + // Loudness-subscription + Mqtt_PubSubClient.subscribe((char *) FPSTR(topicLoudnessCmnd)); - // Sleep-Timer-subscription - Mqtt_PubSubClient.subscribe((char *)FPSTR(topicSleepTimerCmnd)); + // Sleep-Timer-subscription + Mqtt_PubSubClient.subscribe((char *) FPSTR(topicSleepTimerCmnd)); - // Next/previous/stop/play-track-subscription - Mqtt_PubSubClient.subscribe((char *)FPSTR(topicTrackControlCmnd)); + // Next/previous/stop/play-track-subscription + Mqtt_PubSubClient.subscribe((char *) FPSTR(topicTrackControlCmnd)); - // Lock controls - Mqtt_PubSubClient.subscribe((char *)FPSTR(topicLockControlsCmnd)); + // Lock controls + Mqtt_PubSubClient.subscribe((char *) FPSTR(topicLockControlsCmnd)); - // Current repeat-Mode - Mqtt_PubSubClient.subscribe((char *)FPSTR(topicRepeatModeCmnd)); + // Current repeat-Mode + Mqtt_PubSubClient.subscribe((char *) FPSTR(topicRepeatModeCmnd)); - // LED-brightness - Mqtt_PubSubClient.subscribe((char *)FPSTR(topicLedBrightnessCmnd)); + // LED-brightness + Mqtt_PubSubClient.subscribe((char *) FPSTR(topicLedBrightnessCmnd)); - // Publish some stuff - publishMqtt((char *)FPSTR(topicState), "Online", false); - publishMqtt((char *)FPSTR(topicTrackState), "---", false); - publishMqtt((char *)FPSTR(topicLoudnessState), AudioPlayer_GetCurrentVolume(), false); - publishMqtt((char *)FPSTR(topicSleepTimerState), System_GetSleepTimerTimeStamp(), false); - publishMqtt((char *)FPSTR(topicLockControlsState), "OFF", false); - publishMqtt((char *)FPSTR(topicPlaymodeState), gPlayProperties.playMode, false); - publishMqtt((char *)FPSTR(topicLedBrightnessState), Led_GetBrightness(), false); - publishMqtt((char *)FPSTR(topicRepeatModeState), 0, false); - publishMqtt((char *)FPSTR(topicCurrentIPv4IP), Wlan_GetIpAddress().c_str(), false); + // Publish some stuff + publishMqtt((char *) FPSTR(topicState), "Online", false); + publishMqtt((char *) FPSTR(topicTrackState), "---", false); + publishMqtt((char *) FPSTR(topicLoudnessState), AudioPlayer_GetCurrentVolume(), false); + publishMqtt((char *) FPSTR(topicSleepTimerState), System_GetSleepTimerTimeStamp(), false); + publishMqtt((char *) FPSTR(topicLockControlsState), "OFF", false); + publishMqtt((char *) FPSTR(topicPlaymodeState), gPlayProperties.playMode, false); + publishMqtt((char *) FPSTR(topicLedBrightnessState), Led_GetBrightness(), false); + publishMqtt((char *) FPSTR(topicRepeatModeState), 0, false); + publishMqtt((char *) FPSTR(topicCurrentIPv4IP), Wlan_GetIpAddress().c_str(), false); - return Mqtt_PubSubClient.connected(); - } - 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); + return Mqtt_PubSubClient.connected(); + } 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); + } } - } - return false; -#endif + return false; + #endif } // Is called if there's a new MQTT-message for us -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); - - snprintf(Log_Buffer, Log_BufferLength, "%s: [Topic: %s] [Command: %s]", (char *)FPSTR(mqttMsgReceived), mqttTopic, receivedString); - Log_Println(Log_Buffer, LOGLEVEL_INFO); - - // Go to sleep? - 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) - { - char *_rfidId = x_strdup(receivedString); - xQueueSend(gRfidCardQueue, &_rfidId, 0); - //free(_rfidId); - } - // Loudness to change? - 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 - Log_Println((char *)FPSTR(modificatorNotallowedWhenIdle), LOGLEVEL_INFO); - publishMqtt((char *)FPSTR(topicSleepState), 0, false); - System_IndicateError(); - return; +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); + + snprintf(Log_Buffer, Log_BufferLength, "%s: [Topic: %s] [Command: %s]", (char *) FPSTR(mqttMsgReceived), mqttTopic, receivedString); + Log_Println(Log_Buffer, LOGLEVEL_INFO); + + // Go to sleep? + if (strcmp_P(topic, topicSleepCmnd) == 0) { + if ((strcmp(receivedString, "OFF") == 0) || (strcmp(receivedString, "0") == 0)) { + System_RequestSleep(); + } } - if (strcmp(receivedString, "EOP") == 0) - { - gPlayProperties.sleepAfterPlaylist = true; - Log_Println((char *)FPSTR(sleepTimerEOP), LOGLEVEL_NOTICE); - System_IndicateOk(); - return; + // New track to play? Take RFID-ID as input + else if (strcmp_P(topic, topicRfidCmnd) == 0) { + char *_rfidId = x_strdup(receivedString); + xQueueSend(gRfidCardQueue, _rfidId, 0); } - else if (strcmp(receivedString, "EOT") == 0) - { - gPlayProperties.sleepAfterCurrentTrack = true; - Log_Println((char *)FPSTR(sleepTimerEOT), LOGLEVEL_NOTICE); - System_IndicateOk(); - return; + // Loudness to change? + else if (strcmp_P(topic, topicLoudnessCmnd) == 0) { + unsigned long vol = strtoul(receivedString, NULL, 10); + AudioPlayer_VolumeToQueueSender(vol, true); } - else if (strcmp(receivedString, "EO5T") == 0) - { - if ((gPlayProperties.numberOfTracks - 1) >= (gPlayProperties.currentTrackNumber + 5)) - { - gPlayProperties.playUntilTrackNumber = gPlayProperties.currentTrackNumber + 5; + // 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 + Log_Println((char *) FPSTR(modificatorNotallowedWhenIdle), LOGLEVEL_INFO); + publishMqtt((char *) FPSTR(topicSleepState), 0, false); + System_IndicateError(); + return; } - else - { + if (strcmp(receivedString, "EOP") == 0) { gPlayProperties.sleepAfterPlaylist = true; - } - Log_Println((char *)FPSTR(sleepTimerEO5), LOGLEVEL_NOTICE); - System_IndicateOk(); - return; - } - else if (strcmp(receivedString, "0") == 0) - { - if (System_IsSleepTimerEnabled()) - { - System_DisableSleepTimer(); - Log_Println((char *)FPSTR(sleepTimerStop), LOGLEVEL_NOTICE); + Log_Println((char *) FPSTR(sleepTimerEOP), LOGLEVEL_NOTICE); System_IndicateOk(); - publishMqtt((char *)FPSTR(topicSleepState), 0, false); return; - } - else - { - Log_Println((char *)FPSTR(sleepTimerAlreadyStopped), LOGLEVEL_INFO); - System_IndicateError(); + } 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)) { + gPlayProperties.playUntilTrackNumber = gPlayProperties.currentTrackNumber + 5; + } else { + gPlayProperties.sleepAfterPlaylist = true; + } + Log_Println((char *) FPSTR(sleepTimerEO5), LOGLEVEL_NOTICE); + System_IndicateOk(); + return; + } 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 { + Log_Println((char *) FPSTR(sleepTimerAlreadyStopped), LOGLEVEL_INFO); + System_IndicateError(); + return; + } } - } - System_SetSleepTimer((uint8_t)strtoul(receivedString, NULL, 10)); - snprintf(Log_Buffer, Log_BufferLength, "%s: %u Minute(n)", (char *)FPSTR(sleepTimerSetTo), System_GetSleepTimer()); - Log_Println(Log_Buffer, LOGLEVEL_NOTICE); - System_IndicateOk(); - - gPlayProperties.sleepAfterPlaylist = false; - gPlayProperties.sleepAfterCurrentTrack = false; - } - // Track-control (pause/play, stop, first, last, next, previous) - 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) - { - System_SetLockControls(false); - Log_Println((char *)FPSTR(allowButtons), LOGLEVEL_NOTICE); + System_SetSleepTimer((uint8_t)strtoul(receivedString, NULL, 10)); + snprintf(Log_Buffer, Log_BufferLength, "%s: %u Minute(n)", (char *) FPSTR(sleepTimerSetTo), System_GetSleepTimer()); + Log_Println(Log_Buffer, LOGLEVEL_NOTICE); System_IndicateOk(); + + gPlayProperties.sleepAfterPlaylist = false; + gPlayProperties.sleepAfterCurrentTrack = false; } - else if (strcmp(receivedString, "ON") == 0) - { - System_SetLockControls(true); - Log_Println((char *)FPSTR(lockButtons), LOGLEVEL_NOTICE); - System_IndicateOk(); + // Track-control (pause/play, stop, first, last, next, previous) + else if (strcmp_P(topic, topicTrackControlCmnd) == 0) { + uint8_t controlCommand = strtoul(receivedString, NULL, 10); + AudioPlayer_TrackControlToQueueSender(controlCommand); } - } - - // Check if playmode should be adjusted - 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) - { - snprintf(rBuf, 2, "%u", AudioPlayer_GetRepeatMode()); - publishMqtt((char *)FPSTR(topicRepeatModeState), rBuf, false); - Log_Println((char *)FPSTR(noPlaylistNotAllowedMqtt), LOGLEVEL_ERROR); - System_IndicateError(); - } - else - { - switch (repeatMode) - { - case NO_REPEAT: - gPlayProperties.repeatCurrentTrack = false; - gPlayProperties.repeatPlaylist = false; - snprintf(rBuf, 2, "%u", AudioPlayer_GetRepeatMode()); - publishMqtt((char *)FPSTR(topicRepeatModeState), rBuf, false); - Log_Println((char *)FPSTR(modeRepeatNone), LOGLEVEL_INFO); - System_IndicateOk(); - break; - case TRACK: - gPlayProperties.repeatCurrentTrack = true; - gPlayProperties.repeatPlaylist = false; - snprintf(rBuf, 2, "%u", AudioPlayer_GetRepeatMode()); - publishMqtt((char *)FPSTR(topicRepeatModeState), rBuf, false); - Log_Println((char *)FPSTR(modeRepeatTrack), LOGLEVEL_INFO); - System_IndicateOk(); - break; - - case PLAYLIST: - gPlayProperties.repeatCurrentTrack = false; - gPlayProperties.repeatPlaylist = true; - snprintf(rBuf, 2, "%u", AudioPlayer_GetRepeatMode()); - publishMqtt((char *)FPSTR(topicRepeatModeState), rBuf, false); - Log_Println((char *)FPSTR(modeRepeatPlaylist), LOGLEVEL_INFO); - System_IndicateOk(); - break; + // Check if controls should be locked + 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) { + System_SetLockControls(true); + Log_Println((char *) FPSTR(lockButtons), LOGLEVEL_NOTICE); + System_IndicateOk(); + } + } - case TRACK_N_PLAYLIST: - gPlayProperties.repeatCurrentTrack = true; - gPlayProperties.repeatPlaylist = true; + // Check if playmode should be adjusted + 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) { snprintf(rBuf, 2, "%u", AudioPlayer_GetRepeatMode()); - publishMqtt((char *)FPSTR(topicRepeatModeState), rBuf, false); - Log_Println((char *)FPSTR(modeRepeatTracknPlaylist), LOGLEVEL_INFO); - System_IndicateOk(); - break; - - default: + publishMqtt((char *) FPSTR(topicRepeatModeState), rBuf, false); + Log_Println((char *) FPSTR(noPlaylistNotAllowedMqtt), LOGLEVEL_ERROR); System_IndicateError(); - snprintf(rBuf, 2, "%u", AudioPlayer_GetRepeatMode()); - publishMqtt((char *)FPSTR(topicRepeatModeState), rBuf, false); - break; + } else { + switch (repeatMode) { + case NO_REPEAT: + gPlayProperties.repeatCurrentTrack = false; + gPlayProperties.repeatPlaylist = false; + snprintf(rBuf, 2, "%u", AudioPlayer_GetRepeatMode()); + publishMqtt((char *) FPSTR(topicRepeatModeState), rBuf, false); + Log_Println((char *) FPSTR(modeRepeatNone), LOGLEVEL_INFO); + System_IndicateOk(); + break; + + case TRACK: + gPlayProperties.repeatCurrentTrack = true; + gPlayProperties.repeatPlaylist = false; + snprintf(rBuf, 2, "%u", AudioPlayer_GetRepeatMode()); + publishMqtt((char *) FPSTR(topicRepeatModeState), rBuf, false); + Log_Println((char *) FPSTR(modeRepeatTrack), LOGLEVEL_INFO); + System_IndicateOk(); + break; + + case PLAYLIST: + gPlayProperties.repeatCurrentTrack = false; + gPlayProperties.repeatPlaylist = true; + snprintf(rBuf, 2, "%u", AudioPlayer_GetRepeatMode()); + publishMqtt((char *) FPSTR(topicRepeatModeState), rBuf, false); + Log_Println((char *) FPSTR(modeRepeatPlaylist), LOGLEVEL_INFO); + System_IndicateOk(); + break; + + case TRACK_N_PLAYLIST: + gPlayProperties.repeatCurrentTrack = true; + gPlayProperties.repeatPlaylist = true; + snprintf(rBuf, 2, "%u", AudioPlayer_GetRepeatMode()); + publishMqtt((char *) FPSTR(topicRepeatModeState), rBuf, false); + Log_Println((char *) FPSTR(modeRepeatTracknPlaylist), LOGLEVEL_INFO); + System_IndicateOk(); + break; + + default: + System_IndicateError(); + snprintf(rBuf, 2, "%u", AudioPlayer_GetRepeatMode()); + publishMqtt((char *) FPSTR(topicRepeatModeState), rBuf, false); + break; + } } } } - } - - // Check if LEDs should be dimmed - else if (strcmp_P(topic, topicLedBrightnessCmnd) == 0) - { - Led_SetBrightness(strtoul(receivedString, NULL, 10)); - } - - // Requested something that isn't specified? - else - { - snprintf(Log_Buffer, Log_BufferLength, "%s: %s", (char *)FPSTR(noValidTopic), topic); - Log_Println(Log_Buffer, LOGLEVEL_ERROR); - System_IndicateError(); - } - - free(receivedString); - free(mqttTopic); -#endif + + // Check if LEDs should be dimmed + else if (strcmp_P(topic, topicLedBrightnessCmnd) == 0) { + Led_SetBrightness(strtoul(receivedString, NULL, 10)); + } + + // Requested something that isn't specified? + else { + snprintf(Log_Buffer, Log_BufferLength, "%s: %s", (char *) FPSTR(noValidTopic), topic); + Log_Println(Log_Buffer, LOGLEVEL_ERROR); + System_IndicateError(); + } + + free(receivedString); + free(mqttTopic); + #endif } diff --git a/src/Port.cpp b/src/Port.cpp index 969208e..a676c7b 100644 --- a/src/Port.cpp +++ b/src/Port.cpp @@ -4,74 +4,61 @@ #include "Port.h" #ifdef PORT_EXPANDER_ENABLE -extern TwoWire i2cBusTwo; + extern TwoWire i2cBusTwo; -uint8_t Port_ExpanderPorts[portsToRead]; -bool Port_ExpanderHandler(void); + uint8_t Port_ExpanderPorts[portsToRead]; + bool Port_ExpanderHandler(void); #endif -void Port_Init(void) -{ +void Port_Init(void) { } -void Port_Cyclic(void) -{ -#ifdef PORT_EXPANDER_ENABLE - Port_ExpanderHandler(); -#endif +void Port_Cyclic(void) { + #ifdef PORT_EXPANDER_ENABLE + Port_ExpanderHandler(); + #endif } // 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) - { - case 0 ... 39: // GPIO - return digitalRead(_channel); +bool Port_Read(const uint8_t _channel) { + switch (_channel) { + case 0 ... 39: // GPIO + return digitalRead(_channel); -#ifdef PORT_EXPANDER_ENABLE - case 100 ... 107: // Port-expander (port 0) - return (Port_ExpanderPorts[0] & (1 << (_channel - 100))); // Remove offset 100 (return false if pressed) + #ifdef PORT_EXPANDER_ENABLE + case 100 ... 107: // Port-expander (port 0) + 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 - return (Port_ExpanderPorts[1] & (1 << (_channel - 108))); // Remove offset 100 + 8 (return false if pressed) - } - else - { - return true; - } + case 108 ... 115: // Port-expander (port 1) + 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 { + return true; + } + #endif -#endif - - default: // Everything else (doesn't make sense at all) isn't supposed to be pressed - return true; + default: // Everything else (doesn't make sense at all) isn't supposed to be pressed + return true; } } #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() -{ - i2cBusTwo.beginTransmission(expanderI2cAddress); - 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 + // 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() { + i2cBusTwo.beginTransmission(expanderI2cAddress); + 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()) - { - Port_ExpanderPorts[i] = i2cBusTwo.read(); - } - else - { - return false; + if (i2cBusTwo.available()) { + Port_ExpanderPorts[i] = i2cBusTwo.read(); + } else { + return false; + } } + return false; } - return false; -} #endif \ No newline at end of file diff --git a/src/Queues.cpp b/src/Queues.cpp index e8b4262..1c7a81d 100644 --- a/src/Queues.cpp +++ b/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) - { - Log_Println((char *)FPSTR(unableToCreateVolQ), LOGLEVEL_ERROR); + if (gVolumeQueue == NULL) { + Log_Println((char *) FPSTR(unableToCreateVolQ), LOGLEVEL_ERROR); } gRfidCardQueue = xQueueCreate(1, cardIdStringSize); - if (gRfidCardQueue == NULL) - { - Log_Println((char *)FPSTR(unableToCreateRfidQ), LOGLEVEL_ERROR); + if (gRfidCardQueue == NULL) { + Log_Println((char *) FPSTR(unableToCreateRfidQ), LOGLEVEL_ERROR); } gTrackControlQueue = xQueueCreate(1, sizeof(uint8_t)); - if (gTrackControlQueue == NULL) - { - Log_Println((char *)FPSTR(unableToCreateMgmtQ), LOGLEVEL_ERROR); + if (gTrackControlQueue == NULL) { + Log_Println((char *) FPSTR(unableToCreateMgmtQ), LOGLEVEL_ERROR); } char **playlistArray; gTrackQueue = xQueueCreate(1, sizeof(playlistArray)); - if (gTrackQueue == NULL) - { - Log_Println((char *)FPSTR(unableToCreatePlayQ), LOGLEVEL_ERROR); + if (gTrackQueue == NULL) { + Log_Println((char *) FPSTR(unableToCreatePlayQ), LOGLEVEL_ERROR); } } diff --git a/src/RfidCommon.cpp b/src/RfidCommon.cpp index 307520f..f13e837 100644 --- a/src/RfidCommon.cpp +++ b/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,19 +24,17 @@ 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); - snprintf(Log_Buffer, Log_BufferLength, "%s: %s", (char *)FPSTR(rfidTagReceived), gCurrentRfidTagId); + snprintf(Log_Buffer, Log_BufferLength, "%s: %s", (char *) FPSTR(rfidTagReceived), gCurrentRfidTagId); Web_SendWebsocketData(0, 10); // Push new rfidTagId to all websocket-clients Log_Println(Log_Buffer, LOGLEVEL_INFO); String s = gPrefsRfid.getString(gCurrentRfidTagId, "-1"); // Try to lookup rfidId in NVS - if (!s.compareTo("-1")) - { - Log_Println((char *)FPSTR(rfidTagUnknownInNvs), LOGLEVEL_ERROR); + if (!s.compareTo("-1")) { + Log_Println((char *) FPSTR(rfidTagUnknownInNvs), LOGLEVEL_ERROR); System_IndicateError(); return; } @@ -45,54 +42,39 @@ 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) - { - Log_Println((char *)FPSTR(errorOccuredNvs), LOGLEVEL_ERROR); + 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 - { -#ifdef MQTT_ENABLE - publishMqtt((char *)FPSTR(topicRfidState), gCurrentRfidTagId, false); -#endif + } 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) - { - System_SetOperationMode(OPMODE_NORMAL); - } -#endif + #ifdef BLUETOOTH_ENABLE + // if music rfid was read, go back to normal mode + if (System_GetOperationMode() == OPMODE_BLUETOOTH) { + System_SetOperationMode(OPMODE_NORMAL); + } + #endif AudioPlayer_TrackQueueDispatcher(_file, _lastPlayPos, _playMode, _trackLastPlayed); } diff --git a/src/RfidMfrc522.cpp b/src/RfidMfrc522.cpp index 9b2f2ed..f67af77 100644 --- a/src/RfidMfrc522.cpp +++ b/src/RfidMfrc522.cpp @@ -7,95 +7,84 @@ #include "System.h" #if defined RFID_READER_TYPE_MFRC522_SPI || defined RFID_READER_TYPE_MFRC522_I2C + #ifdef RFID_READER_TYPE_MFRC522_SPI + #include + #endif + #if defined(RFID_READER_TYPE_MFRC522_I2C) || defined(PORT_EXPANDER_ENABLE) + #include "Wire.h" + #endif + #ifdef RFID_READER_TYPE_MFRC522_I2C + #include + #endif + + 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) { + #ifdef RFID_READER_TYPE_MFRC522_SPI + SPI.begin(RFID_SCK, RFID_MISO, RFID_MOSI, RFID_CS); + SPI.setFrequency(1000000); + #endif + + // Init RC522 Card-Reader + #if defined(RFID_READER_TYPE_MFRC522_I2C) || defined(RFID_READER_TYPE_MFRC522_SPI) + mfrc522.PCD_Init(); + mfrc522.PCD_SetAntennaGain(rfidGain); + delay(50); + Log_Println((char *) FPSTR(rfidScannerReady), LOGLEVEL_DEBUG); + #endif + } -#ifdef RFID_READER_TYPE_MFRC522_SPI -#include -#endif -#if defined(RFID_READER_TYPE_MFRC522_I2C) || defined(PORT_EXPANDER_ENABLE) -#include "Wire.h" -#endif -#ifdef RFID_READER_TYPE_MFRC522_I2C -#include -#endif - -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) -{ -#ifdef RFID_READER_TYPE_MFRC522_SPI - SPI.begin(RFID_SCK, RFID_MISO, RFID_MOSI, RFID_CS); - SPI.setFrequency(1000000); -#endif - - // Init RC522 Card-Reader -#if defined(RFID_READER_TYPE_MFRC522_I2C) || defined(RFID_READER_TYPE_MFRC522_SPI) - mfrc522.PCD_Init(); - mfrc522.PCD_SetAntennaGain(rfidGain); - delay(50); - Log_Println((char *)FPSTR(rfidScannerReady), LOGLEVEL_DEBUG); -#endif -} - -void Rfid_Cyclic(void) -{ - byte cardId[cardIdSize]; - String cardIdString; - - 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()) - { - return; - } + void Rfid_Cyclic(void) { + byte cardId[cardIdSize]; + String cardIdString; - // Select one of the cards - if (!mfrc522.PICC_ReadCardSerial()) - { - return; - } + 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. - //mfrc522.PICC_DumpToSerial(&(mfrc522.uid)); - mfrc522.PICC_HaltA(); - mfrc522.PCD_StopCrypto1(); + if (!mfrc522.PICC_IsNewCardPresent()) { + return; + } - memcpy(cardId, mfrc522.uid.uidByte, cardIdSize); + // Select one of the cards + if (!mfrc522.PICC_ReadCardSerial()) { + return; + } - Log_Print((char *)FPSTR(rfidTagDetected), LOGLEVEL_NOTICE); - 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); - } + //mfrc522.PICC_DumpToSerial(&(mfrc522.uid)); + mfrc522.PICC_HaltA(); + mfrc522.PCD_StopCrypto1(); - for (uint8_t i = 0u; i < cardIdSize; i++) - { - char num[4]; - snprintf(num, sizeof(num), "%03d", cardId[i]); - cardIdString += num; - } + memcpy(cardId, mfrc522.uid.uidByte, cardIdSize); - xQueueSend(gRfidCardQueue, cardIdString.c_str(), 0); + Log_Print((char *) FPSTR(rfidTagDetected), LOGLEVEL_NOTICE); + 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++) { + char num[4]; + snprintf(num, sizeof(num), "%03d", cardId[i]); + cardIdString += num; + } + + xQueueSend(gRfidCardQueue, cardIdString.c_str(), 0); + } } -} -void Rfid_Exit(void) -{ -} + void Rfid_Exit(void) { + } -void Rfid_WakeupCheck(void) -{ -} + void Rfid_WakeupCheck(void) { + } #endif \ No newline at end of file diff --git a/src/RfidPn5180.cpp b/src/RfidPn5180.cpp index ac8426f..cd94798 100644 --- a/src/RfidPn5180.cpp +++ b/src/RfidPn5180.cpp @@ -9,9 +9,9 @@ #include "System.h" #ifdef RFID_READER_TYPE_PN5180 -#include -#include -#include + #include + #include + #include #endif #define RFID_PN5180_STATE_INIT 0u @@ -28,235 +28,198 @@ 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) -{ -#ifdef PN5180_ENABLE_LPCD - // disable pin hold from deep sleep - gpio_deep_sleep_hold_dis(); - gpio_hold_dis(gpio_num_t(RFID_CS)); // NSS - gpio_hold_dis(gpio_num_t(RFID_RST)); // RST -#endif - - // Create task for rfid - xTaskCreatePinnedToCore( - Rfid_Task, /* Function to implement the task */ - "Rfid_Task", /* Name of the task */ - 1500, /* Stack size in words */ - NULL, /* Task input parameter */ - 1, /* Priority of the task */ - NULL, /* Task handle. */ - 0 /* Core where the task should run */ - ); -} - -void Rfid_Cyclic(void) -{ - // Implemented via task -} - -void Rfid_Task(void *parameter) -{ - for (;;) - { - Rfid_Read(); - vTaskDelay(5u); + static void Rfid_Task(void *parameter); + static void Rfid_Read(void); + + void Rfid_Init(void) { + #ifdef PN5180_ENABLE_LPCD + // disable pin hold from deep sleep + gpio_deep_sleep_hold_dis(); + gpio_hold_dis(gpio_num_t(RFID_CS)); // NSS + gpio_hold_dis(gpio_num_t(RFID_RST)); // RST + #endif + + // Create task for rfid + xTaskCreatePinnedToCore( + Rfid_Task, /* Function to implement the task */ + "Rfid_Task", /* Name of the task */ + 1500, /* Stack size in words */ + NULL, /* Task input parameter */ + 1, /* Priority of the task */ + NULL, /* Task handle. */ + 0 /* Core where the task should run */ + ); } -} - -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; - byte cardId[cardIdSize], lastCardId[cardIdSize]; - uint8_t uid[10]; - String cardIdString; - bool cardReceived = false; - - if (RFID_PN5180_STATE_INIT == stateMachine) - { - nfc14443.begin(); - nfc14443.reset(); - // show PN5180 reader version - uint8_t firmwareVersion[2]; - nfc14443.readEEprom(FIRMWARE_VERSION, firmwareVersion, sizeof(firmwareVersion)); - Serial.print(F("Firmware version=")); - Serial.print(firmwareVersion[1]); - Serial.print("."); - Serial.println(firmwareVersion[0]); - // activate RF field - delay(4); - Log_Println((char *)FPSTR(rfidScannerReady), LOGLEVEL_DEBUG); + void Rfid_Cyclic(void) { + // Implemented via task } - // 1. check for an ISO-14443 card - else if (RFID_PN5180_NFC14443_STATE_RESET == stateMachine) - { - nfc14443.reset(); - } - else if (RFID_PN5180_NFC14443_STATE_SETUPRF == stateMachine) - { - nfc14443.setupRF(); - } - 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) - { - nfc15693.reset(); - } - else if (RFID_PN5180_NFC15693_STATE_SETUPRF == stateMachine) - { - nfc15693.setupRF(); - } - 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) - { - Serial.println(F("disabling privacy-mode successful")); + + void Rfid_Task(void *parameter) { + for (;;) { + Rfid_Read(); + vTaskDelay(5u); } } - else if (RFID_PN5180_NFC15693_STATE_GETINVENTORY == stateMachine) - { - // try to read ISO15693 inventory - ISO15693ErrorCode rc = nfc15693.getInventory(uid); - if (rc == ISO15693_EC_OK) - { - cardReceived = true; + + 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; + byte cardId[cardIdSize], lastCardId[cardIdSize]; + uint8_t uid[10]; + String cardIdString; + bool cardReceived = false; + + if (RFID_PN5180_STATE_INIT == stateMachine) { + nfc14443.begin(); + nfc14443.reset(); + // show PN5180 reader version + uint8_t firmwareVersion[2]; + nfc14443.readEEprom(FIRMWARE_VERSION, firmwareVersion, sizeof(firmwareVersion)); + Serial.print(F("Firmware version=")); + Serial.print(firmwareVersion[1]); + Serial.print("."); + Serial.println(firmwareVersion[0]); + + // 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) { + nfc14443.reset(); + } else if (RFID_PN5180_NFC14443_STATE_SETUPRF == stateMachine) { + nfc14443.setupRF(); + } 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) { + nfc15693.reset(); + } else if (RFID_PN5180_NFC15693_STATE_SETUPRF == stateMachine) { + nfc15693.setupRF(); + } 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) { + Serial.println(F("disabling privacy-mode successful")); + } + } else if (RFID_PN5180_NFC15693_STATE_GETINVENTORY == stateMachine) { + // try to read ISO15693 inventory + ISO15693ErrorCode rc = nfc15693.getInventory(uid); + if (rc == ISO15693_EC_OK) { + cardReceived = true; + } } - } - // send card to queue - if (cardReceived) - { - memcpy(cardId, uid, cardIdSize); + // send card to queue + if (cardReceived) { + memcpy(cardId, uid, cardIdSize); - // check for different card id - if (memcmp((const void *)cardId, (const void *)lastCardId, sizeof(cardId)) == 0) - { - // reset state machine - stateMachine = RFID_PN5180_NFC14443_STATE_RESET; - return; - } + // check for different card id + if (memcmp((const void *)cardId, (const void *)lastCardId, sizeof(cardId)) == 0) { + // reset state machine + stateMachine = RFID_PN5180_NFC14443_STATE_RESET; + return; + } - memcpy(lastCardId, cardId, cardIdSize); + memcpy(lastCardId, cardId, cardIdSize); - Log_Print((char *)FPSTR(rfidTagDetected), LOGLEVEL_NOTICE); - 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); - } + Log_Print((char *) FPSTR(rfidTagDetected), LOGLEVEL_NOTICE); + 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++) - { - char num[4]; - snprintf(num, sizeof(num), "%03d", cardId[i]); - cardIdString += num; - } + for (uint8_t i = 0u; i < cardIdSize; i++) { + char num[4]; + snprintf(num, sizeof(num), "%03d", cardId[i]); + cardIdString += num; + } - xQueueSend(gRfidCardQueue, cardIdString.c_str(), 0); - } + xQueueSend(gRfidCardQueue, cardIdString.c_str(), 0); + } - stateMachine++; + stateMachine++; - if (stateMachine > RFID_PN5180_NFC15693_STATE_GETINVENTORY) - { - stateMachine = RFID_PN5180_NFC14443_STATE_RESET; + if (stateMachine > RFID_PN5180_NFC15693_STATE_GETINVENTORY) { + stateMachine = RFID_PN5180_NFC14443_STATE_RESET; + } } -} -void Rfid_Exit(void) -{ -// goto low power card detection mode -#ifdef PN5180_ENABLE_LPCD - static PN5180 nfc(RFID_CS, RFID_BUSY, RFID_RST); - nfc.begin(); - // show PN5180 reader version - uint8_t firmwareVersion[2]; - nfc.readEEprom(FIRMWARE_VERSION, firmwareVersion, sizeof(firmwareVersion)); - Serial.print(F("Firmware version=")); - Serial.print(firmwareVersion[1]); - Serial.print("."); - 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) - { - Serial.println(F("This PN5180 firmware does not work with LPCD! use firmware >= 4.0")); - return; - } - Serial.println(F("prepare low power card detection...")); - nfc.prepareLPCD(); - nfc.clearIRQStatus(0xffffffff); - Serial.print(F("PN5180 IRQ PIN: ")); - 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)) - { - 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); - // freeze pin states in deep sleep - gpio_hold_en(gpio_num_t(RFID_CS)); // CS/NSS - gpio_hold_en(gpio_num_t(RFID_RST)); // RST - gpio_deep_sleep_hold_en(); + void Rfid_Exit(void) { + // goto low power card detection mode + #ifdef PN5180_ENABLE_LPCD + static PN5180 nfc(RFID_CS, RFID_BUSY, RFID_RST); + nfc.begin(); + // show PN5180 reader version + uint8_t firmwareVersion[2]; + nfc.readEEprom(FIRMWARE_VERSION, firmwareVersion, sizeof(firmwareVersion)); + Serial.print(F("Firmware version=")); + Serial.print(firmwareVersion[1]); + Serial.print("."); + 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) { + Serial.println(F("This PN5180 firmware does not work with LPCD! use firmware >= 4.0")); + return; + } + Serial.println(F("prepare low power card detection...")); + nfc.prepareLPCD(); + nfc.clearIRQStatus(0xffffffff); + Serial.print(F("PN5180 IRQ PIN: ")); + 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)) { + 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); + // freeze pin states in deep sleep + 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 { + Serial.println(F("switchToLPCD failed")); + } + #endif } - 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) -{ -#ifdef PN5180_ENABLE_LPCD - static PN5180ISO14443 nfc14443(RFID_CS, RFID_BUSY, RFID_RST); - nfc14443.begin(); - nfc14443.reset(); - nfc14443.setupRF(); - 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)) - { - 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); - // freeze pin states in deep sleep - gpio_hold_en(gpio_num_t(RFID_CS)); // CS/NSS - gpio_hold_en(gpio_num_t(RFID_RST)); // RST - gpio_deep_sleep_hold_en(); - Log_Println((char *)FPSTR(wakeUpRfidNoIso14443), LOGLEVEL_ERROR); - esp_deep_sleep_start(); - } - else - { - Serial.println(F("switchToLPCD failed")); - } + // wake up from LPCD, check card is present. This works only for ISO-14443 compatible cards + 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()) { + 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)) { + 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); + // freeze pin states in deep sleep + gpio_hold_en(gpio_num_t(RFID_CS)); // CS/NSS + gpio_hold_en(gpio_num_t(RFID_RST)); // RST + gpio_deep_sleep_hold_en(); + Log_Println((char *) FPSTR(wakeUpRfidNoIso14443), LOGLEVEL_ERROR); + esp_deep_sleep_start(); + } else { + Serial.println(F("switchToLPCD failed")); + } + } + #endif } -#endif -} #endif diff --git a/src/RotaryEncoder.cpp b/src/RotaryEncoder.cpp index 0346538..8cfaf1c 100644 --- a/src/RotaryEncoder.cpp +++ b/src/RotaryEncoder.cpp @@ -11,68 +11,59 @@ // Rotary encoder-configuration #ifdef USEROTARY_ENABLE -ESP32Encoder encoder; -// Rotary encoder-helper -int32_t lastEncoderValue; -int32_t currentEncoderValue; -int32_t lastVolume = -1; // Don't change -1 as initial-value! + ESP32Encoder encoder; + // Rotary encoder-helper + int32_t lastEncoderValue; + 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); - encoder.clearCount(); - encoder.setCount(AudioPlayer_GetInitVolume() * 2); // Ganzes Raster ist immer +2, daher initiale Lautstärke mit 2 multiplizieren -#endif -} - -void RotaryEncoder_Readjust(void) -{ -#ifdef USEROTARY_ENABLE - encoder.clearCount(); - encoder.setCount(AudioPlayer_GetCurrentVolume() * 2); -#endif + #ifdef USEROTARY_ENABLE + encoder.attachHalfQuad(DREHENCODER_CLK, DREHENCODER_DT); + encoder.clearCount(); + encoder.setCount(AudioPlayer_GetInitVolume() * 2); // Ganzes Raster ist immer +2, daher initiale Lautstärke mit 2 multiplizieren + #endif } -// Handles volume directed by rotary encoder -void RotaryEncoder_Cyclic(void) -{ -#ifdef USEROTARY_ENABLE - if (System_AreControlsLocked()) - { +void RotaryEncoder_Readjust(void) { + #ifdef USEROTARY_ENABLE encoder.clearCount(); encoder.setCount(AudioPlayer_GetCurrentVolume() * 2); - return; - } + #endif +} - 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)) - { - System_UpdateActivityTimer(); // Set inactive back if rotary encoder was used - 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()) - { +// Handles volume directed by rotary encoder +void RotaryEncoder_Cyclic(void) { + #ifdef USEROTARY_ENABLE + if (System_AreControlsLocked()) { encoder.clearCount(); - encoder.setCount(AudioPlayer_GetMinVolume()); - Log_Println((char *)FPSTR(minLoudnessReached), LOGLEVEL_INFO); - currentEncoderValue = encoder.getCount(); + encoder.setCount(AudioPlayer_GetCurrentVolume() * 2); + return; } - lastEncoderValue = currentEncoderValue; - AudioPlayer_SetCurrentVolume(lastEncoderValue / 2u); - if (AudioPlayer_GetCurrentVolume() != lastVolume) - { - lastVolume = AudioPlayer_GetCurrentVolume(); - AudioPlayer_VolumeToQueueSender(AudioPlayer_GetCurrentVolume(), false); + + 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)) { + System_UpdateActivityTimer(); // Set inactive back if rotary encoder was used + 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()) { + encoder.clearCount(); + encoder.setCount(AudioPlayer_GetMinVolume()); + Log_Println((char *) FPSTR(minLoudnessReached), LOGLEVEL_INFO); + currentEncoderValue = encoder.getCount(); + } + lastEncoderValue = currentEncoderValue; + AudioPlayer_SetCurrentVolume(lastEncoderValue / 2u); + if (AudioPlayer_GetCurrentVolume() != lastVolume) { + lastVolume = AudioPlayer_GetCurrentVolume(); + AudioPlayer_VolumeToQueueSender(AudioPlayer_GetCurrentVolume(), false); + } } - } -#endif + #endif } \ No newline at end of file diff --git a/src/SdCard.cpp b/src/SdCard.cpp index c5df3fe..844eb7d 100644 --- a/src/SdCard.cpp +++ b/src/SdCard.cpp @@ -8,78 +8,69 @@ #include "System.h" #ifdef SD_MMC_1BIT_MODE -fs::FS gFSystem = (fs::FS)SD_MMC; + fs::FS gFSystem = (fs::FS)SD_MMC; #else -SPIClass spiSD(HSPI); -fs::FS gFSystem = (fs::FS)SD; + SPIClass spiSD(HSPI); + fs::FS gFSystem = (fs::FS)SD; #endif -void SdCard_Init(void) -{ -#ifndef SINGLE_SPI_ENABLE -#ifdef SD_MMC_1BIT_MODE - pinMode(2, INPUT_PULLUP); - 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)) - { -#endif -#else -#ifdef SD_MMC_1BIT_MODE - pinMode(2, INPUT_PULLUP); - while (!SD_MMC.begin("/sdcard", true)) - { -#else - 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) - { - Log_Println((char *)FPSTR(sdBootFailedDeepsleep), LOGLEVEL_ERROR); - esp_deep_sleep_start(); - } -#endif - } +void SdCard_Init(void) { + #ifndef SINGLE_SPI_ENABLE + #ifdef SD_MMC_1BIT_MODE + pinMode(2, INPUT_PULLUP); + 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)) { + #endif + #else + #ifdef SD_MMC_1BIT_MODE + pinMode(2, INPUT_PULLUP); + while (!SD_MMC.begin("/sdcard", true)) { + #else + 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) { + Log_Println((char *) FPSTR(sdBootFailedDeepsleep), LOGLEVEL_ERROR); + esp_deep_sleep_start(); + } + #endif + } } -void SdCard_Exit(void) -{ +void SdCard_Exit(void) { // SD card goto idle mode -#ifdef SD_MMC_1BIT_MODE - SD_MMC.end(); -#endif + #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); - cardType = SD_MMC.cardType(); -#else - Log_Println((char *)FPSTR(sdMountedSpiMode), LOGLEVEL_NOTICE); - cardType = SD.cardType(); -#endif - return cardType; + #ifdef SD_MMC_1BIT_MODE + Log_Println((char *) FPSTR(sdMountedMmc1BitMode), LOGLEVEL_NOTICE); + cardType = SD_MMC.cardType(); + #else + Log_Println((char *) FPSTR(sdMountedSpiMode), LOGLEVEL_NOTICE); + cardType = SD.cardType(); + #endif + return cardType; } // 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 . - return (!startsWith(subst, (char *)"/.")) && + return (!startsWith(subst, (char *) "/.")) && (endsWith(_fileItem, ".mp3") || endsWith(_fileItem, ".MP3") || endsWith(_fileItem, ".aac") || endsWith(_fileItem, ".AAC") || endsWith(_fileItem, ".m3u") || endsWith(_fileItem, ".M3U") || @@ -91,46 +82,41 @@ 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]; File fileOrDirectory = gFSystem.open(fileName); - snprintf(Log_Buffer, Log_BufferLength, "%s: %u", (char *)FPSTR(freeMemory), ESP.getFreeHeap()); + 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 - Log_Println((char *)FPSTR(releaseMemoryOfOldPlaylist), LOGLEVEL_DEBUG); + 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)); - snprintf(Log_Buffer, Log_BufferLength, "%s: %u", (char *)FPSTR(freeMemoryAfterFree), ESP.getFreeHeap()); + snprintf(Log_Buffer, Log_BufferLength, "%s: %u", (char *) FPSTR(freeMemoryAfterFree), ESP.getFreeHeap()); Log_Println(Log_Buffer, LOGLEVEL_DEBUG); } - if (!fileOrDirectory) - { - Log_Println((char *)FPSTR(dirOrFileDoesNotExist), LOGLEVEL_ERROR); + if (!fileOrDirectory) { + Log_Println((char *) FPSTR(dirOrFileDoesNotExist), LOGLEVEL_ERROR); return NULL; } // File-mode - if (!fileOrDirectory.isDirectory()) - { - files = (char **)x_malloc(sizeof(char *) * 2); - if (files == NULL) - { - Log_Println((char *)FPSTR(unableToAllocateMemForPlaylist), LOGLEVEL_ERROR); + if (!fileOrDirectory.isDirectory()) { + files = (char **) x_malloc(sizeof(char *) * 2); + if (files == NULL) { + Log_Println((char *) FPSTR(unableToAllocateMemForPlaylist), LOGLEVEL_ERROR); System_IndicateError(); return NULL; } - Log_Println((char *)FPSTR(fileModeDetected), LOGLEVEL_INFO); - strncpy(fileNameBuf, (char *)fileOrDirectory.name(), sizeof(fileNameBuf) / sizeof(fileNameBuf[0])); + Log_Println((char *) FPSTR(fileModeDetected), LOGLEVEL_INFO); + strncpy(fileNameBuf, (char *) fileOrDirectory.name(), sizeof(fileNameBuf) / sizeof(fileNameBuf[0])); if (fileValid(fileNameBuf)) { - files = (char **)x_malloc(sizeof(char *) * 2); + files = (char **) x_malloc(sizeof(char *) * 2); files[1] = x_strdup(fileNameBuf); } files[0] = x_strdup("1"); // Number of files is always 1 in file-mode @@ -141,41 +127,32 @@ 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)); + 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 - { - strncpy(fileNameBuf, (char *)fileItem.name(), sizeof(fileNameBuf) / sizeof(fileNameBuf[0])); + } 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) - { - serializedPlaylist = (char *)realloc(serializedPlaylist, ++allocCount * allocSize); - Log_Println((char *)FPSTR(reallocCalled), LOGLEVEL_DEBUG); - if (serializedPlaylist == NULL) - { - Log_Println((char *)FPSTR(unableToAllocateMemForLinearPlaylist), LOGLEVEL_ERROR); + if ((strlen(serializedPlaylist) + strlen(fileNameBuf) + 2) >= allocCount * allocSize) { + serializedPlaylist = (char *) realloc(serializedPlaylist, ++allocCount * allocSize); + Log_Println((char *) FPSTR(reallocCalled), LOGLEVEL_DEBUG); + if (serializedPlaylist == NULL) { + Log_Println((char *) FPSTR(unableToAllocateMemForLinearPlaylist), LOGLEVEL_ERROR); System_IndicateError(); return files; } @@ -188,20 +165,17 @@ 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++; } } // Alloc only necessary number of playlist-pointers - files = (char **)x_malloc(sizeof(char *) * cnt + 1); + files = (char **) x_malloc(sizeof(char *) * cnt + 1); - if (files == NULL) - { - Log_Println((char *)FPSTR(unableToAllocateMemForPlaylist), LOGLEVEL_ERROR); + if (files == NULL) { + Log_Println((char *) FPSTR(unableToAllocateMemForPlaylist), LOGLEVEL_ERROR); System_IndicateError(); free(serializedPlaylist); return NULL; @@ -211,24 +185,22 @@ 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); } free(serializedPlaylist); - files[0] = (char *)x_malloc(sizeof(char) * 5); + files[0] = (char *) x_malloc(sizeof(char) * 5); - if (files[0] == NULL) - { - Log_Println((char *)FPSTR(unableToAllocateMemForPlaylist), LOGLEVEL_ERROR); + if (files[0] == NULL) { + Log_Println((char *) FPSTR(unableToAllocateMemForPlaylist), LOGLEVEL_ERROR); System_IndicateError(); return NULL; } sprintf(files[0], "%u", cnt); - snprintf(Log_Buffer, Log_BufferLength, "%s: %d", (char *)FPSTR(numberOfValidFiles), cnt); + snprintf(Log_Buffer, Log_BufferLength, "%s: %d", (char *) FPSTR(numberOfValidFiles), cnt); Log_Println(Log_Buffer, LOGLEVEL_NOTICE); return ++files; // return ptr+1 (starting at 1st payload-item); ptr+0 contains number of items diff --git a/src/System.cpp b/src/System.cpp index 01cf5ce..4338f80 100644 --- a/src/System.cpp +++ b/src/System.cpp @@ -28,202 +28,165 @@ 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); - gPrefsRfid.begin((char *)FPSTR(prefsRfidNamespace)); - gPrefsSettings.begin((char *)FPSTR(prefsSettingsNamespace)); + gPrefsRfid.begin((char *) FPSTR(prefsRfidNamespace)); + gPrefsSettings.begin((char *) FPSTR(prefsSettingsNamespace)); // 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); + 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); + Log_Println((char *) FPSTR(wroteMaxInactivityToNvs), LOGLEVEL_ERROR); } 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 - { + Log_Println((char *) FPSTR(modificatorSleepd), LOGLEVEL_NOTICE); + publishMqtt((char *) FPSTR(topicLedBrightnessState), Led_GetBrightness(), false); + } else { System_SleepTimer = minutes; System_SleepTimerStartTimestamp = millis(); sleepTimerEnabled = true; Led_ResetToNightBrightness(); - Log_Println((char *)FPSTR(modificatorSleepTimer60), LOGLEVEL_NOTICE); - publishMqtt((char *)FPSTR(topicSleepTimerState), System_SleepTimer, false); - publishMqtt((char *)FPSTR(topicLedBrightnessState), Led_GetBrightness(), false); + Log_Println((char *) FPSTR(modificatorSleepTimer60), LOGLEVEL_NOTICE); + publishMqtt((char *) FPSTR(topicSleepTimerState), System_SleepTimer, false); + publishMqtt((char *) FPSTR(topicLedBrightnessState), Led_GetBrightness(), false); } 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) - { - Log_Println((char *)FPSTR(modificatorAllButtonsLocked), LOGLEVEL_NOTICE); - publishMqtt((char *)FPSTR(topicLockControlsState), "ON", false); + if (System_LockControls) { + Log_Println((char *) FPSTR(modificatorAllButtonsLocked), LOGLEVEL_NOTICE); + publishMqtt((char *) FPSTR(topicLockControlsState), "ON", false); System_IndicateOk(); - } - else - { - Log_Println((char *)FPSTR(modificatorAllButtonsUnlocked), LOGLEVEL_NOTICE); - publishMqtt((char *)FPSTR(topicLockControlsState), "OFF", false); + } 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))) - { - Log_Println((char *)FPSTR(goToSleepDueToIdle), LOGLEVEL_INFO); + 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)) - { - Log_Println((char *)FPSTR(goToSleepDueToTimer), LOGLEVEL_INFO); + } else if (System_SleepTimerStartTimestamp > 00) { + if (m - System_SleepTimerStartTimestamp >= (System_SleepTimer * 1000u * 60u)) { + Log_Println((char *) FPSTR(goToSleepDueToTimer), LOGLEVEL_INFO); System_RequestSleep(); } } } // 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; } System_Sleeping = true; - Log_Println((char *)FPSTR(goToSleepNow), LOGLEVEL_NOTICE); + Log_Println((char *) FPSTR(goToSleepNow), LOGLEVEL_NOTICE); Mqtt_Exit(); Led_Exit(); -#ifdef USE_LAST_VOLUME_AFTER_REBOOT - gPrefsSettings.putUInt("previousVolume", AudioPlayer_GetCurrentVolume()); -#endif + #ifdef USE_LAST_VOLUME_AFTER_REBOOT + gPrefsSettings.putUInt("previousVolume", AudioPlayer_GetCurrentVolume()); + #endif SdCard_Exit(); Serial.flush(); diff --git a/src/Web.cpp b/src/Web.cpp index 13edc7e..22f94fa 100644 --- a/src/Web.cpp +++ b/src/Web.cpp @@ -21,13 +21,18 @@ #include "Web.h" #include "Wlan.h" -#include "HTMLaccesspoint_DE.h" -#include "HTMLaccesspoint_EN.h" -#include "HTMLmanagement_DE.h" -#include "HTMLmanagement_EN.h" +#if (LANGUAGE == 1) + #include "HTMLaccesspoint_DE.h" + #include "HTMLmanagement_DE.h" +#endif -typedef struct -{ +#if (LANGUAGE == 2) + #include "HTMLaccesspoint_EN.h" + #include "HTMLmanagement_EN.h" +#endif + + +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()); @@ -80,45 +83,41 @@ void Web_Init(void) }); wServer.on("/restart", HTTP_GET, [](AsyncWebServerRequest *request) { -#if (LANGUAGE == 1) + #if (LANGUAGE == 1) request->send(200, "text/html", "ESPuino wird neu gestartet..."); -#else - request->send(200, "text/html", "ESPuino is being restarted..."); -#endif + #else + request->send(200, "text/html", "ESPuino is being restarted..."); + #endif Serial.flush(); ESP.restart(); }); wServer.on("/shutdown", HTTP_GET, [](AsyncWebServerRequest *request) { -#if (LANGUAGE == 1) + #if (LANGUAGE == 1) request->send(200, "text/html", "ESPuino wird ausgeschaltet..."); -#else - request->send(200, "text/html", "ESPuino is being shutdown..."); -#endif + #else + request->send(200, "text/html", "ESPuino is being shutdown..."); + #endif System_RequestSleep(); }); // allow cors for local debug DefaultHeaders::Instance().addHeader("Access-Control-Allow-Origin", "*"); wServer.begin(); - Log_Println((char *)FPSTR(httpReady), LOGLEVEL_NOTICE); + 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 -#ifdef FTP_ENABLE - return (String)FPSTR(ftpTab); -#else + } 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") - { + #endif + } 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 -#ifdef MQTT_ENABLE - return (String)FPSTR(mqttTab); -#else + } 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()) - { + #endif + } 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,25 +261,22 @@ 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(); - if (error) - { -#if (LANGUAGE == 1) - Serial.print(F("deserializeJson() fehlgeschlagen: ")); -#else - Serial.print(F("deserializeJson() failed: ")); -#endif + if (error) { + #if (LANGUAGE == 1) + Serial.print(F("deserializeJson() fehlgeschlagen: ")); + #else + Serial.print(F("deserializeJson() failed: ")); + #endif Serial.println(error.c_str()); return false; } - if (doc.containsKey("general")) - { + if (doc.containsKey("general")) { uint8_t iVol = doc["general"]["iVol"].as(); uint8_t mVolSpeaker = doc["general"]["mVolSpeaker"].as(); uint8_t mVolHeadphone = doc["general"]["mVolHeadphone"].as(); @@ -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(); 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")) - { + Web_DumpNvsToSd("rfidTags", (const char*) FPSTR(backupFile)); // Store backup-file every time when a new rfid-tag is programmed + } 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")) - { + Web_DumpNvsToSd("rfidTags", (const char*) FPSTR(backupFile)); // Store backup-file every time when a new rfid-tag is programmed + } 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(); AudioPlayer_VolumeToQueueSender(new_vol, true); - } - if (object["controls"].containsKey("action")) - { + } if (object["controls"].containsKey("action")) { uint8_t cmd = doc["controls"]["action"].as(); 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 doc; JsonObject object = doc.to(); - 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,40 +479,33 @@ 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; } convertUtf8ToAscii(utf8FilePath, filePath); - snprintf(Log_Buffer, Log_BufferLength, "%s: %s", (char *)FPSTR(writingFile), utf8FilePath.c_str()); + snprintf(Log_Buffer, Log_BufferLength, "%s: %s", (char *)FPSTR (writingFile), utf8FilePath.c_str()); 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,38 +582,31 @@ 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) - { - snprintf(Log_Buffer, Log_BufferLength, (char *)FPSTR(failedToOpenDirectory)); + if (!root) { + snprintf(Log_Buffer, Log_BufferLength, (char *) FPSTR(failedToOpenDirectory)); Log_Println(Log_Buffer, LOGLEVEL_DEBUG); return; } - if (!root.isDirectory()) - { - snprintf(Log_Buffer, Log_BufferLength, (char *)FPSTR(notADirectory)); + if (!root.isDirectory()) { + snprintf(Log_Buffer, Log_BufferLength, (char *) FPSTR(notADirectory)); Log_Println(Log_Buffer, LOGLEVEL_DEBUG); return; } 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,36 +767,27 @@ 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] == '#') - { - snprintf(Log_Buffer, Log_BufferLength, "%s: %s => %s", (char *)FPSTR(writeEntryToNvs), nvsEntry[0].nvsKey, nvsEntry[0].nvsEntry); + 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++; } } diff --git a/src/Wlan.cpp b/src/Wlan.cpp index fd17606..80c5142 100644 --- a/src/Wlan.cpp +++ b/src/Wlan.cpp @@ -25,122 +25,103 @@ 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")) - { - Log_Println((char *)FPSTR(ssidNotFoundInNvs), LOGLEVEL_ERROR); + if (!strSSID.compareTo("-1")) { + Log_Println((char *) FPSTR(ssidNotFoundInNvs), LOGLEVEL_ERROR); } String strPassword = gPrefsSettings.getString("Password", "-1"); - if (!strPassword.compareTo("-1")) - { - Log_Println((char *)FPSTR(wifiPwdNotFoundInNvs), LOGLEVEL_ERROR); + if (!strPassword.compareTo("-1")) { + Log_Println((char *) FPSTR(wifiPwdNotFoundInNvs), LOGLEVEL_ERROR); } const char *_ssid = strSSID.c_str(); const char *_pwd = strPassword.c_str(); // 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()); + snprintf(Log_Buffer, Log_BufferLength, "%s: %s", (char *) FPSTR(restoredHostnameFromNvs), hostname.c_str()); Log_Println(Log_Buffer, LOGLEVEL_INFO); - } - else - { - Log_Println((char *)FPSTR(wifiHostnameNotSet), LOGLEVEL_INFO); + } else { + Log_Println((char *) FPSTR(wifiHostnameNotSet), LOGLEVEL_INFO); } -// Add configration of static IP (if requested) -#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))) - { - snprintf(Log_Buffer, Log_BufferLength, "%s", (char *)FPSTR(staticIPConfigFailed)); - Log_Println(Log_Buffer, LOGLEVEL_ERROR); - } -#endif + // Add configration of static IP (if requested) + #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))) { + snprintf(Log_Buffer, Log_BufferLength, "%s", (char *) FPSTR(staticIPConfigFailed)); + Log_Println(Log_Buffer, LOGLEVEL_ERROR); + } + #endif // Try to join local WiFi. If not successful, an access-point is opened 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]); -#else - snprintf(Log_Buffer, Log_BufferLength, "Current IP: %d.%d.%d.%d", myIP[0], myIP[1], myIP[2], myIP[3]); -#endif + #if (LANGUAGE == 1) + snprintf(Log_Buffer, Log_BufferLength, "Aktuelle IP: %d.%d.%d.%d", myIP[0], myIP[1], myIP[2], myIP[3]); + #else + 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 - accessPointStart((char *)FPSTR(accessPointNetworkSSID), apIP, apNetmask); + } else { // Starts AP if WiFi-connect wasn't successful + accessPointStart((char *) FPSTR(accessPointNetworkSSID), apIP, apNetmask); } -#ifdef MDNS_ENABLE - // zero conf, make device available as .local - if (MDNS.begin(hostname.c_str())) - { - MDNS.addService("http", "tcp", 80); - } -#endif + #ifdef MDNS_ENABLE + // zero conf, make device available as .local + if (MDNS.begin(hostname.c_str())) { + MDNS.addService("http", "tcp", 80); + } + #endif wifiNeedsRestart = false; } } -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); delay(500); - Log_Println((char *)FPSTR(apReady), LOGLEVEL_NOTICE); + Log_Println((char *) FPSTR(apReady), LOGLEVEL_NOTICE); snprintf(Log_Buffer, Log_BufferLength, "IP-Adresse: %d.%d.%d.%d", apIP[0], apIP[1], apIP[2], apIP[3]); Log_Println(Log_Buffer, LOGLEVEL_NOTICE); @@ -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,34 +144,26 @@ bool getWifiEnableStatusFromNVS(void) } // Writes to NVS whether WiFi should be activated -void writeWifiStatusToNVS(bool wifiStatus) -{ - if (!wifiStatus) - { - if (gPrefsSettings.putUInt("enableWifi", 0)) - { // disable - Log_Println((char *)FPSTR(wifiDisabledAfterRestart), LOGLEVEL_NOTICE); - if (gPlayProperties.playMode == WEBSTREAM) - { +void writeWifiStatusToNVS(bool wifiStatus) { + if (!wifiStatus) { + if (gPrefsSettings.putUInt("enableWifi", 0)) { // disable + Log_Println((char *) FPSTR(wifiDisabledAfterRestart), LOGLEVEL_NOTICE); + if (gPlayProperties.playMode == WEBSTREAM) { AudioPlayer_TrackControlToQueueSender(STOP); } delay(300); WiFi.mode(WIFI_OFF); wifiEnabled = false; } - } - else - { - if (gPrefsSettings.putUInt("enableWifi", 1)) - { // enable - Log_Println((char *)FPSTR(wifiEnabledAfterRestart), LOGLEVEL_NOTICE); + } else { + if (gPrefsSettings.putUInt("enableWifi", 1)) { // enable + Log_Println((char *) FPSTR(wifiEnabledAfterRestart), LOGLEVEL_NOTICE); wifiNeedsRestart = true; wifiEnabled = true; } } } -bool Wlan_IsConnected(void) -{ +bool Wlan_IsConnected(void) { return (WiFi.status() == WL_CONNECTED); } \ No newline at end of file diff --git a/src/main.cpp b/src/main.cpp index 6c49e89..c12ce31 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -25,76 +25,68 @@ #include "Wlan.h" #ifdef PLAY_LAST_RFID_AFTER_REBOOT -bool recoverLastRfid = true; + bool recoverLastRfid = true; #endif //////////// #if (HAL == 2) -#include "AC101.h" -static TwoWire i2cBusOne = TwoWire(0); -static AC101 ac(&i2cBusOne); + #include "AC101.h" + static TwoWire i2cBusOne = TwoWire(0); + static AC101 ac(&i2cBusOne); #endif // I2C #if defined(RFID_READER_TYPE_MFRC522_I2C) || defined(PORT_EXPANDER_ENABLE) -TwoWire i2cBusTwo = TwoWire(1); + TwoWire i2cBusTwo = TwoWire(1); #endif #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 + // 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 + recoverLastRfid = false; + return; + } recoverLastRfid = false; - return; - } - recoverLastRfid = false; - String lastRfidPlayed = gPrefsSettings.getString("lastRfid", "-1"); - if (!lastRfidPlayed.compareTo("-1")) - { - Log_Println((char *)FPSTR(unableToRestoreLastRfidFromNVS), LOGLEVEL_INFO); - } - else - { - char *lastRfid = x_strdup(lastRfidPlayed.c_str()); - xQueueSend(gRfidCardQueue, &lastRfid, 0); - snprintf(Log_Buffer, Log_BufferLength, "%s: %s", (char *)FPSTR(restoredLastRfidFromNVS), lastRfidPlayed.c_str()); - Log_Println(Log_Buffer, LOGLEVEL_INFO); + String lastRfidPlayed = gPrefsSettings.getString("lastRfid", "-1"); + if (!lastRfidPlayed.compareTo("-1")) { + Log_Println((char *) FPSTR(unableToRestoreLastRfidFromNVS), LOGLEVEL_INFO); + } else { + char *lastRfid = x_strdup(lastRfidPlayed.c_str()); + xQueueSend(gRfidCardQueue, lastRfid, 0); + snprintf(Log_Buffer, Log_BufferLength, "%s: %s", (char *) FPSTR(restoredLastRfidFromNVS), lastRfidPlayed.c_str()); + Log_Println(Log_Buffer, LOGLEVEL_INFO); + } } } -} #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) - { - case ESP_SLEEP_WAKEUP_EXT0: - Serial.println(F("Wakeup caused by push button")); - break; - case ESP_SLEEP_WAKEUP_EXT1: - Serial.println(F("Wakeup caused by low power card detection")); - break; - case ESP_SLEEP_WAKEUP_TIMER: - Serial.println(F("Wakeup caused by timer")); - break; - case ESP_SLEEP_WAKEUP_TOUCHPAD: - Serial.println(F("Wakeup caused by touchpad")); - break; - case ESP_SLEEP_WAKEUP_ULP: - Serial.println(F("Wakeup caused by ULP program")); - break; - default: - Serial.printf("Wakeup was not caused by deep sleep: %d\n", wakeup_reason); - break; + switch (wakeup_reason) { + case ESP_SLEEP_WAKEUP_EXT0: + Serial.println(F("Wakeup caused by push button")); + break; + case ESP_SLEEP_WAKEUP_EXT1: + Serial.println(F("Wakeup caused by low power card detection")); + break; + case ESP_SLEEP_WAKEUP_TIMER: + Serial.println(F("Wakeup caused by timer")); + break; + case ESP_SLEEP_WAKEUP_TOUCHPAD: + Serial.println(F("Wakeup caused by touchpad")); + break; + case ESP_SLEEP_WAKEUP_ULP: + Serial.println(F("Wakeup caused by ULP program")); + break; + default: + Serial.printf("Wakeup was not caused by deep sleep: %d\n", wakeup_reason); + break; } } @@ -107,10 +99,10 @@ void setup() memset(&gPlayProperties, 0, sizeof(gPlayProperties)); gPlayProperties.playlistFinished = true; -#ifdef PLAY_MONO_SPEAKER - gPlayProperties.newPlayMono = true; - gPlayProperties.currentPlayMono = true; -#endif + #ifdef PLAY_MONO_SPEAKER + gPlayProperties.newPlayMono = true; + gPlayProperties.currentPlayMono = true; + #endif // Examples for serialized RFID-actions that are stored in NVS // #### @@ -123,32 +115,31 @@ void setup() Led_Init(); -#if (HAL == 2) - i2cBusOne.begin(IIC_DATA, IIC_CLK, 40000); + #if (HAL == 2) + i2cBusOne.begin(IIC_DATA, IIC_CLK, 40000); - while (not ac.begin()) - { - Serial.println(F("AC101 Failed!")); - delay(1000); - } - Serial.println(F("AC101 via I2C - OK!")); + while (not ac.begin()) { + Serial.println(F("AC101 Failed!")); + delay(1000); + } + Serial.println(F("AC101 via I2C - OK!")); - pinMode(22, OUTPUT); - digitalWrite(22, HIGH); + pinMode(22, OUTPUT); + digitalWrite(22, HIGH); - pinMode(GPIO_PA_EN, OUTPUT); - digitalWrite(GPIO_PA_EN, HIGH); - Serial.println(F("Built-in amplifier enabled\n")); -#endif + pinMode(GPIO_PA_EN, OUTPUT); + digitalWrite(GPIO_PA_EN, HIGH); + Serial.println(F("Built-in amplifier enabled\n")); + #endif SdCard_Init(); -// Init 2nd i2c-bus if RC522 is used with i2c or if port-expander is enabled -#if defined(RFID_READER_TYPE_MFRC522_I2C) || defined(PORT_EXPANDER_ENABLE) - i2cBusTwo.begin(ext_IIC_DATA, ext_IIC_CLK, 40000); - delay(50); - Log_Println((char *)FPSTR(rfidScannerReady), LOGLEVEL_DEBUG); -#endif + // Init 2nd i2c-bus if RC522 is used with i2c or if port-expander is enabled + #if defined(RFID_READER_TYPE_MFRC522_I2C) || defined(PORT_EXPANDER_ENABLE) + i2cBusTwo.begin(ext_IIC_DATA, ext_IIC_CLK, 40000); + delay(50); + Log_Println((char *) FPSTR(rfidScannerReady), LOGLEVEL_DEBUG); + #endif // welcome message Serial.println(F("")); @@ -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,32 +178,25 @@ 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()); + snprintf(Log_Buffer, Log_BufferLength, "%s: %u", (char *) FPSTR(freeHeapAfterSetup), ESP.getFreeHeap()); Log_Println(Log_Buffer, LOGLEVEL_DEBUG); 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(); @@ -234,9 +211,9 @@ void loop() System_Cyclic(); Rfid_PreferenceLookupHandler(); -#ifdef PLAY_LAST_RFID_AFTER_REBOOT - recoverLastRfidPlayed(); -#endif + #ifdef PLAY_LAST_RFID_AFTER_REBOOT + recoverLastRfidPlayed(); + #endif IrReceiver_Cyclic();