Lauffähig und aufgeräumt

This commit is contained in:
2021-12-16 17:09:19 +01:00
parent cd29191bb4
commit 29a636060c
8 changed files with 79 additions and 49 deletions
+32 -14
View File
@@ -1,7 +1,7 @@
/**
* @file network.cpp
* @author Alexander Klein (alex@kleiax.de)
* @brief Contains function implementation of network.h
* @brief TODO: write some stuff
* @version 0.1
* @date 2021-12-14
*
@@ -10,36 +10,50 @@
*/
#include "network.h"
void setIps() {
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 setupMQTT() {
mqtt_client.setServer(mqtt_server, MQTT_PORT);
void Network::setupMQTT() {
mqtt_client = new PubSubClient(wifi_client);
mqtt_client->setServer(mqtt_server, MQTT_PORT);
// mqtt_client.setServer(MQTT_SERVER, MQTT_PORT);
mqtt_client.setSocketTimeout(1);
Network::mqtt_client->setSocketTimeout(1);
mqtt_client->setSocketTimeout(1);
connectMQTT();
}
bool 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)) {
if (mqtt_client->connect(clientId.c_str(), MQTT_USER, MQTT_PASSWORD)) {
#endif //MQTT_AUTH
#ifndef MQTT_AUTH
if (mqtt_client.connect(clientId.c_str())) {
if (mqtt_client->connect(clientId.c_str())) {
#endif //MQTT_AUTH
// Once connected, publish an announcement...
mqtt_client.publish("Rover/Info", "Connected to Mqtt-Broker");
mqtt_client->publish("Rover/Info", "Connected to Mqtt-Broker");
}
return mqtt_client.connected();
return mqtt_client->connected();
}
void connectWifi() {
void Network::connectWifi() {
// Configures static IP address
if (!WiFi.config(local_IP, gateway, subnet)) {
Serial.println("STA Failed to configure");
@@ -61,9 +75,9 @@ void connectWifi() {
Serial.println(WiFi.localIP());
}
void checkMQTT() {
void Network::checkMQTT() {
static uint64_t lastReconnectAttempt = 0;
if (!mqtt_client.connected()) {
if (!mqtt_client->connected()) {
long now = millis();
if (now - lastReconnectAttempt > MQTT_TIME_RECONNECT) {
lastReconnectAttempt = now;
@@ -72,5 +86,9 @@ void checkMQTT() {
lastReconnectAttempt = 0;
}
} else
mqtt_client.loop();
mqtt_client->loop();
}
PubSubClient* Network::getMqtttClient() {
return mqtt_client;
}