This is an application library, which is used as a project specific library for particular PlatformIO project. It encapsulates the functionality of connection to WiFi network
. The encapsulation provides following advantages:
- Functionality is hidden from the main sketch.
- The library follows the principle
separation of concerns
. - The library is reusable for various projects without need to code connection management.
- Update in library is valid for all involved projects.
- It specifies (inherits from) the parent application library
gbj_appcore
. - It utilizes funcionality and error handling from the parent class.
The library supports only microcontrollers with wifi capability, so that it is not suitable for Arduinos.
- The library enables to set a static (fixed) IP address of the microcontroller.
- The connection to wifi is checked at every loop of a main sketch.
- The library does not support multicast DNS on purpose, because it appeared as unreliable in praxis.
- If no connection to wifi is detected or has been lost, the library starts a new attempt to connect and tries to recover wifi connection.
- The library is designed for blocking the MCU at wifi connection establishment as little as possible, so that it utilizes a main sketch loop for it.
- The project library relies on the system library for wifi management as for reconnection repetation, event handlers firing, etc.
- The project library counts on handlers of type WiFiEventHandler for events WiFiEventStationModeGotIP and WiFiEventStationModeDisconnected at least.
- If WiFiEventStationModeGotIP handler is not implemented in the main sketch or from some reasons it does not fire after successful connection, the library simulates its activation.
- If WiFiEventStationModeDisconnected handler is not implemented in the main sketch or from some reasons it does not fire during repeating waiting for a connection result, the library simulates its activation by a safety counter after safety number of failed connection attempts.
- The library provides statistical smoothing of RSSI by
median
from5
consecutive values in dBm. - The library enables a simple ping to the current wifi gateway in order to detect false wifi status as connected.
Internal parameters are hard-coded in the library as enumerations and none of them have setters or getters associated.
- Timeout of waiting for connection result (
1 second
): It is a time interval injected to the system wifi library method called in a loop, which is waiting for connection result. - Default waiting period for next connection attempt (
5 seconds
): It is a time period since recent failed connection attempt, during which the system is waiting in non-blocking mode for next connection attempt. This time period does not have effect at permanent failures like wrong password or wifi network name. In that cases the wifi management and timeouts are under control of the system library. - Minimal waiting period for next connection attempt (
0 seconds
): Minimal value, to which the input value is limited. The zero period means immediate reconnection after connection lost. - Maximal waiting period for next connection attempt (
60 seconds
): Maximal reasonable value, to which the input value is limited. - Caching period of the pinging result to a gateway (
1 minute
). Time period for caching successful ping result to a gateway (wifi router). If the ping is requested sooner after previous real pinging, the result of that ping is return instead of providing the real ping. The time period prevents frequent pinging to the gateway provided by various methods of a firmware. - Refreshing period of the pinging result to a gateway (
5 minutes
): Time period for repeating ping to the gateway (wifi router) at active connection to wifi. This helps to determine broken connection to wifi even if the system connection check is successful, so that it prevents false positive wifi connection status. Thanks to caching pinging result, the real ping is executed at refreshing only if has not been provided recently withing caching period. - Safety number of connection result waits (
30
): Maximal number of waitings for connection result used by the safety counter for simulating the WiFiEventStationModeDisconnected handler.
- gbj_appcore: Parent application library loaded from the file
gbj_appcore.h
. - gbj_serial_debug: Auxilliary library for debug serial output loaded from the file
gbj_serial_debug.h
. It enables to exclude serial outputs from final compilation. - gbj_appsmooth: Application library for managing statistical smoothing, here RSSI values.
- gbj_running: General library for executing statistical smoothing, here median.
- Arduino.h: Main include file for the Arduino platform.
- ESP8266WiFi.h: Main include file for the wifi connection.
- Arduino.h: Main include file for the Arduino platform.
- WiFi.h: Main include file for the wifi connection.
Library is not intended to be utilized on platforms without WiFi capabality.
- gbj_appwifi()
- begin()
- run()
- connectSuccess()
- connectFail()
- pingGW()
- pingDNS()
- getStatus()
- getEventMillis()
- getHostname()
- getAddressIp()
- getAddressMac()
- getIdMac()
- getRssi()
- getRssiSmooth()
- setRssiSmooth()
- getEventMillis()
- getPeriod()
- setPeriod()
- isConnected()
- isContact()
The template or the signature of a callback function for ESP32 microcontroller, which is called at particular event in the wifi processing. It is utilized for processing connection process of the MCU to a wifi access point.
- A callback function can be declared with
void
type as well in the main sketch.
typedef void (*cbEvent_t)(arduino_event_id_t, arduino_event_info_t)
-
arduino_event_id_t: Numeric type of an event occured.
- Valid values: integer
- Default value: none
-
arduino_event_info_t: Structure with an event parameters.
- Valid values: structure
- Default value: none
None
The template or the signature of a callback function for ESP8266 microcontroller, which is called at gaining an IP address after connecting to a wifi access point.
- A callback function can be declared with
void
type as well in the main sketch.
typedef void (*cbGotIP_t)(const WiFiEventStationModeGotIP &)
- WiFiEventStationModeGotIP: Template of a callback function called at gaining IP address.
- Valid values: pointer
- Default value: none
None
The template or the signature of a callback function for ESP8266 microcontroller, which is called at disconnecting from a wifi access point.
- A callback function can be declared with
void
type as well in the main sketch.
typedef void (*cbDisconnect_t)(const WiFiEventStationModeDisconnected &);
- WiFiEventStationModeDisconnected: Template of a callback function called at disconnecting from access point.
- Valid values: pointer
- Default value: none
None
Overloaded constructor creates the class instance object and initiates internal resources.
- It inputs credentials for a wifi network.
- It enables set network parameters for setting the static IP address.
gbj_appwifi(const char *ssid, const char *pass, const char *hostname)
gbj_appwifi(const char *ssid, const char *pass, const char *hostname,
const IPAddress staticIp, const IPAddress gateway, const IPAddress subnet,
const IPAddress primaryDns, const IPAddress secondaryDns)
-
ssid: Pointer to the name of the wifi network to connect to.
- Valid values: constant pointer to string
- Default value: none
-
pass: Pointer to the passphrase for the wifi network.
- Valid values: constant pointer to string
- Default value: none
-
hostname: Pointer to the hostname for a device on the network.
- Valid values: constant pointer to string
- Default value: none
-
staticIp: IP address to be set as static (fixed) one for the microcontroller. It consists from 4 octets in case of IPv4 addressing and is usually defined as compiler macro in a main sketch.
- Data type: IPAddress
- Default value: none
-
gateway: IP address of the gateway (router) in the network.
- Data type: IPAddress
- Default value: none
-
subnet: Subnet mask of the network. It consists from 4 octets in case of IPv4 addressing.
- Data type: IPAddress
- Default value: none
-
primaryDns: Optional IP address of the primary DNS server used. It can be the address of the gateway, if it ensures DNS connectivity.
- Data type: IPAddress
- Default value: empty address
-
secondaryDns: Optional IP address of the secondary DNS server used. It is empty, if the gateway ensures DNS connectivity.
- Data type: IPAddress
- Default value: empty address
Object performing connection and reconnection to the wifi network.
For case with dynamic IP address assigned by a DHCP server:
gbj_appwifi wifi = gbj_appwifi(WIFI_SSID, WIFI_PASS, WIFI_HOSTNAME);
For case with static IP address assigned in the firmware and defined usually by compiler macros:
gbj_appwifi wifi = gbj_appwifi(WIFI_SSID,
WIFI_PASS,
WIFI_HOSTNAME,
IPAddress(IP_STATIC),
IPAddress(IP_GATEWAY),
IPAddress(IP_SUBNET),
IPAddress(IP_DNS_PRIMARY),
IPAddress(IP_DNS_SECONDARY));
For case with static IP address assigned in the firmware and defined directly in a main sketch without DNS servers:
gbj_appwifi wifi = gbj_appwifi(WIFI_SSID,
WIFI_PASS,
WIFI_HOSTNAME,
IPAddress(192, 168, 0, 20),
IPAddress(192, 168, 0, 1),
IPAddress(255, 255, 255, 0));
The initialization method of the instance object, which should be called in the setup section of a sketch.
- The method registers callback functions for connection and disconnection of the MCU to wifi.
- Callback functions should be defined in the main sketch.
// ESP8266
void begin(cbGotIP_t cbGotIp, cbDisconnect_t cbDisconnected)
// ESP32
void begin(cbEvent_t cbGotIp, cbEvent_t cbDisconnected)
-
cbGotIp: Pointer (only name) to a callback function fired at getting the IP address for the MCU, which is the final moment of the successful connection to wifi.
- Valid values: pointer
- Default value: none
-
cbDisconnected: Pointer (only name) to a callback function fired at loosing connection of the MCU to wifi.
- Valid values: pointer
- Default value: none
None
The execution method should be called frequently, usually in the loop function of a main sketch.
- The method connects to the wifi network at the very first calling it and reconnects to it if neccesary.
- If the serial connection is active, the library outputs flow of the connection and at success lists basic parameters of the connection to wifi.
void run()
None
None
The method processes the successful connection to wifi network.
- The method should be called in success handler for the event WiFiEventStationModeGotIP.
- If the serial connection is active, the method outputs basic parameters of the connection to wifi.
void connectSuccess()
None
None
For handler as a lambda function.
WiFiEventHandler wifiConnectHandler;
void setup()
{
wifiConnectHandler = WiFi.onStationModeGotIP(
[](const WiFiEventStationModeGotIP &event)
{
wifi.connectSuccess();
});
}
For handler as a separate function.
WiFiEventHandler wifiConnectHandler;
void onWifiConnect(const WiFiEventStationModeGotIP &event)
{
wifi.connectSuccess();
}
void setup()
{
wifiConnectHandler = WiFi.onStationModeGotIP(onWifiConnect);
}
The method processes the failed connection to wifi network.
- The method should be called in failure handler for the event WiFiEventStationModeDisconnected.
- If the serial connection is active, the method outputs the reason status of failed connection to wifi.
void connectFail()
None
None
For handler as a lambda function.
WiFiEventHandler wifiDisconnectHandler;
void setup()
{
wifiDisconnectHandler = WiFi.onStationModeDisconnected(
[](const WiFiEventStationModeDisconnected &event)
{
wifi.connectFail();
});
}
For handler as a separate function.
WiFiEventHandler wifiDisconnectHandler;
void onWifiDisconnect(const WiFiEventStationModeDisconnected &event)
{
wifi.connectFail();
}
void setup()
{
wifiDisconnectHandler = WiFi.onStationModeDisconnected(onWifiDisconnect);
}
The method executes ping to the current gateway IP, only if there is a connection to a wifi access point.
- The ping should detect false wifi status as connected, while the real connection has been broken.
- The success ping result is cached in order to eliminate frequent pinging from various methods. In normal operation state the real pinging is executed usually at most once a minute.
bool pingGW(byte pingCnt)
- pingCnt: The number of pings executed.
- Valid values: 0 ~ 255
- Default value: 2
Flag about pinging to a wifi gateway.
The method executes ping to the DNS server IP defined as input argument only if where is a connection to a wifi access point.
- The ping should detect disconnection from internet.
bool pingDNS(const IPAddress dnsIP, byte pingCnt)
-
dnsIP: The IP address used for pinging.
- Valid values: IPv4
- Default value: None
-
pingCnt: The number of pings executed.
- Valid values: 0 ~ 255
- Default value: 2
Flag about pinging to a DNS server.
The method returns the timestamp of the recent event, which can be:
- firing success handler at connecting to wifi,
- firing failure handler at disconnection or failed connection attempt.
unsigned long getEventMillis()
None
A timestamp of the recent wifi event.
The method returns recent status of the connection to wifi in textual form.
String getStatus()
None
A textual wifi status desription.
The method returns the hostname of the microcontroller connected to the wifi network.
- It might be used as a microcontroller's identifier on a network.
const char* getHostname()
None
A pointer to the constant string with hostname of the microcontroller on the network.
The method returns the IPv4 address of the microcontroller connected to the wifi network.
- It may changed at wifi reconnection, if no static address is set.
const char* getAddressIp()
None
A pointer to the constant string with IPv4 address of the microcontroller on the network.
The method returns the MAC address of the microcontroller connected to the wifi network.
- It might be used as a microcontroller's hardware identifier or for setting a static IP address on a network.
const char* getAddressMac()
None
A pointer to the constant string with MAC address of the microcontroller.
The method returns the identifier of the microcontroller composed of least significat bytes of its MAC address as a 16 bit usigned interger.
- It might be used as a short microcontroller's identifier, e.g., for ESP-NOW communication in many-to-one pattern.
unsigned it getIdMac()
None
An unsigned integer identifier of the microcontroller.
The method returns the current RSSI value of the microcontroller connected to the wifi network. Values are negative and in dBm.
int getRssi()
None
Current wifi signal strength of the microcontroller in dBm.
The method returns the recent statistically smoothed RSSI value for previous set of provided values by the setter.
- If the microcontroller is not connected to wifi, the method returns current RSSI value.
- Because corresponding setter returns the smoothed value as well, this getter is useful only for repeating fetching recent smoothed value without adding new value to the internal smoothing function.
int getRssiSmooth()
None
Smoothed wifi signal strength of the microcontroller in dBm.
The method puts current RSSI value to the internal smoothing function for statistically smoothing RSSI values.
- At the same time the setter returns the currently calculated smoothed value by the getter getRssiSmooth(), so that only this setter is needed for smoothing RSSI.
- The setter should be called at reasonable time intervals, usually in publishing or eventing periods.
int setRssiSmooth()
None
Smoothed wifi signal strength of the microcontroller in dBm.
The method returns timestamp of the recent connection event, successful or failed connection attempt to a wifi network in milliseconds.
unsigned long getEventMillis()
None
Recent timestamp of the wifi connection event in milliseconds.
The method returns current waiting period.
unsigned long getPeriod()
None
Current waiting period in milliseconds.
The overloaded method sets a new waiting period for a next reconnection attempt to a wifi network after failed previous one. The period can set in milliseconds or seconds.
- The method with numerical input argument is aimed for input in milliseconds.
- The method with textual input argument is aimed for input in seconds. It is useful with conjunction with a project data hub, which data has always string data type.
- The input period is sanitized and constraint for minimal and maximal value.
- No input argument sets the internal default period, which is setter's default value.
void setPeriod(unsigned long period)
void setPeriod(String periodSec)
-
period: Duration of the waiting period in milliseconds.
- Valid values: 0 ~ 2^32 - 1
- Default value: 15000
-
periodSec: Duration of the waiting period in seconds declared as string.
- Valid values: String
- Default value: none
None
The method returns a flag whether the microcontroller is connected to the wifi.
bool isConnected()
None
Flag about connecting status to wifi.
The method returns a flag whether the microcontroller is really connected to the wifi, i.e., it provides ping to a gateway as well.
bool isContact()
None
Flag about connecting status to wifi.