/*
ESP32 HTTPClient Messagebox
Copyright (C) 2022, Florian M.
*/
#include <WiFi.h>
#include <HTTPClient.h>
#include <ArduinoJson.h>
#include <SPI.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
const char* ssid = "Wokwi-GUEST";
const char* password = "";
#define BTN_PIN 5
#define LED_PIN 4
#define SCREEN_WIDTH 128 // OLED display width, in pixels
#define SCREEN_HEIGHT 64 // OLED display height, in pixels
// Declaration for an SSD1306 display connected to I2C (SDA, SCL pins)
#define OLED_RESET -1 // Reset pin # (or -1 if sharing Arduino reset pin)
#define SSD1306_NO_SPLASH
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);
const String url = "https://mbox-9a811-default-rtdb.europe-west1.firebasedatabase.app/messages.json?orderBy=\"date\"&startAt=3&endAt=400000000000&limitToLast=1";
String getJoke() {
HTTPClient http;
http.useHTTP10(true);
http.begin(url);
http.GET();
String result = http.getString();
DynamicJsonDocument doc(2048);
DeserializationError error = deserializeJson(doc, result);
// Test if parsing succeeds.
if (error) {
Serial.print("deserializeJson() failed: ");
Serial.println(error.c_str());
return "<error>";
}
String msg = doc["msg"].as<String>();
//if (msg == NULL) {
Serial.println("HTTP GET failed: ");
Serial.println(result);
//}
http.end();
return msg;
}
void nextJoke() {
display.clearDisplay();
display.setCursor(0,0); // Start at top-left corner
//display.println(F("Chargement du message..."));
String joke = getJoke();
display.println(joke);
display.display();
}
void setup() {
Serial.begin(115200);
pinMode(BTN_PIN, INPUT_PULLUP);
pinMode(LED_PIN, OUTPUT);
WiFi.begin(ssid, password, 6);
// SSD1306_SWITCHCAPVCC = generate display voltage from 3.3V internally
if(!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) {
Serial.println(F("SSD1306 allocation failed"));
for(;;); // Don't proceed, loop forever
}
display.clearDisplay();
display.setCursor(0,0); // Start at top-left corner
display.setTextSize(1); // Normal 1:1 pixel scale
display.setTextColor(WHITE); // Draw white text
display.println(F("Connection au WiFi"));
while (WiFi.status() != WL_CONNECTED) {
delay(100);
display.print(F("."));
}
display.println(F("OK ! IP="));
display.println(WiFi.localIP());
display.display();
nextJoke();
}
void loop() {
if (digitalRead(BTN_PIN) == LOW) {
nextJoke();
}
delay(100);
// LED
digitalWrite(LED_PIN, HIGH);
delay(500);
digitalWrite(LED_PIN, LOW);
delay(500);
}