Hi all,
I’ve a problem with indexOf function when I parse a html.
The code is working properly but when I add a gettime function, indexOf doesn’t work and it cannot find the string, It make me crazy because there is no sense and I’ve also tried several times but nothing.
Do you know if there are some problem with http request? or gettime function?
Thanks.
#include "Timer.h"
#define CAYENNE_PRINT Serial // Comment this out to disable prints and save space
#include <CayenneEthernet.h>
#define VIRTUAL_PIN 1
#define VIRTUAL_PIN2 2
#define RELAY_DIGITAL_PIN 4
#include <EthernetUdp.h>
Timer t;
unsigned int localPort = 80; // Puerto local para escuchar UDP
const char* server = "afeelink.com"; // server's address
const char* resource = "/tado.php";
const unsigned long HTTP_TIMEOUT = 4000; // max respone time from server
IPAddress timeServer(130,206,3,166);
int retardo = 2 ; // (tiempo (s.) entre visionados)
int StatusTado,StatusSTAY,mark;
String STAYHOME;
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
IPAddress ip(192, 168, 0, 177);// Set the static IP address to use if the DHCP fails to assign
EthernetClient cliente;
const int NTP_PACKET_SIZE= 48; // La hora son los primeros 48 bytes del mensaje
byte packetBuffer[ NTP_PACKET_SIZE]; // buffer para los paquetes
EthernetUDP Udp; // Una instancia de UDP para enviar y recibir mensajes
// Cayenne authentication token. This should be obtained from the Cayenne Dashboard.
char token[] = "xxxxxx";
void setup()
{
// set digital pin to output
pinMode(RELAY_DIGITAL_PIN, OUTPUT);
initEthernet();
Serial.begin(9600);
Cayenne.begin(token);
Udp.begin(localPort);
t.every(10000, Thttp);
//t.every(6000, gettime);
}
void initEthernet() {
byte mac[] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED};
if (!Ethernet.begin(mac)) {
Serial.println("Failed to configure Ethernet");
return;
}
Serial.println("Ethernet ready");
delay(1000);
}
int actialarma()
{
digitalWrite(4, LOW); // turn the LED off by making the voltage LOW
delay(1000); // wait for a second
digitalWrite(4, HIGH); // turn the LED on (HIGH is the voltage level)
delay(1000); // wait for a second
}
CAYENNE_IN(VIRTUAL_PIN)
{
// get value sent from dashboard
int currentValue = getValue.asInt(); // 0 to 1
// assuming you wire your relay as normally open
if (currentValue == 0) {
actialarma();
}
}
CAYENNE_OUT(V3)
{
Cayenne.virtualWrite(V3, StatusTado);
}
CAYENNE_OUT(V5)
{
Cayenne.virtualWrite(V5, StatusSTAY);
}
void loop()
{
Cayenne.run();
t.update();
}
int Thttp()
{
if (connect(server)) {
if (sendRequest(server, resource) && skipResponseHeaders()) {
readReponseContent();
}
disconnect();
}
}
bool gettime()
{
sendNTPpacket(timeServer); // Enviar unaa peticion al servidor NTP
delay(1000);
if ( Udp.parsePacket() ) {
Udp.read(packetBuffer,NTP_PACKET_SIZE); // Leemos el paquete
// La hora empieza en el byte 40 de la respuesta y es de 4 bytes o 2 words
// Hay que extraer ambas word:
unsigned long highWord = word(packetBuffer[40], packetBuffer[41]);
unsigned long lowWord = word(packetBuffer[42], packetBuffer[43]);
unsigned long secsSince1900 = highWord << 16 | lowWord;
const unsigned long seventyYears = 2208988800UL;
unsigned long epoch = secsSince1900 - seventyYears;
Serial.print(((epoch % 86400L) / 3600)+1); // Horas (86400 segundos por dia)
Serial.print(':');
if ( ((epoch % 3600) / 60) < 10 ) {
// Añadir un 0 en los primeros 9 minutos
Serial.print('0');
}
Serial.print((epoch % 3600) / 60); // Minutos:
Serial.print(':');
if ( (epoch % 60) < 10 ) {
// Añadir un 0 en los primeros 9 minutos
Serial.print('0');
}
Serial.println(epoch %60); // Segundos
}
}
bool takeReading()
{
connect(server);
if (sendRequest(server, resource) && skipResponseHeaders())
{
readReponseContent() ;
}
disconnect();
}
// Open connection to the HTTP server
bool connect(const char* hostName) {
Serial.print("Connect to ");
Serial.println(hostName);
bool ok = cliente.connect(hostName, 80);
Serial.println(ok ? "Connected" : "Connection Failed!");
return ok;
}
// Send the HTTP GET request to the server
bool sendRequest(const char* host, const char* resource) {
cliente.print("GET ");
cliente.print(resource);
cliente.println(" HTTP/1.0");
cliente.print("Host: ");
cliente.println(host);
cliente.println("Connection: close");
cliente.println();
return true;
}
// Skip HTTP headers so that we are at the beginning of the response's body
bool skipResponseHeaders() {
// HTTP headers end with an empty line
char endOfHeaders[] = "null";
cliente.setTimeout(HTTP_TIMEOUT);
bool ok = cliente.find(endOfHeaders);
if (!ok) {
Serial.println("No response or invalid response!");
}
return ok;
}
bool readReponseContent() {
String s = cliente.readString();
Serial.println(s);
int heatingOn = s.indexOf("heatingOn");
Serial.println(s.substring(heatingOn+11,heatingOn+15));
int radar = s.indexOf("autoOperation");
String StringheatingOn = (s.substring(heatingOn+11,heatingOn+15));
String STAYHOME = (s.substring(radar+16,radar+20));
Serial.println(STAYHOME);
if (StringheatingOn == "true")
{
StatusTado=1;
}
else if (StringheatingOn == "fals")
{
StatusTado=0;
}
if (STAYHOME == "HOME")
{
StatusSTAY=1;
}
else if (STAYHOME == "AWAY")
{
StatusSTAY=0;
}
}
void disconnect() {
Serial.println("Disconnect");
cliente.stop();
}
unsigned long sendNTPpacket(IPAddress& address)
{
// set all bytes in the buffer to 0
memset(packetBuffer, 0, NTP_PACKET_SIZE);
// Initialize values needed to form NTP request
// (see URL above for details on the packets)
packetBuffer[0] = 0b11100011; // LI, Version, Mode
packetBuffer[1] = 0; // Stratum, or type of clock
packetBuffer[2] = 6; // Polling Interval
packetBuffer[3] = 0xEC; // Peer Clock Precision
// 8 bytes of zero for Root Delay & Root Dispersion
packetBuffer[12] = 49;
packetBuffer[13] = 0x4E;
packetBuffer[14] = 49;
packetBuffer[15] = 52;
// all NTP fields have been given values, now
// you can send a packet requesting a timestamp:
Udp.beginPacket(address, 123); //NTP requests are to port 123
Udp.write(packetBuffer,NTP_PACKET_SIZE);
Udp.endPacket();
}