Dear all, I’m starting my first project with Electron.
This project was previously based and operative with Arduino, but I’m now moving to Electron.
Basically it is an environmental remote monitoring box, where the sensors are red every 5 minutes and the data sent to our web cloud by TCP client. At our server a PHP script takes care of data receiving and DB uploading.
Being pretty new to E., I was really looking for some support and advice about the most reliable connection routine in 2G/3G network.
I will use a 3rd party SIM and I will use my own cloud server.
Looking other Topics and forum’s discussions I was able to arrange this code, which I present here (the very essential part). What do you think about this code?
Really thanks for any support.
Best
Michele
#include <cellular_hal.h>
// network and APN data
SYSTEM_MODE(MANUAL); // do not autoconnect to particle cloud
SYSTEM_THREAD(ENABLED); // enable threading
STARTUP(cellular_credentials_set("mobile.vodafone.it", "", "", NULL)); // custom APN configuration
// Global Functions ============================================================
/*
* Connect to the network
*/
bool SIM_connect()
{
int i;
Serial.println("starting the modem...");
Cellular.on(); // turns on the modem
delay(5000);
Serial.println("now connecting to network...");
while(!Cellular.ready()) //wait until condition is true
{
Serial.print("connection try n°: ");
Serial.println(i);
Cellular.connect(); // make network connection to APN
delay(1000);
i++;
if (i == 4) break; // retry 3 times before giving up
}
if (Cellular.ready()) {
Serial.println("OK connected to network");
return true;
}
else {
Serial.println("error, NOT connected");
return false;
}
} // end of function
/*
* Disconnect from the network
*/
void SIM_disconnect()
{
Serial.println("now disconnecting the network...");
Cellular.disconnect(); // close network connection to APN
delay(5000);
Serial.println("now powering off the modem...");
Cellular.off(); // modem power off
delay(5000);
if (!Cellular.ready()) {
Serial.println("OK disconnected to network");
} else Serial.println("error while disconnecting");
} // end of function
/*
* Read data from the sensors
*/
void DataRead()
{
// here I read the sensors, both analog and digital
}
/*
* Send data to our cloud server
*/
void DataSend()
{
// here I send data to my cloud by TCP client
}
// Setup =======================================================================
void setup()
{
unsigned long now = millis(); // give some time after wake-up
if (now < 20000) {
return;
}
Serial.begin(9600);
}
// Main Loop ===================================================================
void loop()
{
if (SIM_connect()) // if true, read and send data
{
DataRead(); // now read the sensors
DataSend(); // now send the data
SIM_disconnect(); // now disconnect
}
System.sleep(SLEEP_MODE_DEEP,360); // Put the device into deep sleep. The device LED will shut off during deep sleep
}