ntp address detection

This commit is contained in:
Patrick Haßel 2023-01-02 15:31:12 +01:00
parent d0bd19eb73
commit d3b730b9a3

View File

@ -59,6 +59,10 @@ void serial_read();
void wifi_loop(); void wifi_loop();
void ntp_setup();
uint32_t ip2int(const IPAddress &ip);
void web_index() { void web_index() {
server.setContentLength(CONTENT_LENGTH_UNKNOWN); server.setContentLength(CONTENT_LENGTH_UNKNOWN);
server.send(200, "text/html", ""); server.send(200, "text/html", "");
@ -172,9 +176,8 @@ void wifi_loop() {
if (!connected) { if (!connected) {
if (hasIp) { if (hasIp) {
connected = true; connected = true;
configTime(3600, 3600, WiFi.gatewayIP().toString().c_str());
Serial.printf("WiFi connected: %s\n", WiFi.localIP().toString().c_str()); Serial.printf("WiFi connected: %s\n", WiFi.localIP().toString().c_str());
yield(); ntp_setup();
} }
} else { } else {
if (!hasIp) { if (!hasIp) {
@ -184,6 +187,30 @@ void wifi_loop() {
} }
} }
uint32_t ip2int(const IPAddress &ip) {
return ((ip[0] * 256 + ip[1]) * 256 + ip[2]) * 256 + ip[3];
}
void ntp_setup() {
char calculatedGateway[16] = {0};
uint32_t local = ip2int(WiFi.localIP());
uint32_t netmask = ip2int(WiFi.subnetMask());
uint32_t gateway = local & netmask + 1;
snprintf(
calculatedGateway,
sizeof(calculatedGateway),
"%u.%u.%u.%u",
(gateway >> 24) & 0xFF,
(gateway >> 16) & 0xFF,
(gateway >> 8) & 0xFF,
(gateway >> 0) & 0xFF
);
sntp_set_time_sync_notification_cb(timeSyncCallback);
Serial.printf("configTime(%s / %s / %s)\n", WiFi.gatewayIP().toString().c_str(), calculatedGateway, "pool.ntp.org");
configTime(3600, 3600, WiFi.gatewayIP().toString().c_str(), calculatedGateway, "pool.ntp.org");
yield();
}
void serial_read() { void serial_read() {
if (Serial.available()) { if (Serial.available()) {
int input = Serial.read(); int input = Serial.read();