95 lines
2.4 KiB
C++
95 lines
2.4 KiB
C++
/**
|
|
* @file network.cpp
|
|
* @author Alexander Klein (alex@kleiax.de)
|
|
* @brief TODO: write some stuff
|
|
* @version 0.1
|
|
* @date 2021-12-14
|
|
*
|
|
* @copyright Copyright (c) 2021
|
|
*
|
|
*/
|
|
|
|
#include "network.h"
|
|
|
|
IPAddress Network::local_IP;
|
|
IPAddress Network::gateway;
|
|
IPAddress Network::subnet;
|
|
IPAddress Network::mqtt_server;
|
|
|
|
WiFiClient Network::wifi_client;
|
|
PubSubClient* Network::mqtt_client;
|
|
|
|
void Network::setIps() {
|
|
local_IP.fromString(WLAN_IP);
|
|
gateway.fromString(WLAN_GATEWAY);
|
|
subnet.fromString(WLAN_SUBNETMASK);
|
|
mqtt_server.fromString(MQTT_SERVER);
|
|
}
|
|
|
|
void Network::setupMQTT() {
|
|
mqtt_client = new PubSubClient(wifi_client);
|
|
mqtt_client->setServer(mqtt_server, MQTT_PORT);
|
|
// mqtt_client.setServer(MQTT_SERVER, MQTT_PORT);
|
|
Network::mqtt_client->setSocketTimeout(1);
|
|
mqtt_client->setSocketTimeout(1);
|
|
connectMQTT();
|
|
}
|
|
|
|
bool Network::connectMQTT() {
|
|
// Create a random client ID
|
|
String clientId = "ESP32Rover-";
|
|
clientId += String(random(0xffff), HEX);
|
|
|
|
#ifdef MQTT_AUTH
|
|
if (mqtt_client->connect(clientId.c_str(), MQTT_USER, MQTT_PASSWORD)) {
|
|
#endif //MQTT_AUTH
|
|
|
|
#ifndef MQTT_AUTH
|
|
if (mqtt_client->connect(clientId.c_str())) {
|
|
#endif //MQTT_AUTH
|
|
|
|
// Once connected, publish an announcement...
|
|
mqtt_client->publish("Rover/Info", "Connected to Mqtt-Broker");
|
|
}
|
|
return mqtt_client->connected();
|
|
}
|
|
void Network::connectWifi() {
|
|
// Configures static IP address
|
|
if (!WiFi.config(local_IP, gateway, subnet)) {
|
|
Serial.println("STA Failed to configure");
|
|
}
|
|
|
|
// Connect to Wi-Fi network with SSID and password
|
|
Serial.print("Connecting to ");
|
|
Serial.println(WLAN_SSID);
|
|
WiFi.begin(WLAN_SSID, WLAN_PASSWORD);
|
|
while (WiFi.status() != WL_CONNECTED) {
|
|
delay(500);
|
|
Serial.print(".");
|
|
}
|
|
|
|
// Print local IP address and start web server
|
|
Serial.println("");
|
|
Serial.println("WiFi connected.");
|
|
Serial.println("IP address: ");
|
|
Serial.println(WiFi.localIP());
|
|
}
|
|
|
|
void Network::checkMQTT() {
|
|
static uint64_t lastReconnectAttempt = 0;
|
|
if (!mqtt_client->connected()) {
|
|
long now = millis();
|
|
if (now - lastReconnectAttempt > MQTT_TIME_RECONNECT) {
|
|
lastReconnectAttempt = now;
|
|
// Attempt to reconnect
|
|
if (connectMQTT())
|
|
lastReconnectAttempt = 0;
|
|
}
|
|
} else
|
|
mqtt_client->loop();
|
|
}
|
|
|
|
PubSubClient* Network::getMqtttClient() {
|
|
return mqtt_client;
|
|
}
|