Relevant General Configuration:
- Electron
- 3rd Party SIM
- SYSTEM_THREAD(ENABLED);
When using a 3rd party SIM card with the Electron, the default keepAlive interval needs to be adjusted to a lower value to keep the return connection from the Particle Cloud open. That interval more or less is experimentally determined and will vary depending on the SIM provider but generally ranges from 30 seconds to a few minutes.
When I first started using a 3rd party SIM card in a multi-threaded program I had issues getting the electron to stay connected to the Particle cloud. While I could reliably send data to other servers via my MQTT client, I couldn’t connect to Particle. Here is an example of code that does NOT work properly, at least in my testing:
// electron-hardware-test.ino
// THIS DOES NOT WORK
STARTUP(cellular_credentials_set("hologram", "", "", NULL));
SYSTEM_THREAD(ENABLED);
void setup() {
Particle.keepAlive(30);
}
void loop() {
}
Based on this thread I had expected that putting the keepAlive call in the setup function would work, but I found this to not be reliably true for me. Even when setting keepAlive to 30 seconds (which is as low as it should need to be) I would disconnect after my SIM provider’s timeout period of approx 120seconds. This made me think that keepAlive wasn’t getting properly set.
I found the solution for me to be moving the keepAlive call into the main loop, and only calling it once Particle finished connecting to the cloud for the first time (essentially emulating the networking state flow of single threaded operation where setup waits for the cloud connection). The following code has seemed to work reliably for me:
// electron-hardware-test.ino
// THIS DOES WORK
STARTUP(cellular_credentials_set("hologram", "", "", NULL));
SYSTEM_THREAD(ENABLED);
bool keepAlive_set = false;
void setup() {
}
void loop() {
if (!keepAlive_set && Particle.connected())
{
Particle.keepAlive(30);
keepAlive_set = true;
}
}
I found this workaround to be non-intuitive and underdocumented. I would suggest a slight documentation update to indicate what the requirement is for keepAlive to be properly set in the context of SYSTEM_THREAD (which I’m assuming is initial cloud connectivity). Alternatively, ideally if there was some way to ensure that value got set regardless of when it was called that would be more intuitive. I hope this is helpful for anyone else trying to use a 3rd party SIM in threaded mode.