/** * @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 /** * @brief Typedef to easy handle the receive Callback */ typedef void (*receiveCallbackPtr)(const uint8_t *mac, const uint8_t *incomingData, int len); /** * @brief Typedef to easy handle the send Callback */ typedef void (*sendCallbackPtr)(const uint8_t *mac_addr, esp_now_send_status_t status); /** * @brief A Struct to hold all network addresses */ struct NetworkAddresses { IPAddress localIP; IPAddress gateway; IPAddress subnet; IPAddress dnsServer; IPAddress mqttServer; uint16_t mqttPort = 1883; }; /** * @brief A class to manage the wireless connections */ class Network : public Component { public: /** * @brief Construct a new Network object * * With this constructor the esp gets its ip from a Dhcp server * * @param ssid * @param passphrase */ Network(const char *ssid, const char *passphrase); /** * @brief Construct a new Network object * * This constructor is used for a static ip setup * * @param ssid * @param passphrase * @param addresses */ Network(const char *ssid, const char *passphrase, NetworkAddresses addresses); ~Network(); /** * @brief Activate ESP-NOW to communicate with the remote Control * * @param receive * @param send * @return true * @return false */ bool activateEspNow(receiveCallbackPtr receive, sendCallbackPtr send); /** * @brief Activate MQTT to send debug messages * * @param user * @param passphrase * @return true * @return false */ bool activateMqtt(const char *user = nullptr, const char *passphrase = nullptr); /** * @brief Print the current used IPs */ const 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(); NetworkAddresses addresses; WiFiClient wifiClient; PubSubClient *mqttClient = nullptr; bool initSuccessful = false; bool wifiConnected = false; bool mqttConnected = false; const char *mqttUser = nullptr; const char *mqttPassphrase = nullptr; uint8_t broadcastAddress[6] = {0xC8, 0xC9, 0xA3, 0xC8, 0x57, 0x10}; uint32_t lastWifiReconnectAttempt = 0; uint32_t lastMqttReconnectAttempt = 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