diff --git a/doc/TODO allgemein.txt b/doc/TODO allgemein.txt index 74b2cdb..b704681 100644 --- a/doc/TODO allgemein.txt +++ b/doc/TODO allgemein.txt @@ -35,30 +35,28 @@ Do later: - kalibrierungsmethode mit Menü - Daten in flash speichern können -> Check speration between Ui and Route (RouteMenu) + -> update sparkfun gnss auf v3 für SPI korrekturdatenüvbetragung + -> Rover Objekt mit Error zustand freeze, damit das wenn möglich auch auf dem Display angezeigt wird. Do now: Code: Doxygen Kommentare aktualisieren - update sparkfun gnss auf v3 für SPI korrekturdatenüvbetragung - wifi als Komponente + sensor data gnss daten aktualisieren + Menübaum korrigieren, Verlinkung Sensor in Mode etc. + esp und sensoren in den deepsleep Latex: Anhang: Liste mit allen Komponenten und Kurzbeschreibung - Ausgangssituation, langweilig. Begründung wiesow was nicht benutzt wurde. - Anführungszeichen werden nicht richtig gesetzt, 2.1.1 / 2.2.1 / Oberrahmen "A" / Antennenhalterung "T." - Quellen mal mit und mal ohne leerzeichen hinterm Satz - Alle Aufzählungen am Anfang klein. Und EIN Punkt beim letzten Punkt / Vielleicht komme nach jedem Punkt - Kompass soft und hardware winkel auslesen norden = 0° - Anforderungsanalyse Beschreibung des Pattern, keine Unterstriche sichtbar Unterschied funktionale und nicht funktionale Anforderungen - Haupträger zweite Abbildung von oben mit benannten Aussparungen - - - - + Weniger / Keine Füllwörter + Strom nicht über Zeit sondern Rampe + ESP Pulsecounter Name Richtig? + Zittern? Besseres Wort Signal kann Springen + Rad Umfang gerundet + Trick Debugging mit dem Stream + Gyroskop für Bachelor aufheben 3D: - Oberrahmen soll nur aussehen wie ein A diff --git a/include/network.h b/include/network.h deleted file mode 100644 index cf2cd9b..0000000 --- a/include/network.h +++ /dev/null @@ -1,107 +0,0 @@ -/** - * @file network.h - * @author Alexander Klein (alex@kleiax.de) - * @brief Contains the Network class. - * @version 0.1 - * @date 2021-12-14 - * - * @copyright Copyright (c) 2021 - * - */ - -#ifndef NETWORK_H -#define NETWORK_H - -#include -#include -#include -#include -#include - -#include "networkConfig.h" - -typedef void (*recieveCallbackPtr) (const uint8_t * mac, const uint8_t *incomingData, int len); -typedef void (*sendCallbackPtr) (const uint8_t *mac_addr, esp_now_send_status_t status); - -/** - * @brief This class handles all network stuff - * - * This class only inherits static functions and members and use - * only the configuration data is given by networkConfig.h - * - */ -class Network { - public: - /** - * @brief Set the all IPs needed by this class - */ - static void setIps(); - - /** - * @brief Establish a connection to the WiFi. - * - * @return true Wifi is connected - * @return false Timeout - */ - static bool connectWifi(); - static bool connectEspNow(recieveCallbackPtr reci, sendCallbackPtr send); - static uint8_t getCurrentChannel(); - - /** - * @brief Set all general settings to connect to a broker. - */ - static void setupMQTT(); - - /** - * @brief Checks if mqtt is still connected - * - * If mqtt is not connect, this function try a reconnect - * with the function connectMQTT. This function should be - * called every mainloop. - * - * @return true if connected - * @return false if not connected - */ - static bool checkMQTT(); - static bool initMQTT(); - - /** - * @brief Checks if WiFi is still connected - * - * If WiFi is not connected, this function try a reconnect. - * This function should be called every mainloop. - */ - static void checkWiFi(); - - /** - * @brief Get the Mqtt Client object - * - * @return PubSubClient* - */ - static PubSubClient* getMqttClient(); - static const uint8_t * getBroadcastAddress() { return broadcastAddress; } - - private: - /** - * @brief Tries a connect to the broker - * - * @return true if the connect attemp was successful - * @return false if the connect attemp was unsuccessful - */ - static bool connectMQTT(); - static int32_t getWiFiChannel(const char *ssid); - - static esp_now_peer_info_t peerInfo; - static uint8_t broadcastAddress[6]; - - static IPAddress local_IP; - static IPAddress gateway; - static IPAddress subnet; - static IPAddress mqtt_server; - static IPAddress dnsServer; - - static WiFiClient wifi_client; - static PubSubClient* mqtt_client; -}; - -#endif // NETWORK_H diff --git a/include/networkConfig.h b/include/networkConfig.h index d62b70b..ebb265b 100644 --- a/include/networkConfig.h +++ b/include/networkConfig.h @@ -12,94 +12,47 @@ * */ -// General config -#define MQTT_TIME_RECONNECT 2500 - -/** - * @brief Wlan connect timeout - * - * This number multiplied by WLAN_CONNECT_LOOP_TIME is the - * timeout in milliseconds. - */ -#define WLAN_CONNECT_TIMEOUT 20 - -/** - * @brief Wlan connect loop time - * - * The time in milliseconds until the next connection attempt. - */ -#define WLAN_CONNECT_LOOP_TIME 500 -#define WLAN_DNS_SERVER "8.8.8.8" -#define ESP_NOW_CONTROLER_MAC {0xC8, 0xC9, 0xA3, 0xC8, 0x57, 0x10} - -#define NTRIP_RTK2GO - -// NTRIP config NRW -#ifdef NTRIP_NRW -#define NTRIP_HOST "www.sapos-nw-ntrip.de" -#define NTRIP_PORT 2101 -#define NTRIP_MOUNT_POINT "VRS_3_3G_NW" -#define NTRIP_USER "nw-916771" -#define NTRIP_PASSWORD "Schalke#246" -#endif // NTRIP_NRW - -// NTRIP config NS -#ifdef NTRIP_NS -#define NTRIP_HOST "openservice-sapos.niedersachsen.de" -#define NTRIP_PORT 2101 -#define NTRIP_MOUNT_POINT "VRS_3_2G_NI" -#define NTRIP_USER "ni_FHDo01" -#define NTRIP_PASSWORD "ALdx-1-3e49" -#endif // NTRIP_NS - -// NTRIP config RTK2Go -#ifdef NTRIP_RTK2GO -#define NTRIP_HOST "rtk2go.com" -#define NTRIP_PORT 2101 -#define NTRIP_MOUNT_POINT "GER-Dortmund" -#define NTRIP_USER "alklein1@gmx.de" -#define NTRIP_PASSWORD "none" -#endif // NTRIP_RTK2GO - +#include #define HOTSPOT -//Network config Hotspot #ifdef HOTSPOT -#define WLAN_SSID "Kleiax Handy" -#define WLAN_PASSWORD "12345677" -#define WLAN_IP "192.168.43.4" -#define WLAN_SUBNETMASK "255.255.128.0" -#define WLAN_GATEWAY "192.168.43.1" -// Only for defines reasons - #define MQTT_SERVER "172.22.64.216" - #define MQTT_PORT 1883 +namespace NetworkConfig { + const char ssid[] = "Kleiax Handy"; + const char password[] = "12345677"; + const char ip[] = "192.168.43.4"; + const char subnet[] = "255.255.255.0"; + const char gateway[] = "192.168.43.1"; + const char dns[] = "8.8.8.8"; + const bool mqtt = false; +} #endif //HOTSPOT //Network config Rhede #ifdef RHEDE -#define WLAN_SSID "LebennigHuus" -#define WLAN_PASSWORD "Punica-699" -#define WLAN_IP "192.168.11.4" -#define WLAN_SUBNETMASK "255.255.128.0" -#define WLAN_GATEWAY "192.168.0.1" -#define MQTT -#define MQTT_SERVER "192.168.1.7" -#define MQTT_PORT 1883 -#define MQTT_AUTH -#define MQTT_USER "kleiax" -#define MQTT_PASSWORD "p?{$_~5%hBM7wrcFkr55KWr#" +namespace NetworkConfig { + const char ssid[] = "LebennigHuus"; + const char password[] = "Punica-699"; + const char ip[] = "192.168.11.4"; + const char subnet[] = "255.255.128.0"; + const char gateway[] = "192.168.0.1"; + const char dns[] = "8.8.8.8"; + const bool mqtt = true; +} #endif //RHEDE -//Network config Doro -#ifdef DORO -#define WLAN_SSID "Tuedelkram" -#define WLAN_PASSWORD "3Kaesehoch!" -#define WLAN_IP "192.168.178.4" -#define WLAN_SUBNETMASK "255.255.255.0" -#define WLAN_GATEWAY "192.168.178.1" - // Only for defines reasons - #define MQTT_SERVER "172.22.64.216" - #define MQTT_PORT 1883 -#endif //DORO +namespace MqttConfig { + const char server[] = "192.168.1.7"; + const uint16_t port = 1883; + const char user[] = "kleiax"; + const char password[] = "p?{$_~5%hBM7wrcFkr55KWr#"; +} +namespace NtripConfig { + const char host[] = "rtk2go.com"; + const uint16_t port = 2101; + const char mountPoint[] = "GER-Dortmund"; + // const char mountPoint[] = "GER-Papenburg"; + const char user[] = "alklein1@gmx.de"; + const char password[] = "none"; +} diff --git a/lib/Network/network.cpp b/lib/Network/network.cpp new file mode 100644 index 0000000..8e668da --- /dev/null +++ b/lib/Network/network.cpp @@ -0,0 +1,164 @@ +/** + * @file network.cpp + * @author Alexander Klein (alex@kleiax.de) + * @brief + * @version 0.1 + * @date 2023-09-18 + * + * @copyright Copyright (c) 2023 + * + */ + +#include "network.h" + +Network::Network(const char *ssid, const char *passphrase) { + if (!WiFi.mode(WIFI_AP_STA)) + std::cout << "Network::connectWiFi failed WiFi.mode" << std::endl; + + this->init(ssid, passphrase); +} + +Network::Network(const char *ssid, const char *passphrase, NetworkAdresses adresses) { + if (!WiFi.mode(WIFI_AP_STA)) + std::cout << "Network::connectWiFi failed WiFi.mode" << std::endl; + + if (!WiFi.config(this->adresses.localIP, + this->adresses.gateway, + this->adresses.subnet, + this->adresses.dnsServer)) + { + std::cout << "STA Failed to configure" << std::endl; + } + + this->init(ssid, passphrase); +} + +Network::~Network() { + if (this->mqttClient) + delete mqttClient; +} + +bool Network::activateEspNow(recieveCallbackPtr reci, sendCallbackPtr send) { + if (esp_now_init() != ESP_OK) { + std::cout << "Network::activateEspNow - Error initializing ESP-NOW" << std::endl; + return false; + } + + esp_now_register_send_cb(send); + + memcpy(this->peerInfo.peer_addr, this->broadcastAddress, 6); + this->peerInfo.channel = 0; + this->peerInfo.encrypt = false; + + if (esp_now_add_peer(&peerInfo) != ESP_OK) { + std::cout << "Network::connectEspNow - Failed to add peer" << std::endl; + return false; + } + + esp_now_register_recv_cb(reci); + return true; +} + +bool Network::activateMqtt(const char *user, const char *passphrase) { + this->mqttUser = user; + this->mqttPassphrase = passphrase; + + this->mqttClient = new PubSubClient(this->wifiClient); + this->mqttClient->setServer(this->adresses.mqttServer, this->adresses.mqttPort); + this->mqttClient->setSocketTimeout(1); + + if (this->wifiConnected) + return this->connectMqtt(); + return false; +} + +void Network::printIPs() { + std::cout << std::endl; + if (!this->wifiConnected) { + std::cout << "WiFi is not connected." << std::endl; + return; + } + std::cout << "WiFi is connected to" << std::endl; + std::cout << "IP address: " << std::endl; + std::cout << this->adresses.localIP << std::endl; + std::cout << "WiFi MAC Address: " << WiFi.macAddress() << std::endl << std::endl; +} + +uint8_t Network::getCurrentChannel() { + uint8_t channel; + wifi_second_chan_t secondChannel; + if (esp_wifi_get_channel(&channel, &secondChannel) != ESP_OK) { + std::cout << "Network::getCurrentChannel - Error!" << std::endl; + return -1; + } + + return channel; +} + +void Network::runAsChild() { + if (!this->initSucessful) + return; + + this->checkWifi(); + + if (this->wifiConnected && this->mqttClient) + this->checkMqtt(); +} + +void Network::init(const char *ssid, const char *passphrase) { + // Connect to Wi-Fi network with SSID and password + std::cout << "Connecting to " << ssid << std::endl; + WiFi.begin(ssid, passphrase); + uint8_t timeout = Network::wifiConnectTimeout; + while (WiFi.status() != WL_CONNECTED) { + delay(Network::wifiConnectLoopTime); + std::cout << "." << std::flush; + timeout--; + if (timeout == 0) { + std::cout << std::endl; + std::cout << "WiFi NOT connected." << std::endl; + return; + } + } + + this->wifiConnected = true; + this->printIPs(); +} + +void Network::checkWifi() { + if ((WiFi.status() != WL_CONNECTED) + && (millis() - this->lastWifiRecoonectAttemp >= Network::wifiReconnectDelay)) + { + std::cout << "Reconnecting to WiFi..." << std::endl; + WiFi.disconnect(); + this->wifiConnected = WiFi.reconnect(); + this->lastWifiRecoonectAttemp = millis(); + } +} + +void Network::checkMqtt() { + if (!this->mqttClient->connected() + && millis() - this->lastMqttReconnectAttemp > Network::mqttReconnectDelay) + { + this->mqttConnected = this->connectMqtt(); + this->lastMqttReconnectAttemp = millis(); + } + + if (this->mqttConnected) + this->mqttClient->loop(); +} + +bool Network::connectMqtt() { + String clientId = "ESP32Rover-"; + clientId += String(random(0xffff), HEX); + + if (this->mqttUser) { + if (this->mqttClient->connect(clientId.c_str(), this->mqttUser, this->mqttPassphrase)) + this->mqttClient->publish("Rover/Info", "Connected to Mqtt-Broker"); + } else { + if (this->mqttClient->connect(clientId.c_str())) + this->mqttClient->publish("Rover/Info", "Connected to Mqtt-Broker"); + } + + return this->mqttClient->connected(); +} diff --git a/lib/Network/network.h b/lib/Network/network.h new file mode 100644 index 0000000..56f71d5 --- /dev/null +++ b/lib/Network/network.h @@ -0,0 +1,85 @@ +/** + * @file network.h + * @author Alexander Klein (alex@kleiax.de) + * @brief + * @version 0.1 + * @date 2023-09-18 + * + * @copyright Copyright (c) 2023 + * + */ + +#ifndef NETWORK_H +#define NETWORK_H + +#include "component.h" + +#include +#include +#include +#include +#include + +typedef void (*recieveCallbackPtr) (const uint8_t * mac, const uint8_t *incomingData, int len); +typedef void (*sendCallbackPtr) (const uint8_t *mac_addr, esp_now_send_status_t status); + +struct NetworkAdresses { + IPAddress localIP; + IPAddress gateway; + IPAddress subnet; + IPAddress dnsServer; + IPAddress mqttServer; + uint16_t mqttPort = 1883; +}; + +class Network : public Component { + public: + Network(const char *ssid, const char *passphrase); + Network(const char *ssid, const char *passphrase, NetworkAdresses adresses); + + ~Network(); + + bool activateEspNow(recieveCallbackPtr reci, sendCallbackPtr send); + bool activateMqtt(const char *user = nullptr, const char *passphrase = nullptr); + + void printIPs(); + + bool isWifiConnected() const { return this->wifiConnected; } + bool isMqttConnected() const { return this->mqttConnected; } + const uint8_t* getBroadcastAddress() const { return this->broadcastAddress; } + PubSubClient* getMqttClient() const { return this->mqttClient; } + + static uint8_t getCurrentChannel(); + + private: + void run() override {}; + void runAsChild() override; + void init(const char *ssid, const char *passphrase); + void checkWifi(); + void checkMqtt(); + bool connectMqtt(); + + NetworkAdresses adresses; + WiFiClient wifiClient; + PubSubClient* mqttClient = nullptr; + esp_now_peer_info_t peerInfo; + + bool initSucessful = false; + bool wifiConnected = false; + bool mqttConnected = false; + + const char *mqttUser; + const char *mqttPassphrase; + + uint8_t broadcastAddress[6] = {0xC8, 0xC9, 0xA3, 0xC8, 0x57, 0x10}; + uint32_t lastWifiRecoonectAttemp = 0; + uint32_t lastMqttReconnectAttemp = 0; + + static constexpr uint8_t wifiConnectTimeout = 20; + static constexpr uint16_t wifiConnectLoopTime = 500; + static constexpr uint16_t wifiReconnectDelay = 5000; + static constexpr uint16_t mqttReconnectDelay = 2500; + +}; + +#endif //NETWORK_H diff --git a/lib/Sensors/sensorData.cpp b/lib/Sensors/sensorData.cpp index 5e7a4d7..a3de617 100644 --- a/lib/Sensors/sensorData.cpp +++ b/lib/Sensors/sensorData.cpp @@ -171,10 +171,14 @@ void SensorData::setOutputStatusPrintPVTdata(bool status) { } void SensorData::run() { - this->realCompass->read(); - this->realAzimuth = this->realCompass->getAzimuth(); + if (this->realCompass) { + this->realCompass->read(); + this->realAzimuth = this->realCompass->getAzimuth(); + } - if (this->gyroskop->dmpGetCurrentFIFOPacket(this->gyroBuffer)) { + if (this->gyroskop + && this->gyroskop->dmpGetCurrentFIFOPacket(this->gyroBuffer)) + { this->gyroskop->dmpGetQuaternion(&this->quaternion, this->gyroBuffer); this->gyroskop->dmpGetGravity(&this->gravity, &this->quaternion); this->gyroskop->dmpGetYawPitchRoll(this->yawPitchRoll, &this->quaternion, &this->gravity); @@ -182,11 +186,15 @@ void SensorData::run() { } void SensorData::runAsChild() { - this->gnss->checkUblox(); - this->gnss->checkCallbacks(); + if (this->gnss) { + this->gnss->checkUblox(); + this->gnss->checkCallbacks(); + } - if (SensorData::newData) + if (SensorData::newData) { SensorData::newData = false; + // TODO: Update data + } } void SensorData::initGnss() { diff --git a/src/SpecialMenus/SensorData/menuSensorData.cpp b/src/SpecialMenus/SensorData/menuSensorData.cpp index 56b9545..13e74f2 100644 --- a/src/SpecialMenus/SensorData/menuSensorData.cpp +++ b/src/SpecialMenus/SensorData/menuSensorData.cpp @@ -44,7 +44,7 @@ void MenuSensorData::printPage() const { lineOne = "Calc Azimuth:"; lineTwo.concat(this->sensorData->getCalcAzimuth()); lineTwo.concat(" "); - lineTwo.concat(CalcAzimuth::stateToString(this->sensorData->getCalcAzimuthState)); + lineTwo.concat(CalcAzimuth::stateToString(this->sensorData->getCalcAzimuthState())); break; case 3: { diff --git a/src/main.cpp b/src/main.cpp index 97bbcd4..6646e51 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -29,6 +29,7 @@ #include "LcdWrapper.h" #include "moveControl.h" #include "network.h" +#include "networkConfig.h" #include "debugMqtt.h" #include "battery.h" #include "sensorData.h" @@ -45,10 +46,10 @@ #include "SpecialMenus/Systeminformation/menuSysteminformation.h" #include "SpecialMenus/PID/menuPidSettings.h" #include "SpecialMenus/Route/menuRoute.h" -#include "SpecialMenus/GPS/menuGPS.h" #include "SpecialMenus/SensorData/menuSensorData.h" MoveControl moveController; +Network* network; DriveManager* driveManager; Menu* main_m; LiquidCrystal_I2C* lcd; @@ -68,17 +69,13 @@ void restart(void); void receiveCallback (const uint8_t * mac, const uint8_t *incomingData, int len); void sendCallback (const uint8_t *mac_addr, esp_now_send_status_t status); void lcdWrapperCallback (const char data[][LcdWrapper::totalRows], uint8_t lines, uint8_t rows); +NetworkAdresses setIPs(void); void setup() { Serial.begin(115200); // DebugTimes::setConsolOutput(true); DebugTimes setupTime; - char wifiIndicator = 'X'; - - WiFi.mode(WIFI_MODE_STA); - Serial.print("MAC Address: "); - Serial.println(WiFi.macAddress()); spiPort = new SPIClass(HSPI); spiPort->begin(PinNumbers::spiSck, PinNumbers::spiCipo, PinNumbers::spiCopi, PinNumbers::gnssSpiCs); @@ -94,25 +91,21 @@ void setup() { lcd->clear(); lcd->noBacklight(); - Network::setIps(); - Network::setupMQTT(); - wifiIsActive = Network::connectWifi(); - if (wifiIsActive) { - Network::initMQTT(); - if (Network::checkMQTT()) { - DebugMqtt::init(Network::getMqttClient(), Loglevel::debug); - std::cout << "Activate additional output via MQTT..." << std::endl; + network = new Network(NetworkConfig::ssid, NetworkConfig::password, setIPs()); + network->activateEspNow(receiveCallback, sendCallback); + if (NetworkConfig::mqtt) { + if (network->activateMqtt(MqttConfig::user, MqttConfig::password)) { + DebugMqtt::init(network->getMqttClient(), Loglevel::debug); debugMqtt = new DebugMqtt("Console"); outputBuf = new OutputBuf(debugMqtt); - } else + outputBuf->activateMqtt(true); + } else { outputBuf = new OutputBuf(); - wifiIndicator = '-'; + } } else outputBuf = new OutputBuf(); std::cout.rdbuf(outputBuf); - Network::connectEspNow(receiveCallback, sendCallback); - std::cout << "Welcome to Kleiax-Rover" << std::endl; std::cout << "Project verion: " << VERSION << std::endl; std::cout << "Build timestamp: " << BUILD_TIMESTAMP << std::endl; @@ -121,11 +114,12 @@ void setup() { sensorData = new SensorData(); sensorData->enableGnss(spiPort, PinNumbers::gnssSpiCs); sensorData->enableRealCompass(); - sensorData->enableGyroskop(); + // sensorData->enableGyroskop(); driveManager = new DriveManager(&moveController, sensorData, controlPad->getControlPadDataPtr()); - outputBuf->activateMqtt(true); - + char wifiIndicator = 'X'; + if (network->isWifiConnected()) + wifiIndicator = '-'; lcd->backlight(); lcd->printf("%c Kleiax-Rover %c", wifiIndicator, wifiIndicator); lcd->setCursor(0, 1); @@ -139,16 +133,7 @@ void setup() { } void loop() { - if (wifiIsActive) { - DebugTimes wifiTime; - Network::checkWiFi(); - #ifdef MQTT - bool err = Network::checkMQTT(); - if (!err) - std::cout << "loop(): checkMQTT returns false" << std::endl; - #endif //MQTT - wifiTime.stopConsol("WiFi-Time", 10); - } + network->loop(); sensorData->loop(); driveManager->loop(); controlPad->loop(); @@ -297,8 +282,22 @@ void lcdWrapperCallback (const char data[][LcdWrapper::totalRows], uint8_t lines if (!controlPad->isControlPadConnected()) return; - esp_err_t result = esp_now_send(Network::getBroadcastAddress(), (uint8_t *) data, lines * rows); + esp_err_t result = esp_now_send(network->getBroadcastAddress(), (uint8_t *) data, lines * rows); if (result != ESP_OK) Serial.println("Error sending the data"); } + +NetworkAdresses setIPs() { + NetworkAdresses adresses; + adresses.localIP.fromString(NetworkConfig::ip); + adresses.subnet.fromString(NetworkConfig::subnet); + adresses.gateway.fromString(NetworkConfig::gateway); + adresses.dnsServer.fromString(NetworkConfig::dns); + if (NetworkConfig::mqtt) { + adresses.mqttServer.fromString(MqttConfig::server); + adresses.mqttPort = MqttConfig::port; + } + + return adresses; +} diff --git a/src/network.cpp b/src/network.cpp deleted file mode 100644 index baaa932..0000000 --- a/src/network.cpp +++ /dev/null @@ -1,174 +0,0 @@ -/** - * @file network.cpp - * @author Alexander Klein (alex@kleiax.de) - * @brief Contains the implementation of the ststic class Network - * @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; -IPAddress Network::dnsServer; - -WiFiClient Network::wifi_client; -PubSubClient* Network::mqtt_client; - -esp_now_peer_info_t Network::peerInfo; -uint8_t Network::broadcastAddress[6] = ESP_NOW_CONTROLER_MAC; - -void Network::setIps() { - local_IP.fromString(WLAN_IP); - gateway.fromString(WLAN_GATEWAY); - subnet.fromString(WLAN_SUBNETMASK); - mqtt_server.fromString(MQTT_SERVER); - dnsServer.fromString(WLAN_DNS_SERVER); -} - -void Network::setupMQTT() { - Network::mqtt_client = new PubSubClient(wifi_client); - Network::mqtt_client->setServer(MQTT_SERVER, MQTT_PORT); - Network::mqtt_client->setSocketTimeout(1); -} - -bool Network::connectMQTT() { - #ifndef MQTT - return false; - #endif - - // 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(); -} -bool Network::connectWifi() { - // Configures static IP address - - if (!WiFi.mode(WIFI_AP_STA)) - std::cout << "Network::connectWiFi failed WiFi.mode" << std::endl; - - if (!WiFi.config(local_IP, gateway, subnet, dnsServer)) - std::cout << "STA Failed to configure" << std::endl; - - // Connect to Wi-Fi network with SSID and password - std::cout << "Connecting to " << WLAN_SSID << std::endl; - WiFi.begin(WLAN_SSID, WLAN_PASSWORD); - uint8_t timeout = WLAN_CONNECT_TIMEOUT; - while (WiFi.status() != WL_CONNECTED) { - delay(WLAN_CONNECT_LOOP_TIME); - std::cout << "." << std::flush; - timeout--; - if (timeout == 0) { - std::cout << std::endl; - std::cout << "WiFi NOT connected." << std::endl; - return false; - } - } - - // Print local IP address and start web server - std::cout << std::endl; - std::cout << "WiFi connected." << std::endl; - std::cout << "IP address: " << std::endl; - std::cout << WLAN_IP << std::endl; - // std::cout << "WiFi MAC Address: " << WiFi.macAddress() << std::endl << std::endl; - return true; -} - -bool Network::connectEspNow(recieveCallbackPtr reci, sendCallbackPtr send) { - if (esp_now_init() != ESP_OK) { - std::cout << "Network::connectEspNow - Error initializing ESP-NOW" << std::endl; - return false; - } - - esp_now_register_send_cb(send); - - memcpy(peerInfo.peer_addr, broadcastAddress, 6); - peerInfo.channel = 0; - peerInfo.encrypt = false; - - if (esp_now_add_peer(&peerInfo) != ESP_OK) { - std::cout << "Network::connectEspNow - Failed to add peer" << std::endl; - return false; - } - - esp_now_register_recv_cb(reci); - return true; -} - -uint8_t Network::getCurrentChannel() { - uint8_t channel; - wifi_second_chan_t secondChannel; - if (esp_wifi_get_channel(&channel, &secondChannel) != ESP_OK) { - std::cout << "Network::getCurrentChannel - Error!" << std::endl; - return -1; - } - // std::cout << "Network::getCurrentChannel - Current WiFi channel: " - // << (int) channel << " second channel: " << (int) secondChannel - // << std::endl; - return channel; -} - -bool 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()) - return true; - } - return false; - } - mqtt_client->loop(); - return true; -} - -bool Network::initMQTT() { - if (connectMQTT()) - return true; - return false; -} - -int32_t Network::getWiFiChannel(const char *ssid) { - if (int32_t n = WiFi.scanNetworks()) - for (uint8_t i=0; i= delay)) { - std::cout << "Reconnecting to WiFi..." << std::endl; - WiFi.disconnect(); - WiFi.reconnect(); - previousMillis = currentMillis; - } - -} - -PubSubClient* Network::getMqttClient() { - return mqtt_client; -}