Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <ESP8266WiFi.h>
- #include <AbstractTask.h>
- #include <Scheduler.h>
- #include <Task.h>
- #include <PubSubClient.h>
- #include "helpers/wifihelper.h"
- #include <Arduino.h>
- #include <Arduino_JSON.h>
- #include <string>
- #include <stdexcept>
- #include <iostream>
- #include <FastLED.h>
- #define DATA_PIN D2
- #define NUM_LEDS 60
- CRGB leds[NUM_LEDS];
- const unsigned long LED_UPDATE_INTERVAL = 5000;
- const char *mqtt_server = "";
- const int mqtt_port = ;
- const char *mqtt_user = "";
- const char *mqtt_password = "";
- const char *mqtt_requesttopic = "garmin/requestStats";
- const char *mqtt_responsetopic = "garmin/responseStats";
- String responseMessage;
- JSONVar jsonMessage;
- WiFiClient espClient;
- PubSubClient client(espClient);
- class Steps
- {
- public:
- int StepGoal;
- int TotalSteps;
- float CalculatePercentage()
- {
- if (StepGoal != 0)
- {
- return static_cast<float>(TotalSteps) / static_cast<float>(StepGoal) * 100.0f;
- }
- else
- {
- Serial.println("Error: Division by zero.");
- return -1.0f;
- }
- };
- Steps(int stepGoal = 0, int totalSteps = 0)
- {
- StepGoal = stepGoal;
- totalSteps = totalSteps;
- };
- };
- Steps steps(0, 0);
- class StateObject {
- public:
- int AverageStress;
- int BodyBatteryLatest;
- int SleepScore;
- float RestStressPercentage;
- Steps StepsObject;
- bool StatsMode;
- unsigned long LastUpdateTime;
- int LastPercentage;
- CRGB LastColour;
- StateObject()
- {
- AverageStress = 0;
- BodyBatteryLatest = 0;
- SleepScore = 0;
- RestStressPercentage = 0;
- StepsObject = Steps(1, 0);
- StatsMode = false;
- LastUpdateTime = 0;
- LastPercentage = 0;
- LastColour = CRGB::Black;
- };
- };
- StateObject stateObject;
- class FastLedHelper
- {
- public:
- void initializeLEDs()
- {
- FastLED.addLeds<WS2812B, DATA_PIN, GRB>(leds, NUM_LEDS);
- }
- void updateLEDs(int percentage, CRGB colour, unsigned long &lastUpdateTime)
- {
- int ledsToLight = map(percentage, 0, 100, 0, NUM_LEDS);
- fill_solid(leds, NUM_LEDS, colour.Black);
- FastLED.show();
- delay(100);
- for (int i = NUM_LEDS - 1; i > NUM_LEDS - ledsToLight; i--)
- {
- leds[i] = colour;
- FastLED.show();
- delay(75);
- }
- }
- void ambientDisplay()
- {
- Serial.println("Starting Ambient Display");
- fill_solid(leds, NUM_LEDS, CRGB::Black);
- FastLED.show();
- for (int i = NUM_LEDS - 1; i >= 0; i--)
- {
- leds[i] = CRGB::Red;
- FastLED.show();
- delay(75);
- }
- }
- void displayStats(int percentage, CRGB colour)
- {
- if (percentage != stateObject.LastPercentage || colour != stateObject.LastColour)
- {
- updateLEDs(percentage, colour, stateObject.LastUpdateTime);
- }
- }
- } fastLedHelper;
- class MqttHelper
- {
- public:
- static void MapStateMessageToStateObject(JSONVar message)
- {
- if (message.hasOwnProperty("average_stress") &&
- message.hasOwnProperty("body_battery_latest") &&
- message.hasOwnProperty("sleep_score") &&
- message.hasOwnProperty("rest_stress_percentage") &&
- message.hasOwnProperty("step_goal") &&
- message.hasOwnProperty("total_steps"))
- {
- stateObject.AverageStress = message["average_stress"];
- stateObject.BodyBatteryLatest = message["body_battery_latest"];
- stateObject.SleepScore = message["sleep_score"];
- stateObject.RestStressPercentage = (double)message["rest_stress_percentage"];
- stateObject.StepsObject.StepGoal = message["step_goal"];
- stateObject.StepsObject.TotalSteps = message["total_steps"];
- stateObject.StatsMode = message["stats_mode"];
- }
- else
- {
- char newMessage[] = "Failed to map state message to state object, one or more parameters are missing";
- Serial.println(newMessage);
- throw std::invalid_argument(std::string(newMessage));
- }
- }
- static void callback(char* topic, byte* payload, unsigned int length) {
- for (unsigned int i = 0; i < length; i++) {
- responseMessage += (char)payload[i];
- }
- Serial.println(responseMessage);
- responseMessage.replace("False", "false");
- responseMessage.replace("True", "true");
- jsonMessage = JSON.parse(responseMessage);
- MqttHelper::MapStateMessageToStateObject(jsonMessage);
- responseMessage = "";
- jsonMessage = null;
- }
- static void requestStats() {
- client.publish(mqtt_requesttopic, "");
- }
- void setupMQTT()
- {
- client.setServer(mqtt_server, mqtt_port);
- client.setCallback(&callback);
- while (!client.connected())
- {
- Serial.print("Connecting to MQTT...");
- if (client.connect("ESP8266Client", mqtt_user, mqtt_password))
- {
- Serial.println("connected to MQTT, subscribed to ");
- Serial.println(mqtt_responsetopic);
- client.subscribe(mqtt_responsetopic);
- }
- else
- {
- Serial.print("failed, rc=");
- Serial.print(client.state());
- Serial.println(" try again in 5 seconds");
- delay(5000);
- }
- }
- }
- } mqttHelper;
- class FastLedTask : public Task
- {
- protected:
- void loop()
- {
- if (!stateObject.StatsMode)
- {
- fastLedHelper.ambientDisplay();
- MqttHelper::requestStats();
- delay(1000);
- }
- else
- {
- fastLedHelper.displayStats(stateObject.AverageStress, CRGB::Red);
- MqttHelper::requestStats();
- delay(10000);
- if (stateObject.StatsMode)
- {
- fastLedHelper.displayStats(stateObject.BodyBatteryLatest, CRGB::Blue);
- MqttHelper::requestStats();
- delay(10000);
- }
- if (stateObject.StatsMode)
- {
- fastLedHelper.displayStats(stateObject.SleepScore, CRGB::Orange);
- MqttHelper::requestStats();
- delay(10000);
- }
- if (stateObject.StatsMode)
- {
- fastLedHelper.displayStats(stateObject.RestStressPercentage, CRGB::Purple);
- MqttHelper::requestStats();
- delay(10000);
- }
- if (stateObject.StatsMode)
- {
- fastLedHelper.displayStats(stateObject.StepsObject.CalculatePercentage(), CRGB::Green);
- MqttHelper::requestStats();
- delay(10000);
- }
- }
- }
- private:
- time_t lastCheck;
- bool firstRun;
- } fastLedTask;
- class MqttTask : public Task
- {
- protected:
- void loop()
- {
- client.loop();
- delay(500);
- }
- private:
- time_t lastCheck;
- bool firstRun;
- } mqttTask;
- void setup()
- {
- Serial.begin(115200);
- setupWiFi();
- fastLedHelper.initializeLEDs();
- mqttHelper.setupMQTT();
- Scheduler.start(&mqttTask);
- Scheduler.start(&fastLedTask);
- Scheduler.begin();
- }
- void loop()
- {
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement