diff --git a/src/main.cpp b/src/main.cpp index 4760bfb..301a210 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -59,6 +59,10 @@ void serial_read(); void wifi_loop(); +void ntp_setup(); + +uint32_t ip2int(const IPAddress &ip); + void web_index() { server.setContentLength(CONTENT_LENGTH_UNKNOWN); server.send(200, "text/html", ""); @@ -172,9 +176,8 @@ void wifi_loop() { if (!connected) { if (hasIp) { connected = true; - configTime(3600, 3600, WiFi.gatewayIP().toString().c_str()); Serial.printf("WiFi connected: %s\n", WiFi.localIP().toString().c_str()); - yield(); + ntp_setup(); } } else { 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() { if (Serial.available()) { int input = Serial.read();