105 lines
2.6 KiB
C++
105 lines
2.6 KiB
C++
#include "wifi.h"
|
|
#include "display.h"
|
|
#include "mqtt.h"
|
|
|
|
#include <WiFi.h>
|
|
#include <ArduinoOTA.h>
|
|
#include <esp_sntp.h>
|
|
|
|
bool wifiConnected = false;
|
|
|
|
void onConnect();
|
|
|
|
uint32_t ip2int(const IPAddress &ip);
|
|
|
|
void timeSyncCallback(struct timeval *tv);
|
|
|
|
char *calculateGateway(char *calculatedGateway, size_t size);
|
|
|
|
void wifi_setup() {
|
|
WiFiClass::setHostname("RGBMatrixDisplay");
|
|
WiFi.begin("HappyNet", "1Grausame!Sackratte7");
|
|
yield();
|
|
|
|
ArduinoOTA.onStart([]() {
|
|
Serial.print("\n\nOTA Update: ");
|
|
display.clear();
|
|
display.loop();
|
|
});
|
|
ArduinoOTA.onProgress([](unsigned int progress, unsigned int total) {
|
|
double ratio = (double) progress / (double) total;
|
|
Serial.printf("\rOTA Update: %3.0f%%", ratio * 100);
|
|
|
|
auto index = (uint16_t) round(ratio * (double) display.pixelCount);
|
|
auto color = (uint8_t) round(ratio * 255.0);
|
|
display.set(index, {(uint8_t) (255 - color), color, 0});
|
|
display.loop();
|
|
});
|
|
ArduinoOTA.onEnd([]() {
|
|
Serial.println("\nOTA Success!\n");
|
|
display.clear();
|
|
display.loop();
|
|
});
|
|
ArduinoOTA.onError([](int error) {
|
|
Serial.println("\nOTA Failure!\n");
|
|
display.clear();
|
|
display.loop();
|
|
});
|
|
ArduinoOTA.begin();
|
|
yield();
|
|
}
|
|
|
|
void wifi_loop() {
|
|
ArduinoOTA.handle();
|
|
bool hasIp = (uint32_t) WiFi.localIP() != 0;
|
|
if (!wifiConnected) {
|
|
if (hasIp) {
|
|
wifiConnected = true;
|
|
onConnect();
|
|
}
|
|
} else {
|
|
if (!hasIp) {
|
|
wifiConnected = false;
|
|
Serial.println("WiFi disconnected!");
|
|
}
|
|
}
|
|
}
|
|
|
|
void onConnect() {
|
|
Serial.printf("WiFi connected: %s\n", WiFi.localIP().toString().c_str());
|
|
char calculatedGateway[16] = {0};
|
|
calculateGateway(calculatedGateway, sizeof(calculatedGateway));
|
|
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, "pool.ntp.org", WiFi.gatewayIP().toString().c_str(), calculatedGateway);
|
|
yield();
|
|
}
|
|
|
|
bool wifiIsConnected() {
|
|
return wifiConnected;
|
|
}
|
|
|
|
char *calculateGateway(char *calculatedGateway, size_t size) {
|
|
uint32_t local = ip2int(WiFi.localIP());
|
|
uint32_t netmask = ip2int(WiFi.subnetMask());
|
|
uint32_t gateway = local & netmask + 1;
|
|
snprintf(
|
|
calculatedGateway,
|
|
size,
|
|
"%u.%u.%u.%u",
|
|
(gateway >> 24) & 0xFF,
|
|
(gateway >> 16) & 0xFF,
|
|
(gateway >> 8) & 0xFF,
|
|
(gateway >> 0) & 0xFF
|
|
);
|
|
return calculatedGateway;
|
|
}
|
|
|
|
uint32_t ip2int(const IPAddress &ip) {
|
|
return ((ip[0] * 256 + ip[1]) * 256 + ip[2]) * 256 + ip[3];
|
|
}
|
|
|
|
void timeSyncCallback(struct timeval *tv) {
|
|
Serial.printf("timeSyncCallback: %ld\n", tv->tv_sec);
|
|
}
|