Network
The Network class can be used instead of Cellular or WiFi and represents the set of features common across all supported networking types: Cellular, Wi-Fi, and Ethernet.
There are two common uses for this:
- When you have code that runs on both Wi-Fi and Cellular devices, and you want to work automatically with the default network interface without having to use
#ifdef. - When you are writing a library or module within a large application and want to be able to work with a specific interface that is decided on by the caller.
// EXAMPLE
#include "Particle.h"
#ifndef SYSTEM_VERSION_v620
SYSTEM_THREAD(ENABLED); // System thread defaults to on in 6.2.0 and later and this line is not required
#endif
SerialLogHandler logHandler;
class ExampleModule {
public:
ExampleModule &withNetwork(NetworkClass &network) {
this->network = network;
return *this;
}
void setup() {
}
void loop() {
bool ready = network.ready();
if (ready != lastReady) {
lastReady = ready;
Log.info("ready=%d", (int) ready);
}
}
NetworkClass &network = Network;
bool lastReady = false;
};
ExampleModule exampleModule;
void setup() {
exampleModule
.withNetwork(Ethernet)
.setup();
}
void loop() {
exampleModule.loop();
}
This example prints when the network changes to or from ready state. By default, it uses Network, the default networking for this device. However, the caller can use the withNetwork() method to pass in a different network. In this example, it changes the behavior to monitor the Ethernet network instead.
When using the switchable network, it uses network (lowercase, the member variable), instead of Network (default interface), or a specific interface like Cellular or WiFi.