Hieromon / AutoConnect

An Arduino library for ESP8266/ESP32 WLAN configuration at runtime with the Web interface

Home Page:https://hieromon.github.io/AutoConnect/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Startup without network connection

Tipmanfrank opened this issue · comments

Discussed in #568

Originally posted by Tipmanfrank January 25, 2023
I have below code. When it comes to line 150 code stops until I have connected to a network. The rest of my Serial.print "OK" is not shown.

How can I change code, so I can startup without an internet connection? I must be able to start the ESP32 with and without network connection.

Code:
//After first load Båtomat must connect to Internet to have eeprom updated.

// 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 <EEPROM.h> // Save stand alone settings in eeprom
#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;

//EEPROM
#define EEPROM_SIZE 3 //3 values can be saved i eeprom

// 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);
}

// PRINT NTP TIME
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
}

// SET TIMEZONE
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
}

// GET NTP TIME FROM EUROPE
void initTime(String timezone) {
struct tm timeinfo; // write time to "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)) // If can't get NTP time
{
Serial.println(" Failed to obtain time");
return;
}
Serial.println(" Got the time from NTP"); // NTP has been received
// Now we can set the real timezone
setTimezone(timezone); // Set timezone
}

void setup() {
Serial.begin(115200);
Serial.println("SETUP START");

// 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);
Serial.println("I/O OK");

// AUTOCONNECT
Config.apid = "Kapsejlads-horn";
Config.psk = "Kapsejlads.nu";
Portal.config(Config);
Serial.println("AUTO CONNECT OK");

// SHOW AUTOCONNECT SCREEN
Server.on("/", rootPage);
if (Portal.begin()) {
Serial.println("WiFi connected: " + WiFi.localIP().toString());
}
Serial.println("ROOTPAGE OK");

delay(1000); // Wait 1 s until wifi is ready
if (WiFi.status() == WL_CONNECTED) {
// GET NTP TIME
initTime("CET-1CEST,M3.5.0,M10.5.0/3"); // Get time for Copenhagen, https://github.com/nayarsystems/posix_tz_db/blob/master/zones.csv
Serial.print("NTP OK");

// SET SERVER NAME AND FILE
String serverName = "https://kapsejlads.nu/hide-horn-esp.php";
Serial.print("SERVERNAME OK");

// CONNECT TO KAPSEJLADS HOMEPAGE 
WiFiClientSecure client;  // Use https
HTTPClient http; 
client.setInsecure();  // Get data without certificate
Serial.print("KAPSEJLADS CONNECT OK");

/*      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

  //https://arduinojson.org/ --> Assistent menu, to generate json code without nested elements
  //StaticJsonDocument<512> doc; // Define statid JSON
  DynamicJsonDocument doc(2048); // Define dynamic JSON
  DeserializationError error = deserializeJson(doc, payload5);
  if (error) {
    Serial.print("deserializeJson() failed: ");
    Serial.println(error.c_str());
    return;
  }
  JsonArray nested = doc.as<JsonArray>();

  String KLUBID1 = nested[0][F("KLUBID")].as<String>();
  String KLUBID2 = nested[1][F("KLUBID")].as<String>();
  int KLUBID3 = KLUBID2.toInt();
  String TIDMLSTART1 = nested[0][F("TIDMLSTART")].as<String>();
  String TIDMLSTART2 = nested[1][F("TIDMLSTART")].as<String>();
  Serial.println(KLUBID1);
  Serial.println(KLUBID2);
  Serial.println(KLUBID3);
  Serial.println(TIDMLSTART1);
  Serial.println(TIDMLSTART2);

  int i = 0;
  int arrayLength = doc.size();
  Serial.print(arrayLength);
  while (i < arrayLength) {
    String KLUBID[i] = nested[i][F("KLUBID")].as<String>();
    Serial.print(KLUBID[i]);
    i++;
  }

  //GET HORN SETTING FROM WEB
  Serial.println("HORN SETTINGS OK");

  //SAVE HORNSETTINGS TO EEPROM
  //UDSKIFT VÆRDIER MED VARIABLE
  EEPROM.begin(EEPROM_SIZE);
  EEPROM.write(0, 5);   //Position 0 = 5 min between start
  EEPROM.write(1, 10);  //Position 1 = 10 starts
  EEPROM.write(2, 8);   //Position 2 = activate 8 min before start
  EEPROM.commit();
  Serial.println("EEPROM WRITTEN OK");




} else {
  Serial.print("Error code: ");  // Else print http error code
  Serial.println(httpResponseCode);
}

} else {
Serial.println("WiFi Disconnected");
}

//READ EEPROM DATA
EEPROM.begin(EEPROM_SIZE);
int ALONE_BETWEEN_START = EEPROM.read(0);
int ALONE_NUMBER_OF_STARTS = EEPROM.read(1);
int ALONE_STARTTIME = EEPROM.read(2);
Serial.println("ALONE_BETWEEN_START_EPROM= " + String(ALONE_BETWEEN_START));
Serial.println("ALONE_NUMBER_OF_STARTS_EPROM= " + String(ALONE_NUMBER_OF_STARTS));
Serial.println("ALONE_STARTTIME_EPROM= " + String(ALONE_STARTTIME));
Serial.println();
Serial.println("EEPROM READ OK");

//DISPLAY DATA
// 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.
Serial.println("DISPLAY OK");

}

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
}

It is multi post.