Skip to content

Commit

Permalink
Add a function to auto lookup our timezone using our public ip
Browse files Browse the repository at this point in the history
autoset the time based on local timezone
  • Loading branch information
jgstroud committed Oct 28, 2024
1 parent 6e6aee8 commit 2488343
Show file tree
Hide file tree
Showing 3 changed files with 47 additions and 3 deletions.
2 changes: 2 additions & 0 deletions src/ratgdo.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -256,6 +256,8 @@ void service_timer_loop()
unsigned long current_millis = millis();

#ifdef NTP_CLIENT
if (current_millis % 10000 == 0)
update_timezone();
if (enableNTP && clockSet && lastRebootAt == 0)
{
lastRebootAt = time(NULL) - (current_millis / 1000);
Expand Down
47 changes: 44 additions & 3 deletions src/utilities.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
#include "LittleFS.h"
#include "comms.h"
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>

#ifdef LEGACY_SETTINGS_MIGRATION
// Filenames for legacy user configuation, replaced by single file.
Expand Down Expand Up @@ -51,6 +52,49 @@ bool enableNTP = false;
unsigned long lastRebootAt = 0;
int32_t savedDoorUpdateAt = 0;

int get_tz()
{
WiFiClient client;
HTTPClient http;

if (http.begin(client, "http://ip-api.com/csv/?fields=timezone,offset"))
{ // HTTP

// start connection and send HTTP header
int httpCode = http.GET();

// httpCode will be negative on error
if (httpCode > 0)
{
if (httpCode == HTTP_CODE_OK || httpCode == HTTP_CODE_MOVED_PERMANENTLY)
{
String payload = http.getString();
char * timezone = (char*)payload.c_str();
char * ch = strchr(timezone, ',');
*ch = '\0';
ch++;
int offset = atoi(ch);
offset /= -3600;
sprintf(userConfig->timeZone, "%s;UTC%d", timezone, offset);
RINFO("Setting timezone to %s", userConfig->timeZone);
return offset;
}
}
http.end();
}
return 0;
}

void update_timezone()
{
if (clockSet)
return;
get_tz();
char *tz = strchr(userConfig->timeZone, ';');
// semicolon may separate continent/city from posix TZ string
configTime((tz) ? tz + 1 : userConfig->timeZone, NTP_SERVER);
}

void time_is_set(bool from_sntp)
{
RINFO("Clock set from NTP server: %d", from_sntp ? 1 : 0);
Expand Down Expand Up @@ -239,9 +283,6 @@ void load_all_config_settings()
if (enableNTP)
{
settimeofday_cb(time_is_set);
char *tz = strchr(userConfig->timeZone, ';');
// semicolon may separate continent/city from posix TZ string
configTime((tz) ? tz + 1 : userConfig->timeZone, NTP_SERVER);
}
#endif
syslogEn = userConfig->syslogEn;
Expand Down
1 change: 1 addition & 0 deletions src/utilities.h
Original file line number Diff line number Diff line change
Expand Up @@ -117,5 +117,6 @@ bool read_config_from_file();
void write_config_to_file();

void delete_file(const char *filename);
void update_timezone();

#endif

0 comments on commit 2488343

Please sign in to comment.