Here is full code:
//INPUT
// I15 - D15 start stand alone
// I4 - D4 start homepage data
// I17 - TX2
//OUTPUT
// O12 - D12 horn (relay)
// O27 - D27 device is on and ready after setup (red)
// O25 - D25 stand alone running (green)
// O32 - D32 kapsejlads data running (blue)
//når den ikke kører, så skal den hver 5 s hente Kap data, dette sikrer at data altid er opdateret.
#include <WiFi.h> // Replace with WiFi.h for ESP32
#include <WebServer.h> // Replace with WebServer.h for ESP32
#include <AutoConnect.h> // For AutoConnect Wifi
#include <time.h> // For NTP time
#include <ArduinoJSON.h> // For reading JSON data
//For display
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
//DISPLAY
#define SCREEN_WIDTH 128 // OLED display width, in pixels
#define SCREEN_HEIGHT 32 // OLED display height, in pixels
// Declaration for an SSD1306 display connected to I2C (SDA, SCL pins)
// The pins for I2C are defined by the Wire-library.
// On an arduino UNO: A4(SDA), A5(SCL)
// On an arduino MEGA 2560: 20(SDA), 21(SCL)
// On an arduino LEONARDO: 2(SDA), 3(SCL), ...
#define OLED_RESET 4 // Reset pin # (or -1 if sharing Arduino reset pin)
#define SCREEN_ADDRESS 0x3C ///< See datasheet for Address; 0x3D for 128x64, 0x3C for 128x32
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);
//DISPLAY
int x,minX;
IPAddress ip;
//OUTPUTS
int HORN=12; //Output for horn
int LED_ON=27; //Output for LED, device is on
int LED_AUTO_ALONE=25; //Output for LED, program in stand alone
int LED_AUTO_DATA=32; //Output for LED, program running homepage data
//INPUTS
int START_ALONE=15; //Input to start stand alone
int START_DATA=16; //Input to start with homepage data
int START_TEST=18; //Input to start with homepage data
int BUTTON_START_ALONE=LOW;
int BUTTON_START_DATA=LOW;
int BUTTON_START_TEST=LOW;
//SETABLE VARIABLES FROM WEB
int KLUBID=13;
int ALONE_BETWEEN_START=5;
int ALONE_NUMBER_OF_STARTS=10;
int ALONE_STARTTIME=8;
int HORN_SHORTTIME=1000;
int HORN_LONGTIME=3000;
int DATA_BETWEEN_START=5;
int DATA_NUMBER_OF_STARTS=10;
int DATA_STARTTIME=8;
//CONST TO RUN PROGRAM
int HORN_STARTUPTIME=50; //Horn time during startup
int BLINKTIME=500; //Time for blinking
int STARTDELAY=0; //
int BETWEEN_START_DELAY=0;
int STARTNUM=0;
int FIVEMIN=0; //Time elapsed by 5 min
int FOURMIN=1*60*1000; //Time elapsed by 4 min
int ONEMIN=4*60*1000; //Time elapsed by 1 min
int ZEROMIN=5*60*1000; //Time elapsed by start
//AUTOCONNECT
WebServer Server; // Replace with WebServer for ESP32
AutoConnect Portal(Server);
AutoConnectConfig Config;
//Webside fra ESP
void rootPage() {
char content[] = "Kapsejlads.nu - HORN";
Server.send(200, "text/plain", content);
}
//SKRIV NTP TID
void printLocalTime(){
struct tm timeinfo; //skriv tiden til timeinfo som tidskode
if(!getLocalTime(&timeinfo)){ //kontroller om tid er modtaget
Serial.println("Failed to obtain time");
return;
}
Serial.println(&timeinfo, "%A, %B %d %Y %H:%M:%S"); //skriv tid til monitor
}
//SÆT TIDSZONE
void setTimezone(String timezone){
Serial.printf(" Setting Timezone to %s\n",timezone.c_str()); //skriv til monitor
setenv("TZ",timezone.c_str(),1); // Now adjust the TZ. Clock settings are adjusted to show the new local time. Indstil til CPH
tzset(); //indstil tidszonen
}
//HENT NTP TID
void initTime(String timezone){
struct tm timeinfo; //skriv tiden til timeinfo
Serial.println("Setting up time");
configTime(0, 0, "europe.pool.ntp.org"); // First connect to NTP server, with 0 TZ offset. Ingen tidszone eller sommertidskorrektion
if(!getLocalTime(&timeinfo)){ //hvis NTP ikke kan hentes
Serial.println(" Failed to obtain time");
return;
}
Serial.println(" Got the time from NTP"); //NTP tid er hentet
// Now we can set the real timezone
setTimezone(timezone); //sæt tidszonen og dermed evt. sommertid
}
void setup() {
//DISPLAY
//Input Output
pinMode(START_ALONE, INPUT);
pinMode(START_DATA, INPUT);
pinMode(START_TEST, INPUT);
pinMode(HORN,OUTPUT);
pinMode(LED_ON,OUTPUT);
pinMode(LED_AUTO_ALONE,OUTPUT);
pinMode(LED_AUTO_DATA,OUTPUT);
// SSD1306_SWITCHCAPVCC = generate display voltage from 3.3V internally
display.begin(SSD1306_SWITCHCAPVCC, SCREEN_ADDRESS);
//delay(2000); // Pause for 2 seconds
display.setTextSize(1); //font størrelse
display.setTextColor(WHITE); //skrift farve
display.setTextWrap(false); //skift ikke linje
display.clearDisplay(); //ryd display
display.setCursor(0, 10); //start position
display.print("Kapsejlads.nu"); //sæt tekst
display.setCursor(0, 20); //ny position
display.print("by Frank Larsen"); //sæt tekst
display.display(); //skriv til display
x=display.width(); //sæt x = display bredde.
//AUTOCONNECT
Serial.begin(115200);
Serial.println();
Config.apid = "Kapsejlads-horn";
Config.psk = "Kapsejlads.nu";
Portal.config(Config);
//FORBIND WIFI
Server.on("/", rootPage);
if (Portal.begin()) {
Serial.println("WiFi connected: " + WiFi.localIP().toString());
}
//hent NTP tid
delay(500); //vent 0,5 s, så wifi er klar
initTime("CET-1CEST,M3.5.0,M10.5.0/3"); //hent tid for københavn, https://github.com/nayarsystems/posix_tz_db/blob/master/zones.csv
//hent klub navn
String serverName = "https://kapsejlads.nu/hide-horn-esp.php";
if(WiFi.status()== WL_CONNECTED){
//connect to homepage
WiFiClientSecure client; //Use https
HTTPClient http;
client.setInsecure(); //Get data without certificate
/* String serverPath = serverName + "?klubid=13"; //Set server and request data
Serial.println(serverPath); //Print server path
//GET CLUB NAME
http.begin(client, serverPath.c_str()); //Begin request
int httpResponseCode = http.GET(); //Get data
if (httpResponseCode>0) { //If http runs OK
Serial.print("HTTP Response code: "); //Print http code
Serial.println(httpResponseCode);
String payload1 = http.getString(); //Read http response
Serial.println(payload1); //Print http response
}
else {
Serial.print("Error code: "); //Else print http error code
Serial.println(httpResponseCode);
}
//GET HORN SETTINGS STRING
serverPath = serverName + "?klubid=13&hornset=J"; //Set server and request data
Serial.println(serverPath); //Print server path
http.begin(client, serverPath.c_str()); //Begin request
httpResponseCode = http.GET(); //Get data
if (httpResponseCode>0) { //If http runs OK
Serial.print("HTTP Response code: "); //Print http code
Serial.println(httpResponseCode);
String payload2 = http.getString(); //Read http response
Serial.println(payload2); //Print http response
}
else {
Serial.print("Error code: "); //Else print http error code
Serial.println(httpResponseCode);
}
// Free resources
http.end(); //End http request
//GET CLUB NAME AND HORN SETTINGS
String serverPath3 = serverName + "?klubid=13"; //Set server and request data
String serverPath4 = serverName + "?klubid=13&hornset=J"; //Set server and request data
http.begin(client, serverPath3.c_str()); //Begin request
httpResponseCode = http.GET(); //Get data
if (httpResponseCode>0) { //If http runs OK
String CLUBNAME = http.getString(); //Read http response
Serial.println(CLUBNAME); //Print http response
http.begin(client, serverPath4.c_str()); //Begin request
String payload4= http.getString(); //Read http response
Serial.println(payload4); //Print http response
}
http.end(); //End http request
*/
//GET HORN_SETTINGS DATA FORMATTED AS JSON
String serverPath5 = serverName + "?klubid=13&hornset=J&json=J"; //Set server and request data
Serial.println(serverPath5);
http.begin(client, serverPath5.c_str()); //Begin request
int httpResponseCode = http.GET(); //Get data
if (httpResponseCode>0) { //If http runs OK
Serial.print("JSON HTTP Response code: "); //Print http code
Serial.println(httpResponseCode);
String payload5 = http.getString(); //Read http response
Serial.println(payload5); //Print http response
//Format JSON data
char json[500];
payload5.replace(" ","");
payload5.replace("\n","");
payload5.trim();
payload5.remove(0,1);
payload5.toCharArray(json, 500);
Serial.println(payload5);
StaticJsonDocument<512> doc;
DeserializationError error = deserializeJson(doc, payload5);
if (error) {
Serial.print("deserializeJson() failed: ");
Serial.println(error.c_str());
return;
}
for (JsonObject item : doc.as<JsonArray>()) {
const char* ID = item["ID"]; // "1", "2"
const char* KLUBID = item["KLUBID"]; // "13", "10"
const char* TIDMLSTART = item["TIDMLSTART"]; // "5", "6"
const char* ANTALSTART = item["ANTALSTART"]; // "10", "10"
const char* MINFORSTART = item["MINFORSTART"]; // "8", "8"
const char* KORTHORN = item["KORTHORN"]; // "1000", "1000"
const char* LANGHORN = item["LANGHORN"]; // "3000", "3000"
const char* TESTHORN = item["TESTHORN"]; // "50", "50"
}
String KLUBID1 = doc[F("KLUBID")][0].as<String>();
String KLUBID2 = doc[F("KLUBID")][1].as<String>();
Serial.println(KLUBID1);
Serial.println(KLUBID2);
/*
StaticJsonDocument<1000> doc;
deserializeJson(doc, json);
String ID1 = doc["ID"][0];
String KLUBID1 = doc[0]["KLUBID"];
String ID2 = doc[1]["ID"];
String KLUBID2 = doc[1]["KLUBID"];
Serial.println(ID1);
Serial.println(KLUBID1);
Serial.println(ID2);
Serial.println(KLUBID1);
//Set horn variables and print them
ALONE_BETWEEN_START=doc["TIDMLSTART"];
DATA_BETWEEN_START=doc["TIDMLSTART"];
ALONE_NUMBER_OF_STARTS=doc["ANTALSTART"];
DATA_NUMBER_OF_STARTS=doc["ANTALSTART"];
ALONE_STARTTIME=doc["MINFORSTART"];
DATA_STARTTIME=doc["MINFORSTART"];
HORN_SHORTTIME=doc["KORTHORN"];
HORN_LONGTIME=doc["LANGHORN"];
Serial.println("Time between start "+ String(ALONE_BETWEEN_START));
Serial.println("Number of starts "+ String(ALONE_NUMBER_OF_STARTS));
Serial.println("Activate time before start "+ String(ALONE_STARTTIME));
Serial.println("Horn short signal "+ String(HORN_SHORTTIME));
Serial.println("Horn long signal "+ String(HORN_LONGTIME));
//POST2
*/
}
else {
Serial.print("Error code: "); //Else print http error code
Serial.println(httpResponseCode);
}
}
else {
Serial.println("WiFi Disconnected");
}
}
void loop() {
//Show ESP homepage
Portal.handleClient();
//Get local time from ESP
struct tm timeinfo;
getLocalTime(&timeinfo);
//Read input
BUTTON_START_ALONE = digitalRead(START_ALONE);
BUTTON_START_DATA = digitalRead(START_DATA);
BUTTON_START_TEST = digitalRead(START_TEST);
//Serial.print(BUTTON_START_ALONE);
//Serial.print(BUTTON_START_DATA);
//Serial.println(BUTTON_START_TEST);
//display rolling text
char message[]="Dette er min tekst"; //Text
//minX=-12*strlen(message); //Calculate length of text string
minX=-12*25; //Set string length to fixed size.
display.setTextSize(2); //Font size. Max is 3
display.clearDisplay(); //Clear the display
display.setCursor(x,10); //Set cursor in position
display.print(WiFi.localIP().toString()+" - "); //Put IP to display
display.print(&timeinfo, "%H:%M:%S"); //Put time to display
//display.print(message); //Display text
display.display(); //Show in display
x=x-1; //Move on display
if(x<minX)x=display.width();
//Serial.println(&timeinfo, "%A, %B %d %Y %H:%M:%S"); //Print time
}
And result:
WiFi connected: 192.168.1.118
Setting up time
Failed to obtain time
https://kapsejlads.nu/hide-horn-esp.php?klubid=13&hornset=J&json=J
JSON HTTP Response code: 200
[{"ID":"1","KLUBID":"13","TIDMLSTART":"5","ANTALSTART":"10","MINFORSTART":"8","KORTHORN":"1000","LANGHORN":"3000","TESTHORN":"50"},{"ID":"2","KLUBID":"10","TIDMLSTART":"6","ANTALSTART":"10","MINFORSTART":"8","KORTHORN":"1000","LANGHORN":"3000","TESTHORN":"50"}]
{"ID":"1","KLUBID":"13","TIDMLSTART":"5","ANTALSTART":"10","MINFORSTART":"8","KORTHORN":"1000","LANGHORN":"3000","TESTHORN":"50"},{"ID":"2","KLUBID":"10","TIDMLSTART":"6","ANTALSTART":"10","MINFORSTART":"8","KORTHORN":"1000","LANGHORN":"3000","TESTHORN":"50"}]
null
null