Open Model Railroad Network (OpenMRN)
Loading...
Searching...
No Matches
Esp32WiFiManager.hxx
Go to the documentation of this file.
1
35#ifndef _FREERTOS_DRIVERS_ESP32_ESP32WIFIMGR_HXX_
36#define _FREERTOS_DRIVERS_ESP32_ESP32WIFIMGR_HXX_
37
39#include "executor/Executor.hxx"
40#include "executor/Service.hxx"
45#include "utils/GcTcpHub.hxx"
46#include "utils/macros.h"
47#include "utils/Singleton.hxx"
48
49#include <esp_event.h>
50#include <esp_netif.h>
51#include <esp_wifi_types.h>
52#include <freertos/event_groups.h>
53
54namespace openlcb
55{
56 class SimpleStackBase;
57}
58
59class Gpio;
60class SocketClient;
61
62namespace openmrn_arduino
63{
64
69typedef enum : uint8_t
70{
73
76
80} esp_network_interface_t;
81
91typedef std::function<void(esp_network_interface_t
93
102
110
114typedef std::function<void(time_t)> esp_network_time_callback_t;
115
121 , public Service
122 , public Singleton<Esp32WiFiManager>
123{
124public:
166 Esp32WiFiManager(const char *station_ssid
167 , const char *station_password
169 , const WiFiConfiguration &cfg
170 , wifi_mode_t wifi_mode = WIFI_MODE_STA
171 , uint8_t connection_mode = CONN_MODE_UPLINK_BIT
172 , const char *hostname_prefix = "esp32_"
173 , const char *sntp_server = "pool.ntp.org"
174 , const char *timezone = "UTC0"
175 , bool sntp_enabled = false
176 , uint8_t softap_channel = 1
177 , wifi_auth_mode_t softap_auth_mode = WIFI_AUTH_OPEN
178 , const char *softap_ssid = ""
179 , const char *softap_password = ""
180 );
181
184
187
192 void set_status_led(const Gpio *led = nullptr)
193 {
194 statusLed_ = led;
195 }
196
210 int fd, bool initial_load, BarrierNotifiable *done) override;
211
215 void factory_reset(int fd) override;
216
225 static void process_idf_event(void *ctx, esp_event_base_t event_base
226 , int32_t event_id, void *event_data);
227
235
240
243
248 wifi_ap_record_t get_ssid_scan_result(size_t index);
249
252
260 void mdns_publish(std::string service, uint16_t port);
261
265 void mdns_unpublish(std::string service);
266
277 void wait_for_ssid_connect(bool enable)
278 {
279 waitForStationConnect_ = enable;
280 }
281
289 void set_tx_power(uint8_t power)
290 {
291 HASSERT(power >= 8 && power <= 84);
292 wifiTXPower_ = power;
293 }
294
300
306
315
320
326 void sync_time(time_t now);
327
333 {
334 return &executor_;
335 }
336
337private:
340
344 static void *wifi_manager_task(void *param);
345
347 void stop_hub();
348
353 void start_hub();
354
357
361
367 void on_uplink_created(int fd, Notifiable *on_exit);
368
372
375
381
385
390 void on_station_disconnected(uint8_t reason);
391
394 void on_station_ip_assigned(uint32_t ip_address);
395
399
404
407
412 void on_softap_station_connected(uint8_t mac[6], uint8_t aid);
413
418 void on_softap_station_disconnected(uint8_t mac[6], uint8_t aid);
419
424 void on_wifi_scan_completed(uint32_t status, uint8_t count);
425
428
431
438
441 std::string hostname_;
442
444 std::string ssid_;
445
447 std::string password_;
448
450 const WiFiConfiguration cfg_;
451
454
456 const Gpio *statusLed_{nullptr};
457
459 const wifi_mode_t wifiMode_;
460
462 const uint8_t softAPChannel_;
463
466 wifi_auth_mode_t softAPAuthMode_;
467
472 std::string softAPName_;
473
478 std::string softAPPassword_;
479
481 const bool sntpEnabled_;
482
484 std::string sntpServer_;
485
487 std::string timeZone_;
488
490 bool sntpConfigured_{false};
491
495 int configFd_{-1};
496
499 uint32_t configCrc32_{0};
500
505
507 bool verboseLogging_{false};
508
511
513 uint8_t wifiTXPower_{84};
514
516 std::string hubServiceName_;
517
519 std::unique_ptr<SocketClient> uplink_;
520
522 int uplinkFd_{-1};
523
530
532 EventGroupHandle_t wifiStatusEventGroup_;
533
535 std::vector<wifi_ap_record_t> ssidScanResults_;
536
539
542
545
547 bool mdnsInitialized_{false};
548
551
554 std::map<std::string, uint16_t> mdnsDeferredPublish_;
555
559
561 std::vector<esp_network_up_callback_t> networkUpCallbacks_;
562
564 std::vector<esp_network_down_callback_t> networkDownCallbacks_;
565
567 std::vector<esp_network_init_callback_t> networkInitCallbacks_;
568
570 std::vector<esp_network_time_callback_t> networkTimeCallbacks_;
571
573 static constexpr uint8_t MAX_HOSTNAME_LENGTH = 32;
574
576 static constexpr uint8_t CONN_MODE_UPLINK_BIT = BIT(0);
577
579 static constexpr uint8_t CONN_MODE_HUB_BIT = BIT(1);
580
583 {
584 nullptr, nullptr
585 };
586
592 {
593 public:
599 {
600 }
601
603 virtual void notify() override
604 {
605 // if we have a valid notifiable from the uplink forward the notify
606 // call, otherwise this method is a no-op.
607 if (parent_->uplinkNotifiable_ != nullptr)
608 {
610 }
611 }
612 private:
615 };
616
619
680
683
685};
686
687} // namespace openmrn_arduino
688
695
696#endif // _FREERTOS_DRIVERS_ESP32_ESP32WIFIMGR_HXX_
std::function< void(esp_network_interface_t, uint32_t)> esp_network_up_callback_t
Callback function definition for the network up events.
esp_network_interface_t
ESP32 network interfaces.
@ MAX_NETWORK_INTERFACES
This is the maximum supported WiFi interfaces of the ESP32 and is not a valid network interface for u...
@ STATION_INTERFACE
This is used for the Station WiFi interface.
@ SOFTAP_INTERFACE
This is used for the SoftAP WiFi interface.
std::function< void(esp_network_interface_t)> esp_network_down_callback_t
Callback function definition for the network down events.
std::function< void(time_t)> esp_network_time_callback_t
Callback function definition for network time synchronization.
std::function< void(esp_network_interface_t)> esp_network_init_callback_t
Callback function definition for the network is initializing.
#define STATE_FLOW_STATE(_state)
Declare a state callback in a StateFlow.
Definition StateFlow.hxx:68
A BarrierNotifiable allows to create a number of child Notifiable and wait for all of them to finish.
UpdateAction
Specifies what additional steps are needed to apply the new configuration.
Implementation of ConfigUpdateListener that registers itself in the constructor and unregisters itsel...
Implementation the ExecutorBase with a specific number of priority bands.
Definition Executor.hxx:266
OS-independent abstraction for GPIO.
Definition Gpio.hxx:43
This is an empty struct.
Definition Executor.hxx:256
An object that can schedule itself on an executor to run.
virtual void notify()=0
Generic callback.
This class provides a mutex API.
Definition OS.hxx:427
Collection of related state machines that pend on incoming messages.
Singleton class.
Definition Singleton.hxx:65
Use this timer class to deliver the timeout notification to a stateflow.
Base class for state machines.
This class provides a proxy for the Notifiable provided by the SocketClient.
Esp32WiFiManager * parent_
Esp32WiFiManager instance that manages this class instance.
UplinkNotifiable(Esp32WiFiManager *parent)
Constructor.
virtual void notify() override
Proxies the notify() call to the uplink if it is not null.
StateFlow that is responsible for startup and maintenance of the WiFi stack.
Action init_wifi()
Initializes the ESP32 WiFi subsystems prior to configuration.
Action configure_station()
Configures the ESP32 WiFi Station interface.
uint32_t wifiConnectBitMask_
Bit mask used for checking WiFi connection process events in wait_for_connect.
uint8_t wifiConnectAttempts_
Number of attempts to connect to the SSID before timing out.
Action startup()
Initial state for this flow.
Esp32WiFiManager * parent_
Esp32WiFiManager instance that is being maintained.
Action reload()
State which processes a configuration reload or the initial configuration of the hub and uplink tasks...
Action wait_for_connect()
Re-entrant state that periodically checks if the Station interface has successfully connected to the ...
Action noop()
No-op state used when the WiFi system is not enabled and events are received.
WiFiStackFlow(Esp32WiFiManager *parent)
Constructor.
Action start_wifi()
Starts the ESP32 WiFi subsystem which will trigger the startup of the SoftAP interface (if configured...
StateFlowTimer timer_
StateFlowTimer used for periodic wakeup of wait_for_connect.
Action configure_softap()
Configures the ESP32 WiFi SoftAP interface.
Action init_interface()
Initializes the ESP32 WiFi interfaces that are maintained by this flow.
This class provides a simple way for ESP32 nodes to manage the WiFi and mDNS systems of the ESP32,...
static constexpr uint8_t CONN_MODE_UPLINK_BIT
Constant used to determine if the Uplink mode should be enabled.
const WiFiConfiguration cfg_
Persistent configuration that will be used for this node's WiFi usage.
OSMutex ssidScanResultsLock_
Protects ssidScanResults_ vector.
void register_network_up_callback(esp_network_up_callback_t callback)
Registers a callback for when the WiFi connection is up.
uint8_t wifiTXPower_
Maximum WiFi transmit power setting.
void enable_verbose_logging()
If called, sets the ESP32 wifi stack to log verbose information to the console.
void on_softap_stop()
Event handler called when the ESP32 SoftAP interface has shutdown.
void stop_hub()
Shuts down the hub listener (if running) for this node.
void on_softap_station_disconnected(uint8_t mac[6], uint8_t aid)
Event handler called when a station disconnects from the ESP32 SoftAP.
static constexpr uint8_t MAX_HOSTNAME_LENGTH
Maximum length of the hostname for the ESP32.
Notifiable * uplinkNotifiable_
Notifiable handle provided by the SocketClient once a connection has been established.
std::vector< esp_network_down_callback_t > networkDownCallbacks_
Holder for callbacks to invoke when the WiFi connection is down.
std::string ssid_
User provided SSID to connect to.
void on_station_ip_assigned(uint32_t ip_address)
Event handler called when the ESP32 Station interface has received an IP address (DHCP or static).
bool verboseLogging_
If true, request esp32 wifi to do verbose logging.
UplinkNotifiable uplinkNotifiableProxy_
UplinkNotifiable to use for uplink connections.
std::unique_ptr< SocketClient > uplink_
SocketClient for this node's uplink connection.
void set_status_led(const Gpio *led=nullptr)
Configures a Gpio to be used as a visual indication of the current WiFi status.
void start_mdns_system()
Initializes the mDNS system if it hasn't already been initialized.
static constexpr uint8_t CONN_MODE_HUB_BIT
Constant used to determine if the Hub mode should be enabled.
Executor< 1 > executor_
Executor to use for the uplink connections and callbacks.
std::string softAPName_
User provided name for the SoftAP when active, defaults to hostname_ when null.
std::string softAPPassword_
User provided password for the SoftAP when active, defaults to password when null and softAPAuthMode_...
void on_uplink_created(int fd, Notifiable *on_exit)
Callback for the SocketClient to handle a newly connected outbound socket connection.
void on_wifi_scan_completed(uint32_t status, uint8_t count)
Event handler called when a WiFi scan operation completes.
uint8_t connectionMode_
Defines the WiFi connection mode to operate in.
void register_network_time_callback(esp_network_time_callback_t callback)
Registers a callback for when SNTP updates are received.
void configure_sntp()
Configures SNTP and TimeZone (if enabled).
void on_station_connected()
Event handler called when the ESP32 Station interface has connected to an SSID.
std::string sntpServer_
SNTP server address.
int uplinkFd_
Socket handle used by the uplink connection.
void set_tx_power(uint8_t power)
Configures the WiFi maximum transmit power setting.
std::vector< wifi_ap_record_t > ssidScanResults_
WiFi SSID scan results holder.
void clear_ssid_scan_results()
Clears the SSID scan results.
Notifiable * ssidCompleteNotifiable_
Notifiable to be called when SSID scan completes.
const Gpio * statusLed_
WiFi connection status indicator Gpio instance.
void reconfigure_wifi_tx_power()
Reconfigures the WiFi radio transmit power.
static void process_idf_event(void *ctx, esp_event_base_t event_base, int32_t event_id, void *event_data)
Processes an event coming from the ESP-IDF default event loop.
static void * wifi_manager_task(void *param)
Background task used by the Esp32WiFiManager to maintain health of any connections to other nodes.
void mdns_unpublish(std::string service)
Removes the advertisement of a service via mDNS.
esp_netif_t * espNetIfaces_[MAX_NETWORK_INTERFACES]
Network interfaces that are managed by Esp32WiFiManager.
bool mdnsInitialized_
Internal flag for tracking that the mDNS system has been initialized.
const bool sntpEnabled_
Enables SNTP polling.
OSMutex networkCallbacksLock_
Protects the networkUpCallbacks_, networkDownCallbacks_, networkInitCallbacks_ and networkTimeCallbac...
std::string password_
User provided password for the SSID to connect to.
void on_softap_start()
Event handler called when the ESP32 SoftAP interface has started.
std::string timeZone_
TimeZone of the node.
wifi_auth_mode_t softAPAuthMode_
Authentication mode to use for the SoftAP.
void on_softap_station_connected(uint8_t mac[6], uint8_t aid)
Event handler called when a station connects to the ESP32 SoftAP.
std::vector< esp_network_time_callback_t > networkTimeCallbacks_
Holder for callbacks to invoke when network time synchronizes.
void on_station_ip_lost()
Event handler called when the ESP32 Station interface has lost it's assigned IP address.
openlcb::SimpleStackBase * stack_
OpenMRN stack for the Arduino system.
int configFd_
Cached copy of the file descriptor passed into apply_configuration.
void register_network_down_callback(esp_network_down_callback_t callback)
Registers a callback for when the WiFi connection is down.
void stop_uplink()
Disconnects and shuts down the uplink connector socket (if running).
std::string hostname_
Dynamically generated hostname for this node, esp32_{node-id}.
void on_station_disconnected(uint8_t reason)
Event handler called when the ESP32 Station interface has lost it's connection to the SSID or failed ...
wifi_ap_record_t get_ssid_scan_result(size_t index)
Returns one entry from the SSID scan.
Esp32WiFiManager(const char *station_ssid, const char *station_password, openlcb::SimpleStackBase *stack, const WiFiConfiguration &cfg, wifi_mode_t wifi_mode=WIFI_MODE_STA, uint8_t connection_mode=CONN_MODE_UPLINK_BIT, const char *hostname_prefix="esp32_", const char *sntp_server="pool.ntp.org", const char *timezone="UTC0", bool sntp_enabled=false, uint8_t softap_channel=1, wifi_auth_mode_t softap_auth_mode=WIFI_AUTH_OPEN, const char *softap_ssid="", const char *softap_password="")
Constructor.
ConfigUpdateListener::UpdateAction apply_configuration(int fd, bool initial_load, BarrierNotifiable *done) override
Updates the WiFiConfiguration settings used by this node.
std::string hubServiceName_
mDNS service name being advertised by the hub, if enabled.
uint32_t configCrc32_
Calculated CRC-32 of cfg_ data.
void on_station_started()
Event handler called when the ESP32 Station interface has started.
void wait_for_ssid_connect(bool enable)
Forces the Esp32WiFiManager to wait until SSID connection completes.
void sync_time(time_t now)
Time synchronization callback for SNTP.
void start_uplink()
Creates an uplink connector socket that will automatically add the uplink to the node's hub.
Esp32WiFiManager()
Default constructor.
WiFiStackFlow wifiStackFlow_
Instance of WiFiStackFlow used for WiFi maintenance.
std::vector< esp_network_init_callback_t > networkInitCallbacks_
Holder for callbacks to invoke when the WiFi subsystem has started.
void mdns_publish(std::string service, uint16_t port)
Advertises a service via mDNS.
EventGroupHandle_t wifiStatusEventGroup_
Internal event group used to track the IP assignment events.
OSMutex mdnsInitLock_
Protects the mdnsInitialized_ flag and mdnsDeferredPublish_ map.
std::map< std::string, uint16_t > mdnsDeferredPublish_
Internal holder for mDNS entries which could not be published due to mDNS not being initialized yet.
void display_configuration()
Display the configuration settings in use.
void register_network_init_callback(esp_network_init_callback_t callback)
Registers a callback for when WiFi interfaces are being initialized.
const uint8_t softAPChannel_
Channel to use for the SoftAP interface.
void reconfigure_wifi_radio_sleep()
Reconfigures the WiFi radio sleep mode.
void start_ssid_scan(Notifiable *n)
Starts a scan for available SSIDs.
const wifi_mode_t wifiMode_
WiFi operating mode.
bool sntpConfigured_
Tracks if SNTP has been configured.
void enable_esp_wifi_logging()
Enables the esp_wifi logging, including the esp_wifi_internal APIs when available.
std::vector< esp_network_up_callback_t > networkUpCallbacks_
Holder for callbacks to invoke when the WiFi connection is up.
void start_hub()
Creates a hub listener for this node after loading configuration details.
void factory_reset(int fd) override
Resets the WiFiConfiguration settings used by this node.
bool waitForStationConnect_
If true, the esp32 will block startup until the SSID connection has successfully completed and upon f...
#define HASSERT(x)
Checks that the value of expression x is true, else terminates the current process.
Definition macros.h:138
#define DISALLOW_COPY_AND_ASSIGN(TypeName)
Removes default copy-constructor and assignment added by C++.
Definition macros.h:171