-->
Page 1 of 3

Can't set time despite sending ESP8266 seconds since epoch

PostPosted: Mon Nov 22, 2021 8:35 am
by Bill2k
So I'm designing a clock sketch using an ESP8266. I programmed a webpage that figures out the seconds since epoch and sends it to the esp8266 without any issue. But immediately after receiving the string containing the number of seconds since epoch, that number gets screwed up, which screws up setting the proper time. The following is my code that isn't working as expected. Ill try and include all relevant code.

Code: Select allsettimeofday_cb(time_is_set);  // This function gets called every time the time is set

// Part of function that handles the javascript derived seconds since epoch
else if (server.argName(i) == "synctime") {
        char buff[20];
        server.arg("synctime").toCharArray(buff, sizeof(buff) - 1);
        Serial.print("Time sent from browser: "); Serial.println(buff);
        time_t rtc = (uint32_t)buff;
        timeval tv = { rtc, 0 };
        settimeofday(&tv, nullptr);
}

void time_is_set(bool from_sntp) {
  lastTimeSet = time(nullptr);

if (from_sntp) {
    strcpy(whoSetTime, "SNTP");
  }
  else {
    strcpy(whoSetTime, "USER");
  }

Serial.println((uint32_t)lastTimeSet);
  Serial.print(F("Time was set by ")); Serial.print(whoSetTime); Serial.print(F(" @ ")); Serial.println(ctime(&lastTimeSet));
}


The following is what gets sent to the Serial monitor.
Code: Select allTime sent from browser: 1637587376
1073741408
Time was set by USER @ Sat Jan 10 13:30:08 2004


Am I just converting the value wrong? Ive tried converting the number to all types of variables.

Any help is appreciated. Thanks for looking.

Re: Can't set time despite sending ESP8266 seconds since epo

PostPosted: Mon Nov 22, 2021 5:35 pm
by AcmeUK
Do you have a particular requirement to use a web page to send the seconds to your ESP?
Most people use one of the Network Time Protocol librarys to keep a clock accurate.

Have a look at This One

Re: Can't set time despite sending ESP8266 seconds since epo

PostPosted: Mon Nov 22, 2021 9:50 pm
by Bill2k
My sketch already has a function to get the time from an ntp server. I wanted to add this method to set the time in case the clock gets mounted in an area without wifi. It was a 'plan b'.

I think I'm gonna try to do something with mktime to see if that accomplishes what I want.

Re: Can't set time despite sending ESP8266 seconds since epo

PostPosted: Tue Nov 23, 2021 1:05 am
by JurajA
convert the received characters to a number with atol or similar.

@AcmeUK, esp8266 has NTP support in SDK. there is no need for Arduino library to get the time