Added basic Logger with 4 modes.
This commit is contained in:
@@ -26,25 +26,20 @@ void SuscribeMqtt() {
|
|||||||
String topicRelayTimers = String("vesper/") + DEV_ID + "/control/settings/relayTimers";
|
String topicRelayTimers = String("vesper/") + DEV_ID + "/control/settings/relayTimers";
|
||||||
|
|
||||||
uint16_t control_id = mqttClient.subscribe(topicPlayback.c_str(), 2);
|
uint16_t control_id = mqttClient.subscribe(topicPlayback.c_str(), 2);
|
||||||
Serial.print("Subscribing to Playback Control topic, QoS 2, packetId: ");
|
LOG_INFO("Subscribing to Playback Control topic, QoS 2, packetId: %d", control_id);
|
||||||
Serial.println(control_id);
|
|
||||||
|
|
||||||
uint16_t set_melody_id = mqttClient.subscribe(topicSetMelody.c_str(), 2);
|
uint16_t set_melody_id = mqttClient.subscribe(topicSetMelody.c_str(), 2);
|
||||||
Serial.print("Subscribing to Set-Melody topic, QoS 2, packetId: ");
|
LOG_INFO("Subscribing to Set-Melody topic, QoS 2, packetId: %d", set_melody_id);
|
||||||
Serial.println(set_melody_id);
|
|
||||||
|
|
||||||
// doesn't work yet:
|
// doesn't work yet:
|
||||||
uint16_t add_melody_id = mqttClient.subscribe(topicAddMelody.c_str(), 2);
|
uint16_t add_melody_id = mqttClient.subscribe(topicAddMelody.c_str(), 2);
|
||||||
Serial.print("Subscribing to Add-Melody topic, QoS 2, packetId: ");
|
LOG_INFO("Subscribing to Add-Melody topic, QoS 2, packetId: %d", add_melody_id);
|
||||||
Serial.println(add_melody_id);
|
|
||||||
|
|
||||||
uint16_t add_schedule_id = mqttClient.subscribe(topicAddSchedule.c_str(), 2);
|
uint16_t add_schedule_id = mqttClient.subscribe(topicAddSchedule.c_str(), 2);
|
||||||
Serial.print("Subscribing to Add-Schedule topic, QoS 2, packetId: ");
|
LOG_INFO("Subscribing to Add-Schedule topic, QoS 2, packetId: %d", add_schedule_id);
|
||||||
Serial.println(add_schedule_id);
|
|
||||||
|
|
||||||
uint16_t relay_timers_id = mqttClient.subscribe(topicRelayTimers.c_str(), 2);
|
uint16_t relay_timers_id = mqttClient.subscribe(topicRelayTimers.c_str(), 2);
|
||||||
Serial.print("Subscribing to Relay-Timers topic, QoS 2, packetId: ");
|
LOG_INFO("Subscribing to Relay-Timers topic, QoS 2, packetId: %d", relay_timers_id);
|
||||||
Serial.println(relay_timers_id);
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -72,7 +67,7 @@ void OnMqttReceived(char * topic, char * payload, AsyncMqttClientMessageProperti
|
|||||||
|
|
||||||
else if (String(topic) == topicAddMelody) {
|
else if (String(topic) == topicAddMelody) {
|
||||||
// Handle adding melody
|
// Handle adding melody
|
||||||
Serial.println("Adding melody...");
|
LOG_INFO("Adding melody...");
|
||||||
// You can call a function here to handle adding the melody
|
// You can call a function here to handle adding the melody
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -86,7 +81,7 @@ void OnMqttReceived(char * topic, char * payload, AsyncMqttClientMessageProperti
|
|||||||
|
|
||||||
else {
|
else {
|
||||||
// Handle unknown topics
|
// Handle unknown topics
|
||||||
Serial.println("Unknown topic received.");
|
LOG_WARNING("Unknown topic received.");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -14,21 +14,20 @@ String GetPayloadContent(char * data, size_t len) {
|
|||||||
|
|
||||||
void ConnectToMqtt()
|
void ConnectToMqtt()
|
||||||
{
|
{
|
||||||
Serial.println("Connecting to MQTT...");
|
LOG_INFO("Connecting to MQTT...");
|
||||||
mqttClient.connect();
|
mqttClient.connect();
|
||||||
}
|
}
|
||||||
|
|
||||||
void OnMqttConnect(bool sessionPresent)
|
void OnMqttConnect(bool sessionPresent)
|
||||||
{
|
{
|
||||||
Serial.println("Connected to MQTT.");
|
LOG_INFO("Connected to MQTT.");
|
||||||
Serial.print("Session present: ");
|
//LOG_INFO("Session present: %s", sessionPresent ? "Yes":"No");
|
||||||
Serial.println(sessionPresent);
|
|
||||||
SuscribeMqtt();
|
SuscribeMqtt();
|
||||||
}
|
}
|
||||||
|
|
||||||
void OnMqttDisconnect(AsyncMqttClientDisconnectReason reason)
|
void OnMqttDisconnect(AsyncMqttClientDisconnectReason reason)
|
||||||
{
|
{
|
||||||
Serial.println("Disconnected from MQTT.");
|
LOG_WARNING("Disconnected from MQTT.");
|
||||||
|
|
||||||
if(WiFi.isConnected())
|
if(WiFi.isConnected())
|
||||||
{
|
{
|
||||||
@@ -38,25 +37,17 @@ void OnMqttDisconnect(AsyncMqttClientDisconnectReason reason)
|
|||||||
|
|
||||||
void OnMqttSubscribe(uint16_t packetId, uint8_t qos)
|
void OnMqttSubscribe(uint16_t packetId, uint8_t qos)
|
||||||
{
|
{
|
||||||
Serial.println("Subscribe acknowledged.");
|
LOG_INFO("Subscribe acknowledged. PacketID: %d / QoS: %d", packetId, qos);
|
||||||
Serial.print(" packetId: ");
|
|
||||||
Serial.println(packetId);
|
|
||||||
Serial.print(" qos: ");
|
|
||||||
Serial.println(qos);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
void OnMqttUnsubscribe(uint16_t packetId)
|
void OnMqttUnsubscribe(uint16_t packetId)
|
||||||
{
|
{
|
||||||
Serial.println("Unsubscribe acknowledged.");
|
LOG_INFO("Unsubscribe Acknowledged. PacketID: %d",packetId);
|
||||||
Serial.print(" packetId: ");
|
|
||||||
Serial.println(packetId);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
void OnMqttPublish(uint16_t packetId)
|
void OnMqttPublish(uint16_t packetId)
|
||||||
{
|
{
|
||||||
Serial.println("Publish acknowledged.");
|
LOG_INFO("Publish Acknowledged. PacketID: %d", packetId);
|
||||||
Serial.print(" packetId: ");
|
|
||||||
Serial.println(packetId);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
void ConnectWiFi_STA(bool useStaticIP = false)
|
void ConnectWiFi_STA(bool useStaticIP = false)
|
||||||
@@ -74,11 +65,13 @@ void ConnectWiFi_STA(bool useStaticIP = false)
|
|||||||
Serial.print('.');
|
Serial.print('.');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (LOG_LEVEL_ENABLED(LOG_LEVEL_INFO)){
|
||||||
Serial.println("");
|
Serial.println("");
|
||||||
Serial.print("Iniciado STA:\t");
|
Serial.print("Initiating STA:\t");
|
||||||
Serial.println(ssid);
|
Serial.println(ssid);
|
||||||
Serial.print("IP address:\t");
|
Serial.print("IP address:\t");
|
||||||
Serial.println(WiFi.localIP());
|
Serial.println(WiFi.localIP());
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
void ConnectWiFi_AP(bool useStaticIP = false)
|
void ConnectWiFi_AP(bool useStaticIP = false)
|
||||||
@@ -93,26 +86,27 @@ void ConnectWiFi_AP(bool useStaticIP = false)
|
|||||||
|
|
||||||
if(useStaticIP) WiFi.softAPConfig(ip, gateway, subnet);
|
if(useStaticIP) WiFi.softAPConfig(ip, gateway, subnet);
|
||||||
|
|
||||||
|
if (LOG_LEVEL_ENABLED(LOG_LEVEL_INFO)){
|
||||||
Serial.println("");
|
Serial.println("");
|
||||||
Serial.print("Iniciado AP:\t");
|
Serial.print("Iniciado AP:\t");
|
||||||
Serial.println(ssid);
|
Serial.println(ssid);
|
||||||
Serial.print("IP address:\t");
|
Serial.print("IP address:\t");
|
||||||
Serial.println(WiFi.softAPIP());
|
Serial.println(WiFi.softAPIP());
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
void WiFiEvent(WiFiEvent_t event)
|
void WiFiEvent(WiFiEvent_t event)
|
||||||
{
|
{
|
||||||
Serial.printf("[WiFi-event] event: %d\n", event);
|
LOG_INFO("[WiFi-event] event: %d\n", event);
|
||||||
switch(event)
|
switch(event)
|
||||||
{
|
{
|
||||||
case ARDUINO_EVENT_WIFI_STA_GOT_IP:
|
case ARDUINO_EVENT_WIFI_STA_GOT_IP:
|
||||||
Serial.println("WiFi connected");
|
Serial.print("[INFO] - WiFi connected. IP Address: ");
|
||||||
Serial.println("IP address: ");
|
|
||||||
Serial.println(WiFi.localIP());
|
Serial.println(WiFi.localIP());
|
||||||
ConnectToMqtt();
|
ConnectToMqtt();
|
||||||
break;
|
break;
|
||||||
case ARDUINO_EVENT_WIFI_STA_DISCONNECTED:
|
case ARDUINO_EVENT_WIFI_STA_DISCONNECTED:
|
||||||
Serial.println("WiFi lost connection");
|
LOG_WARNING("WiFi Lost Connection! :()");
|
||||||
xTimerStop(mqttReconnectTimer, 0); // ensure we don't reconnect to MQTT while reconnecting to Wi-Fi
|
xTimerStop(mqttReconnectTimer, 0); // ensure we don't reconnect to MQTT while reconnecting to Wi-Fi
|
||||||
xTimerStart(wifiReconnectTimer, 0);
|
xTimerStart(wifiReconnectTimer, 0);
|
||||||
break;
|
break;
|
||||||
|
|||||||
@@ -35,7 +35,7 @@ bool timeToStop(unsigned long now) {
|
|||||||
if (player.isPlaying) {
|
if (player.isPlaying) {
|
||||||
uint64_t stopTime = player.startTime + player.duration;
|
uint64_t stopTime = player.startTime + player.duration;
|
||||||
if (now >= stopTime) {
|
if (now >= stopTime) {
|
||||||
Serial.println("TIMER: Total Duration Reached");
|
LOG_DEBUG("TIMER: Total Duration Reached");
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -46,10 +46,9 @@ bool timeToStop(unsigned long now) {
|
|||||||
bool timeToPause(unsigned long now) {
|
bool timeToPause(unsigned long now) {
|
||||||
if (player.isPlaying && player.loop_duration > 0) {
|
if (player.isPlaying && player.loop_duration > 0) {
|
||||||
uint64_t pauseTimeLimit = player.loopStartTime + player.loop_duration;
|
uint64_t pauseTimeLimit = player.loopStartTime + player.loop_duration;
|
||||||
Serial.printf("PTL: %lu // NOW: ",pauseTimeLimit);
|
LOG_DEBUG("PTL: %lu // NOW: %d",pauseTimeLimit, now);
|
||||||
Serial.println(now);
|
|
||||||
if (now >= pauseTimeLimit && !player.isPaused) {
|
if (now >= pauseTimeLimit && !player.isPaused) {
|
||||||
Serial.println("TIMER: Segment Duration Reached");
|
LOG_DEBUG("TIMER: Segment Duration Reached");
|
||||||
player.pauseTime = now;
|
player.pauseTime = now;
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
@@ -62,7 +61,7 @@ bool timeToResume(unsigned long now) {
|
|||||||
if (player.isPaused) {
|
if (player.isPaused) {
|
||||||
uint64_t resumeTime = player.pauseTime + player.interval;
|
uint64_t resumeTime = player.pauseTime + player.interval;
|
||||||
if (now >= resumeTime) {
|
if (now >= resumeTime) {
|
||||||
Serial.println("TIMER: Pause Duration Reached");
|
LOG_DEBUG("TIMER: Pause Duration Reached");
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -67,7 +67,7 @@ void loop_playback(std::vector<uint16_t> &melody_steps) {
|
|||||||
vTaskDelay(pdMS_TO_TICKS(tempo));
|
vTaskDelay(pdMS_TO_TICKS(tempo));
|
||||||
}
|
}
|
||||||
|
|
||||||
Serial.println("SINGLE LOOP OVER.");
|
LOG_DEBUG("Single Loop Over.");
|
||||||
//if (!player.isPlaying) break; // Stop playback only after completing the loop
|
//if (!player.isPlaying) break; // Stop playback only after completing the loop
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -24,36 +24,35 @@ public:
|
|||||||
isPlaying = true;
|
isPlaying = true;
|
||||||
hardStop = false;
|
hardStop = false;
|
||||||
startTime = loopStartTime = millis();
|
startTime = loopStartTime = millis();
|
||||||
Serial.println("Plbck: PLAY");
|
LOG_DEBUG("Plbck: PLAY");
|
||||||
}
|
}
|
||||||
|
|
||||||
void forceStop() {
|
void forceStop() {
|
||||||
hardStop = true;
|
hardStop = true;
|
||||||
isPlaying = false;
|
isPlaying = false;
|
||||||
Serial.println("Plbck: FORCE STOP");
|
LOG_DEBUG("Plbck: FORCE STOP");
|
||||||
}
|
}
|
||||||
|
|
||||||
void stop() {
|
void stop() {
|
||||||
hardStop = false;
|
hardStop = false;
|
||||||
isPlaying = false;
|
isPlaying = false;
|
||||||
Serial.println("Plbck: STOP");
|
LOG_DEBUG("Plbck: STOP");
|
||||||
}
|
}
|
||||||
|
|
||||||
void pause() {
|
void pause() {
|
||||||
isPaused = true;
|
isPaused = true;
|
||||||
Serial.println("Plbck: PAUSE");
|
LOG_DEBUG("Plbck: PAUSE");
|
||||||
}
|
}
|
||||||
|
|
||||||
void unpause() {
|
void unpause() {
|
||||||
isPaused = false;
|
isPaused = false;
|
||||||
loopStartTime = millis();
|
loopStartTime = millis();
|
||||||
Serial.println("Plbck: RESUME");
|
LOG_DEBUG("Plbck: RESUME");
|
||||||
}
|
}
|
||||||
|
|
||||||
// Handles Incoming Commands to PLAY or STOP
|
// Handles Incoming Commands to PLAY or STOP
|
||||||
void command(char * command){
|
void command(char * command){
|
||||||
Serial.print("INCOMING COMMAND: ");
|
LOG_DEBUG("Incoming Command: %s",command);
|
||||||
Serial.println(command);
|
|
||||||
if (command[0] == '1') {
|
if (command[0] == '1') {
|
||||||
play();
|
play();
|
||||||
PublishMqtt("OK - PLAY");
|
PublishMqtt("OK - PLAY");
|
||||||
@@ -88,7 +87,7 @@ public:
|
|||||||
loop_duration = doc["loop_dur"].as<uint32_t>();
|
loop_duration = doc["loop_dur"].as<uint32_t>();
|
||||||
}
|
}
|
||||||
// Print Just for Debugging Purposes
|
// Print Just for Debugging Purposes
|
||||||
Serial.printf("Name: %s, ID: %d, Total Duration: %lu, Loop Duration: %lu, Interval: %d, Speed: %d, Inf: %s\n",
|
LOG_DEBUG("Name: %s, ID: %d, Total Duration: %lu, Loop Duration: %lu, Interval: %d, Speed: %d, Inf: %s\n",
|
||||||
name.c_str(),
|
name.c_str(),
|
||||||
id,
|
id,
|
||||||
duration,
|
duration,
|
||||||
@@ -102,13 +101,12 @@ public:
|
|||||||
// Loads the Selected melody from a .bin file, into RAM
|
// Loads the Selected melody from a .bin file, into RAM
|
||||||
void loadMelodyInRAM(std::vector<uint16_t> &melody_steps) {
|
void loadMelodyInRAM(std::vector<uint16_t> &melody_steps) {
|
||||||
|
|
||||||
|
LOG_INFO("Loading Melody.");
|
||||||
std::string filePath = "/" + name + ".bin";
|
std::string filePath = "/" + name + ".bin";
|
||||||
Serial.println("New Melody Selected !!!");
|
|
||||||
Serial.println("Reading data from file...");
|
|
||||||
|
|
||||||
File bin_file = SPIFFS.open(filePath.c_str(), "r");
|
File bin_file = SPIFFS.open(filePath.c_str(), "r");
|
||||||
if (!bin_file) {
|
if (!bin_file) {
|
||||||
Serial.println("Failed to Open File");
|
LOG_ERROR("Failed to Open File");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -116,22 +114,14 @@ public:
|
|||||||
size_t steps = fileSize / 2;
|
size_t steps = fileSize / 2;
|
||||||
melody_steps.resize(steps);
|
melody_steps.resize(steps);
|
||||||
|
|
||||||
Serial.print("Opened File ! Size: ");
|
LOG_DEBUG("Opened File, size: %zu - Steps: %zu",fileSize,steps)
|
||||||
Serial.print(fileSize);
|
|
||||||
Serial.print(" Steps: ");
|
|
||||||
Serial.println(steps);
|
|
||||||
|
|
||||||
for (size_t i=0; i<steps; i++){
|
for (size_t i=0; i<steps; i++){
|
||||||
melody_steps[i] = bin_file.read() << 8 | bin_file.read();
|
melody_steps[i] = bin_file.read() << 8 | bin_file.read();
|
||||||
|
LOG_DEBUG("Current Step: %03d // HEX Value: 0x%04X", i, melody_steps[i]);
|
||||||
}
|
}
|
||||||
|
|
||||||
for (size_t i=0; i<steps; i++){
|
LOG_DEBUG("Closing File");
|
||||||
Serial.print("Current Step: ");
|
|
||||||
Serial.printf("%03d // ", i);
|
|
||||||
Serial.print(" HEX Value: ");
|
|
||||||
Serial.printf("0x%04X\n", melody_steps[i]);
|
|
||||||
}
|
|
||||||
Serial.println("Closing File");
|
|
||||||
bin_file.close();
|
bin_file.close();
|
||||||
|
|
||||||
// closing the file
|
// closing the file
|
||||||
@@ -173,32 +163,34 @@ private:
|
|||||||
std::string filePath = "/" + getMonth() + ".json";
|
std::string filePath = "/" + getMonth() + ".json";
|
||||||
File file = SPIFFS.open(filePath.c_str(), "r");
|
File file = SPIFFS.open(filePath.c_str(), "r");
|
||||||
if (!file) {
|
if (!file) {
|
||||||
Serial.printf("Failed to open file: %s\n", filePath.c_str());
|
LOG_ERROR("Failed to open file: %s\n", filePath.c_str());
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
Serial.println("Opened daily schedule file");
|
LOG_INFO("Opened daily schedule file");
|
||||||
StaticJsonDocument<8192> doc; // Adjust size based on expected JSON complexity
|
StaticJsonDocument<8192> doc; // Adjust size based on expected JSON complexity
|
||||||
DeserializationError error = deserializeJson(doc, file);
|
DeserializationError error = deserializeJson(doc, file);
|
||||||
file.close();
|
file.close();
|
||||||
|
|
||||||
if (error) {
|
if (error) {
|
||||||
Serial.printf("Failed to parse JSON: %s\n", error.c_str());
|
LOG_ERROR("Failed to parse JSON: %s\n", error.c_str());
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
Serial.println("- - - SERIALIZE JSON - - -");
|
if (LOG_LEVEL_ENABLED(LOG_LEVEL_DEBUG)){
|
||||||
serializeJsonPretty(doc, Serial);
|
String jsonString;
|
||||||
Serial.println("- - - - END JSON - - - -");
|
serializeJsonPretty(doc, jsonString);
|
||||||
|
LOG_DEBUG("Serialized JSON: /n%s",jsonString.c_str());
|
||||||
|
}
|
||||||
|
|
||||||
// Extract entries for the current day
|
// Extract entries for the current day
|
||||||
std::string currentDay = getDay();
|
std::string currentDay = getDay();
|
||||||
dailySchedule.clear(); // Clear previous day's schedule
|
dailySchedule.clear(); // Clear previous day's schedule
|
||||||
|
|
||||||
Serial.printf("Current Day: %s\n", currentDay.c_str());
|
LOG_DEBUG("Current Day: %s\n", currentDay.c_str());
|
||||||
|
|
||||||
if (doc.containsKey(currentDay.c_str())) {
|
if (doc.containsKey(currentDay.c_str())) {
|
||||||
Serial.println("doc contains key!");
|
LOG_DEBUG("Doc contains key!");
|
||||||
|
|
||||||
// Check if the current day contains a single object or an array
|
// Check if the current day contains a single object or an array
|
||||||
JsonVariant dayVariant = doc[currentDay.c_str()];
|
JsonVariant dayVariant = doc[currentDay.c_str()];
|
||||||
@@ -215,7 +207,7 @@ private:
|
|||||||
schedule.duration = entry["duration"];
|
schedule.duration = entry["duration"];
|
||||||
dailySchedule.push_back(schedule);
|
dailySchedule.push_back(schedule);
|
||||||
|
|
||||||
Serial.printf("Added Entry - Melody: %s, Hour: %d, Minute: %d, Speed: %d, Duration: %d\n",
|
LOG_INFO("Added Entry - Melody: %s, Hour: %d, Minute: %d, Speed: %d, Duration: %d\n",
|
||||||
schedule.mel.c_str(), schedule.hour, schedule.minute, schedule.speed, schedule.duration);
|
schedule.mel.c_str(), schedule.hour, schedule.minute, schedule.speed, schedule.duration);
|
||||||
}
|
}
|
||||||
} else if (dayVariant.is<JsonObject>()) {
|
} else if (dayVariant.is<JsonObject>()) {
|
||||||
@@ -229,13 +221,13 @@ private:
|
|||||||
schedule.duration = entry["duration"];
|
schedule.duration = entry["duration"];
|
||||||
dailySchedule.push_back(schedule);
|
dailySchedule.push_back(schedule);
|
||||||
|
|
||||||
Serial.printf("Added Single Entry - Melody: %s, Hour: %d, Minute: %d, Speed: %d, Duration: %d\n",
|
LOG_INFO("Added Single Entry - Melody: %s, Hour: %d, Minute: %d, Speed: %d, Duration: %d\n",
|
||||||
schedule.mel.c_str(), schedule.hour, schedule.minute, schedule.speed, schedule.duration);
|
schedule.mel.c_str(), schedule.hour, schedule.minute, schedule.speed, schedule.duration);
|
||||||
} else {
|
} else {
|
||||||
Serial.println("Invalid data format for the current day.");
|
LOG_WARNING("Invalid data format for the current day.");
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
Serial.println("No schedule found for today.");
|
LOG_INFO("No schedule found for today.");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -249,12 +241,12 @@ private:
|
|||||||
if (!alreadyTriggered) {
|
if (!alreadyTriggered) {
|
||||||
// First time at midnight, trigger the event
|
// First time at midnight, trigger the event
|
||||||
alreadyTriggered = true;
|
alreadyTriggered = true;
|
||||||
Serial.println("New day detected, returning true.");
|
LOG_DEBUG("New day detected, returning true.");
|
||||||
loadDailySchedule();
|
loadDailySchedule();
|
||||||
return true;
|
return true;
|
||||||
} else {
|
} else {
|
||||||
// It's still midnight, but we've already triggered
|
// It's still midnight, but we've already triggered
|
||||||
Serial.println("Already triggered for today, returning false.");
|
LOG_DEBUG("Already triggered for today, returning false.");
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
@@ -291,7 +283,7 @@ public:
|
|||||||
|
|
||||||
// Prints the time, NOW.
|
// Prints the time, NOW.
|
||||||
void printTimeNow(){
|
void printTimeNow(){
|
||||||
Serial.printf("Current Time: %s %s, %u - %02u:%02u:%02u\n",
|
LOG_INFO("Current Time: %s %s, %u - %02u:%02u:%02u\n",
|
||||||
getMonth().c_str(), // Month as a string
|
getMonth().c_str(), // Month as a string
|
||||||
getDay().c_str(), // Day as a string
|
getDay().c_str(), // Day as a string
|
||||||
getYear(), // Year as an integer
|
getYear(), // Year as an integer
|
||||||
@@ -306,18 +298,17 @@ public:
|
|||||||
}
|
}
|
||||||
|
|
||||||
void checkAndRunSchedule(Player & player) {
|
void checkAndRunSchedule(Player & player) {
|
||||||
|
LOG_DEBUG("Running daily schedule check");
|
||||||
for (auto it = dailySchedule.begin(); it != dailySchedule.end(); ) {
|
for (auto it = dailySchedule.begin(); it != dailySchedule.end(); ) {
|
||||||
Serial.println("Running daily schedule check");
|
|
||||||
if (now.hour == it->hour && now.minute == it->minute) {
|
if (now.hour == it->hour && now.minute == it->minute) {
|
||||||
Serial.printf("Entry Exists, returning True!");
|
LOG_DEBUG("Entry Exists, Calling program.");
|
||||||
StaticJsonDocument<200> jsonDoc;
|
StaticJsonDocument<200> jsonDoc;
|
||||||
jsonDoc["name"] = it->mel.c_str();
|
jsonDoc["name"] = it->mel.c_str();
|
||||||
jsonDoc["speed"] = it->speed;
|
jsonDoc["speed"] = it->speed;
|
||||||
jsonDoc["duration"] = it->duration;
|
jsonDoc["duration"] = it->duration;
|
||||||
jsonDoc["loop_dur"] = 0;
|
jsonDoc["loop_dur"] = 0;
|
||||||
jsonDoc["internal"] = 0;
|
jsonDoc["internal"] = 0;
|
||||||
Serial.printf("name: %s speed: %d duration: %d",it->mel.c_str(), it->speed, it->duration);
|
//LOG_INFO("Entry Found. Name: %s Speed: %d Duration: %d",it->mel.c_str(), it->speed, it->duration);
|
||||||
if (!player.isPlaying){
|
if (!player.isPlaying){
|
||||||
player.setMelodyAttributes(jsonDoc);
|
player.setMelodyAttributes(jsonDoc);
|
||||||
player.loadMelodyInRAM(melody_steps);
|
player.loadMelodyInRAM(melody_steps);
|
||||||
@@ -326,7 +317,7 @@ public:
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
else {
|
else {
|
||||||
Serial.printf("No Entry, returning False!");
|
LOG_DEBUG("Entry's time doesn't match. Skipping.");
|
||||||
++it;
|
++it;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -16,24 +16,25 @@ void updateRelayTimings(JsonDocument doc) {
|
|||||||
String key = String("b") + (i + 1); // Generate "b1", "b2", ...
|
String key = String("b") + (i + 1); // Generate "b1", "b2", ...
|
||||||
if (doc.containsKey(key)) {
|
if (doc.containsKey(key)) {
|
||||||
relayDurations[i] = doc[key].as<uint16_t>();
|
relayDurations[i] = doc[key].as<uint16_t>();
|
||||||
Serial.printf("Relay %d duration set to %d ms\n", i + 1, relayDurations[i]);
|
LOG_DEBUG("Relay %d duration s1et to %d ms\n", i + 1, relayDurations[i]);
|
||||||
} else {
|
} else {
|
||||||
Serial.printf("Relay %d not found in JSON payload. Keeping previous duration: %d ms\n", i + 1, relayDurations[i]);
|
LOG_DEBUG("Relay %d not found in JSON payload. Keeping previous duration: %d ms\n", i + 1, relayDurations[i]);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
saveRelayTimings();
|
saveRelayTimings();
|
||||||
|
LOG_INFO("Updated Relay Timings.")
|
||||||
}
|
}
|
||||||
|
|
||||||
// Save file "fileName" with data: "data"
|
// Save file "fileName" with data: "data"
|
||||||
void savefile(const char* fileName, const char* data) {
|
void savefile(const char* fileName, const char* data) {
|
||||||
File file = SPIFFS.open(fileName, "w");
|
File file = SPIFFS.open(fileName, "w");
|
||||||
if (!file) {
|
if (!file) {
|
||||||
Serial.println("Failed to open file!");
|
LOG_ERROR("Failed to open file!");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
file.print(data);
|
file.print(data);
|
||||||
file.close();
|
file.close();
|
||||||
Serial.printf("File %s saved successfully.\n", fileName);
|
LOG_INFO("File %s saved successfully.\n", fileName);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Saves Relay Durations from RAM, into a file
|
// Saves Relay Durations from RAM, into a file
|
||||||
@@ -49,7 +50,7 @@ void saveRelayTimings() {
|
|||||||
char buffer[512];
|
char buffer[512];
|
||||||
size_t len = serializeJson(doc, buffer, sizeof(buffer));
|
size_t len = serializeJson(doc, buffer, sizeof(buffer));
|
||||||
if (len == 0) {
|
if (len == 0) {
|
||||||
Serial.println("Failed to serialize JSON.");
|
LOG_ERROR("Failed to serialize JSON.");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -78,7 +79,7 @@ void loadRelayTimings() {
|
|||||||
// Open the file for reading
|
// Open the file for reading
|
||||||
File file = SPIFFS.open("/settings/relayTimings.json", "r");
|
File file = SPIFFS.open("/settings/relayTimings.json", "r");
|
||||||
if (!file) {
|
if (!file) {
|
||||||
Serial.println("Settings file not found. Using default relay timings.");
|
LOG_ERROR("Settings file not found. Using default relay timings.");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -86,7 +87,7 @@ void loadRelayTimings() {
|
|||||||
StaticJsonDocument<512> doc; // Adjust size if needed
|
StaticJsonDocument<512> doc; // Adjust size if needed
|
||||||
DeserializationError error = deserializeJson(doc, file);
|
DeserializationError error = deserializeJson(doc, file);
|
||||||
if (error) {
|
if (error) {
|
||||||
Serial.println("Failed to parse settings file. Using default relay timings.");
|
LOG_ERROR("Failed to parse settings file. Using default relay timings.");
|
||||||
file.close();
|
file.close();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -96,7 +97,7 @@ void loadRelayTimings() {
|
|||||||
String key = String("b") + (i + 1);
|
String key = String("b") + (i + 1);
|
||||||
if (doc.containsKey(key)) {
|
if (doc.containsKey(key)) {
|
||||||
relayDurations[i] = doc[key].as<uint16_t>();
|
relayDurations[i] = doc[key].as<uint16_t>();
|
||||||
Serial.printf("Loaded relay %d duration: %d ms\n", i + 1, relayDurations[i]);
|
LOG_DEBUG("Loaded relay %d duration: %d ms\n", i + 1, relayDurations[i]);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -109,7 +110,7 @@ void updateSchedule(JsonDocument doc) {
|
|||||||
|
|
||||||
// Ensure fileName exists and is valid
|
// Ensure fileName exists and is valid
|
||||||
if (!fileName || strlen(fileName) == 0) {
|
if (!fileName || strlen(fileName) == 0) {
|
||||||
Serial.println("Invalid JSON payload: Missing or invalid 'file' field");
|
LOG_ERROR("Invalid JSON payload: Missing or invalid 'file' field");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -119,9 +120,9 @@ void updateSchedule(JsonDocument doc) {
|
|||||||
|
|
||||||
if (dataString.length() > 0) {
|
if (dataString.length() > 0) {
|
||||||
savefile(fileName, dataString.c_str());
|
savefile(fileName, dataString.c_str());
|
||||||
Serial.printf("File '%s' updated successfully.\n", fileName);
|
LOG_INFO("File '%s' updated successfully.\n", fileName);
|
||||||
} else {
|
} else {
|
||||||
Serial.println("Invalid JSON payload: Unable to serialize 'data'");
|
LOG_DEBUG("Invalid JSON payload: Unable to serialize 'data'");
|
||||||
}
|
}
|
||||||
timekeeper.refreshDailySchedule();
|
timekeeper.refreshDailySchedule();
|
||||||
}
|
}
|
||||||
|
|||||||
37
vesper/logging.hpp
Normal file
37
vesper/logging.hpp
Normal file
@@ -0,0 +1,37 @@
|
|||||||
|
// Define Log Levels
|
||||||
|
#define LOG_LEVEL_NONE 0 // No logs
|
||||||
|
#define LOG_LEVEL_ERROR 1 // Errors only
|
||||||
|
#define LOG_LEVEL_WARNING 2 // Warnings and errors
|
||||||
|
#define LOG_LEVEL_INFO 3 // Info, warnings, and errors
|
||||||
|
#define LOG_LEVEL_DEBUG 4 // All logs (full debugging)
|
||||||
|
|
||||||
|
// Set the active log level
|
||||||
|
#define ACTIVE_LOG_LEVEL LOG_LEVEL_DEBUG
|
||||||
|
|
||||||
|
// Check if the log level is enabled
|
||||||
|
#define LOG_LEVEL_ENABLED(level) (ACTIVE_LOG_LEVEL >= level)
|
||||||
|
|
||||||
|
// Macro to control logging based on the active level
|
||||||
|
#if LOG_LEVEL_ENABLED(LOG_LEVEL_ERROR)
|
||||||
|
#define LOG_ERROR(...) { Serial.print("[ERROR] - "); Serial.printf(__VA_ARGS__); Serial.println(); }
|
||||||
|
#else
|
||||||
|
#define LOG_ERROR(...) // No logging if level is not enabled
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#if LOG_LEVEL_ENABLED(LOG_LEVEL_WARNING)
|
||||||
|
#define LOG_WARNING(...) { Serial.print("[WARNING] - "); Serial.printf(__VA_ARGS__); Serial.println(); }
|
||||||
|
#else
|
||||||
|
#define LOG_WARNING(...) // No logging if level is not enabled
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#if LOG_LEVEL_ENABLED(LOG_LEVEL_INFO)
|
||||||
|
#define LOG_INFO(...) { Serial.print("[INFO] - "); Serial.printf(__VA_ARGS__); Serial.println(); }
|
||||||
|
#else
|
||||||
|
#define LOG_INFO(...) // No logging if level is not enabled
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#if LOG_LEVEL_ENABLED(LOG_LEVEL_DEBUG)
|
||||||
|
#define LOG_DEBUG(...) { Serial.print("[DEBUG] - "); Serial.printf(__VA_ARGS__); Serial.println(); }
|
||||||
|
#else
|
||||||
|
#define LOG_DEBUG(...) // No logging if level is not enabled
|
||||||
|
#endif
|
||||||
@@ -14,7 +14,9 @@ TODO List:
|
|||||||
- Add
|
- Add
|
||||||
|
|
||||||
*/
|
*/
|
||||||
|
#include "logging.hpp"
|
||||||
|
|
||||||
|
#include <Arduino.h>
|
||||||
#include <WiFi.h>
|
#include <WiFi.h>
|
||||||
#include <AsyncMqttClient.h>
|
#include <AsyncMqttClient.h>
|
||||||
#include <ArduinoJson.h>
|
#include <ArduinoJson.h>
|
||||||
@@ -67,10 +69,10 @@ void setup()
|
|||||||
}
|
}
|
||||||
// Initialize SPIFFS
|
// Initialize SPIFFS
|
||||||
if (!SPIFFS.begin(true)) { // 'true' means format SPIFFS if initialization fails
|
if (!SPIFFS.begin(true)) { // 'true' means format SPIFFS if initialization fails
|
||||||
Serial.println("Failed to mount SPIFFS");
|
LOG_ERROR("Failed to mount SPIFFS");
|
||||||
while(true) delay(10);
|
while(true) delay(10);
|
||||||
}
|
}
|
||||||
Serial.println("SPIFFS mounted successfully");
|
LOG_INFO("SPIFFS mounted successfully");
|
||||||
delay(50);
|
delay(50);
|
||||||
// Initialize RTC
|
// Initialize RTC
|
||||||
if (!rtc.begin()) {
|
if (!rtc.begin()) {
|
||||||
@@ -79,7 +81,7 @@ void setup()
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (! rtc.isrunning()) {
|
if (! rtc.isrunning()) {
|
||||||
Serial.println("RTC is NOT running, let's set the time!");
|
LOG_INFO("RTC is NOT running, let's set the time!");
|
||||||
// When time needs to be set on a new device, or after a power loss, the
|
// When time needs to be set on a new device, or after a power loss, the
|
||||||
// following line sets the RTC to the date & time this sketch was compiled
|
// following line sets the RTC to the date & time this sketch was compiled
|
||||||
rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
|
rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
|
||||||
@@ -104,7 +106,7 @@ void setup()
|
|||||||
if (schedulerTimer != NULL) {
|
if (schedulerTimer != NULL) {
|
||||||
xTimerStart(schedulerTimer, 0);
|
xTimerStart(schedulerTimer, 0);
|
||||||
} else {
|
} else {
|
||||||
Serial.println("Failed to create timer!");
|
LOG_ERROR("Failed to create timer!");
|
||||||
}
|
}
|
||||||
|
|
||||||
timekeeper.refreshDailySchedule();
|
timekeeper.refreshDailySchedule();
|
||||||
|
|||||||
Reference in New Issue
Block a user