Salve a tutti,
vi è mai capitato che OTA non funzioni ?
Allora se lo provo da solo non ci sono problemi, funziona benissimo, ma se lo inserisco nel mio codice non c'è verso di farlo funzionare.
Vi posto il codice OTA compreso:
#include "Credentials.h"
#include <WiFi.h>
#include <ESPmDNS.h>
#include <MySQL_Generic.h>
#include <WiFiClient.h>
#include <WiFiUdp.h>
#include <NTPClient.h>
#include <ArduinoOTA.h>
#define RX_PIN 8
#define TX_PIN 9
#define LED_RED 3
#define LED_GREEN 4
#define LED_WHITE 19
#define MYSQL_DEBUG_PORT Serial
#define _MYSQL_LOGLEVEL_ 0
IPAddress server(10,20,1,21); // Server database (this is my setup you use your database server IP)
uint16_t server_port = 3306; // is the 3306 standard port (idem)
WiFiUDP ntpUDP; // Define NTP Client to get time
NTPClient timeClient(ntpUDP);
// Replace with your network credentials
const char* host = "Meteo";
const char* ssid = "MyHome"; // Input your wifi network name
const char* pass = "Mypassword"; // Input your wifi password
const char default_database[] = "meteo"; // my setup
const char default_table[] = "meteo"; // my setup
const char* ntpServer = "it.pool.ntp.org"; // my setup
const long gmtOffset_sec = 0; // my setup
const int daylightOffset_sec = 3600; // my setup
String Latitude = "41.353333"; // my setup
String Longitude = "19.456667"; // my setup
String elevation = "5.0"; // my setup
String field1,field2,field3,field4,field5,field6,field7,field8,field9,field10,Insert_Data,Data,postStr;
// Thingspeak Write API
const char* server1 = "api.thingspeak.com";
const char* api_key = "123456789012121"; // API write key
char created_at[28];
// Base query
String INSERT_SQL = "INSERT INTO meteo.meteo (created_at,field1,field2,field3,field4,field5,field6,field7,field8,field9,field10,latitude,longitude,elevation) VALUES (";
MySQL_Connection conn((Client *)&client);
MySQL_Query *query_mem;
/////////////////////////////////////////// SETUP
void setup() {
Serial.begin(115200);
delay(1500);
while (!Serial && millis() < 2000); // wait for serial port to connect
if (Serial) {
Serial.println("Serial OK");
}
// Begin WiFi section
MYSQL_DISPLAY1("Connecting to", ssid);
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, pass);
while (WiFi.waitForConnectResult() != WL_CONNECTED) {
Serial.println("Connection Failed! Rebooting...");
delay(5000);
ESP.restart();
}
//*********************************************************************** OTA WEB START
ArduinoOTA
.onStart([]() {
String type;
if (ArduinoOTA.getCommand() == U_FLASH)
type = "sketch";
else // U_SPIFFS
type = "filesystem";
// NOTE: if updating SPIFFS this would be the place to unmount SPIFFS using SPIFFS.end()
Serial.println("Start updating " + type);
})
.onEnd([]() {
Serial.println("\nEnd");
})
.onProgress([](unsigned int progress, unsigned int total) {
Serial.printf("Progress: %u%%\r", (progress / (total / 100)));
})
.onError([](ota_error_t error) {
Serial.printf("Error[%u]: ", error);
if (error == OTA_AUTH_ERROR) Serial.println("Auth Failed");
else if (error == OTA_BEGIN_ERROR) Serial.println("Begin Failed");
else if (error == OTA_CONNECT_ERROR) Serial.println("Connect Failed");
else if (error == OTA_RECEIVE_ERROR) Serial.println("Receive Failed");
else if (error == OTA_END_ERROR) Serial.println("End Failed");
});
ArduinoOTA.begin();
//*********************************************************************** OTA WEB END
Serial1.begin(9600, SERIAL_8N1, RX_PIN, TX_PIN); // Serial port to HC12
delay(1500);
while (!Serial1 && millis() < 2000); // wait for serial port to connect
if (Serial1) {
Serial.println("Serial 1 OK");
Serial1.flush();
}
pinMode(LED_GREEN, OUTPUT); // Init OFF
digitalWrite(LED_GREEN, LOW); // INIT OFF
pinMode(LED_RED, OUTPUT); // Init OFF
digitalWrite(LED_RED, LOW); // INIT OFF
pinMode(LED_WHITE, OUTPUT); // Init OFF
digitalWrite(LED_WHITE, LOW); // INIT OFF
// Init and get the time
configTime(gmtOffset_sec, daylightOffset_sec, ntpServer);
MYSQL_DISPLAY1("\nStarting Basic_Insert_ESP on", ARDUINO_BOARD);
MYSQL_DISPLAY(MYSQL_MARIADB_GENERIC_VERSION);
// print out info about the connection:
MYSQL_DISPLAY1("Connected to network. My IP address is:", WiFi.localIP());
MYSQL_DISPLAY3("Connecting to SQL Server @", server, ", Port =", server_port);
MYSQL_DISPLAY5("User =", user, ", PW =", password, ", DB =", default_database);
// For ThingSpeak
if(!MDNS.begin("METEO")) {
Serial.println("Error starting mDNS");
return;
}
MDNS.addService("Meteo", "tcp", 80);
}
/////////////////////////////////////////// Delay function
void millisDelay( long int delayTime){
long int start_time = millis();
while ( millis() - start_time < delayTime) ;
}
/////////////////////////////////////////// Build Localtime field
void printLocalTime(){
timeClient.update();
struct tm timeinfo;
if ( !getLocalTime(&timeinfo )) {
Serial.println("Failed to obtain time");
return;
}
strftime( created_at, 28, "'%Y-%m-%dT%H:%M:%S+00:00'", &timeinfo ); //+ or - then 00:00 indicate delta time from UCT
}
/////////////////////////////////////////// Insert Record
void runInsert() {
// Initiate the query class instance
MySQL_Query query_mem = MySQL_Query(&conn);
if (conn.connected()) {
if ( !query_mem.execute(Insert_Data.c_str()) ) {
MYSQL_DISPLAY("Insert error");
} else {
MYSQL_DISPLAY("Meteo Data Inserted...");
}
} else {
MYSQL_DISPLAY("Disconnected from Server. Can't insert.");
}
}
/////////////////////////////////////////// SEND TO THINGSPEAK
void Send_data() {
// Send data to ThingSpeak
WiFiClient client;
if (client.connect(server1,80)) {
Serial.println("Connect to ThingSpeak - OK");
Serial.println("");
String postStr = "";
postStr+="GET /update?api_key=";
postStr+=api_key;
postStr+=Data.substring(0,Data.length() - 1);
postStr+=" HTTP/1.1\r\nHost: a.c.d\r\nConnection: close\r\n\r\n";
postStr+="";
client.print(postStr);
//Serial.println(postStr);
}
//Serial.println(postStr);
while(client.available()) {
String line = client.readStringUntil('r');
Serial.print(line);
}
}
/////////////////////////////////////////// LOOP
void loop() {
ArduinoOTA.handle();
// Send data to ThingSpeak
if (Serial1.available() > 0) { // If HC-12 has data
Data = Serial1.readStringUntil('\n');
// Check that the data are for ThingSpeak
if (Data.substring(5,11) == "field1") {
//Serial.println(Data.substring(5,11));
digitalWrite(LED_GREEN, HIGH); // INIT ON
Send_data();
// millisDelay(500);
Serial.println("Data in ThingSpeak inserted...");
Serial.println("");
} else {
// Send data to internal database
digitalWrite(LED_RED, HIGH); // INIT ON
printLocalTime(); // Print Time
Insert_Data = INSERT_SQL; // query construction
Insert_Data += created_at;
Insert_Data += ",";
Insert_Data += Data;
Insert_Data += ",'";
Insert_Data += Latitude;
Insert_Data += "','";
Insert_Data += Longitude;
Insert_Data += "','";
Insert_Data += elevation;
Insert_Data += "')";
MYSQL_DISPLAY("Connecting to database...");
if (conn.connectNonBlocking(server, server_port, user, password) != RESULT_FAIL) {
// millisDelay(500);
runInsert();
conn.close(); // close the connection
} else {
MYSQL_DISPLAY("\nConnect failed. Trying again on next iteration.");
}
}
Serial1.flush();
}
digitalWrite(LED_GREEN, LOW); // LED OFF
digitalWrite(LED_RED, LOW); // LED OFF
}
//END
Io ritengo di averlo inseirto nel modo corretto, ma forse mi sbaglio...