#include <WiFi.h>
#include <HTTPClient.h>
#include <ArduinoJson.h>
#include <Adafruit_GFX.h>
#include <Adafruit_ILI9341.h>
const char* ssid = "Wokwi-GUEST";
const char* password = "";
#define TFT_DC 2
#define TFT_CS 15
Adafruit_ILI9341 tft = Adafruit_ILI9341(TFT_CS, TFT_DC);
const String url = "https://api.porssisahko.net/v1/latest-prices.json";
struct PriceInfo {
int price;
String startDate; // Keep the full date string for extracting the hour
String endDate;
};
std::vector<PriceInfo> getElectricityPrices() {
std::vector<PriceInfo> pricesList;
HTTPClient http;
http.useHTTP10(true);
http.begin(url);
http.GET();
String result = http.getString();
DynamicJsonDocument doc(8192);
DeserializationError error = deserializeJson(doc, result);
if (error) {
Serial.print("deserializeJson() failed: ");
Serial.println(error.c_str());
return pricesList;
}
JsonArray prices = doc["prices"].as<JsonArray>();
for (JsonObject priceInfo : prices) {
double price = priceInfo["price"].as<double>();
int roundedPrice = static_cast<int>(round(price));
String startDate = priceInfo["startDate"].as<String>();
String endDate = priceInfo["endDate"].as<String>();
pricesList.push_back({roundedPrice, startDate, endDate});
}
http.end();
return pricesList;
}
void displayBar(int x, int height, int price, const String& time) {
int barWidth = 20;
tft.fillRect(x, tft.height() - height - 30, barWidth, height, ILI9341_GREEN); // Lift bars higher
tft.setCursor(x, tft.height() - height - 50);
tft.print(price); // Display price at the top of each bar
// Display time below each bar
tft.setCursor(x, tft.height() - 20);
tft.print(time);
}
void displayPrices() {
std::vector<PriceInfo> prices = getElectricityPrices();
int maxPrice = 0;
int minPrice = INT_MAX;
for (const auto& priceInfo : prices) {
if (priceInfo.price > maxPrice) {
maxPrice = priceInfo.price;
}
if (priceInfo.price < minPrice) {
minPrice = priceInfo.price;
}
}
tft.fillScreen(ILI9341_BLACK);
tft.setTextColor(ILI9341_WHITE);
tft.setTextSize(1);
int x = 0;
for (const auto& priceInfo : prices) {
int barHeight = (int)((priceInfo.price / (double)maxPrice) * (tft.height() - 50)); // Adjust height calculation
// Extract hour from the startDate
int hourIndex = priceInfo.startDate.indexOf('T') + 1;
String hourString = priceInfo.startDate.substring(hourIndex, hourIndex + 2);
displayBar(x, barHeight, priceInfo.price, hourString);
x += 30;
}
}
void setup() {
WiFi.begin(ssid, password, 6);
tft.begin();
tft.setRotation(1);
tft.setTextColor(ILI9341_WHITE);
tft.setTextSize(2);
tft.print("Connecting to WiFi");
while (WiFi.status() != WL_CONNECTED) {
delay(100);
tft.print(".");
}
tft.print("\nOK! IP=");
tft.println(WiFi.localIP());
displayPrices();
}
void loop() {
delay(10000); // Update every 10 seconds
displayPrices(); // Redraw the screen with updated prices
}