112 lines
2.6 KiB
C++
112 lines
2.6 KiB
C++
#include "GSMMobileData.h"
|
|
#include <SoftwareSerial.h>
|
|
#include "GSMMobileDevice.h"
|
|
#include "DebugLog.h"
|
|
#include "Helper.h"
|
|
|
|
//#define DEBUG
|
|
|
|
void GSMMobileDevice::init()
|
|
{
|
|
// init software serial
|
|
_gsmSerial.begin(_baudRate);
|
|
delay(5000); // initialization GSM module (give it some time to boot up)
|
|
}
|
|
|
|
void GSMMobileDevice::end()
|
|
{
|
|
_gsmSerial.end();
|
|
#ifdef DEBUG
|
|
DebugLog::log("GSM End ..");
|
|
#endif
|
|
}
|
|
|
|
void GSMMobileDevice::executeAtCommand(const String &atCommand)
|
|
{
|
|
#ifdef DEBUG
|
|
DebugLog::log(atCommand);
|
|
#endif
|
|
|
|
_gsmSerial.print(atCommand + "\r");
|
|
delay(500);
|
|
#ifdef DEBUG
|
|
DebugLog::log("read fromGMS:" + readStringSerialPort());
|
|
delay(100);
|
|
#endif
|
|
}
|
|
|
|
String GSMMobileDevice::readStringSerialPort()
|
|
{
|
|
return _gsmSerial.readString();
|
|
}
|
|
|
|
void GSMMobileDevice::sendSMSToGSM(GSMMobileData gsmData)
|
|
{
|
|
#ifdef DEBUG
|
|
DebugLog::log("SMS Start SEND SMS Id:" + gsmData.Id + " M:" + gsmData.MobileNumber + " with message " + gsmData.Sms);
|
|
#endif
|
|
executeAtCommand("AT+CMGF=1");
|
|
|
|
executeAtCommand("AT + CMGS =\"" + gsmData.MobileNumber + "\"");
|
|
executeAtCommand("ID:" + gsmData.Id + " Msg:" + gsmData.Sms);
|
|
|
|
delay(1000);
|
|
// Send a Ctrl+Z / ASCII SUB
|
|
_gsmSerial.print((char)26);
|
|
delay(500);
|
|
// Close the connection
|
|
_gsmSerial.print((char)27);
|
|
delay(500);
|
|
}
|
|
|
|
bool GSMMobileDevice::checkSMSError()
|
|
{
|
|
return true;
|
|
String response = readStringSerialPort();
|
|
if (response.indexOf("ERROR") != -1)
|
|
{
|
|
// If there was an error, try to reconnect and resend
|
|
_gsmSerial.println("AT+CFUN=1,1"); // Restart the module
|
|
delay(15000); // Wait for the module to restart
|
|
return true;
|
|
}
|
|
return false;
|
|
}
|
|
|
|
unsigned long _lastSMSTime = 0;
|
|
|
|
void GSMMobileDevice::sendSMS(GSMMobileData gsmData)
|
|
{
|
|
// Check if enough time has passed since the last SMS was sent
|
|
if (millis() - _lastSMSTime >= 60000)
|
|
{
|
|
// Send the SMS
|
|
init();
|
|
sendSMSToGSM(gsmData);
|
|
if (checkSMSError())
|
|
{
|
|
// Log that the SMS was sent
|
|
DebugLog::log("SMS sent successfully.");
|
|
}
|
|
else
|
|
{
|
|
// Log that the SMS was not sent
|
|
DebugLog::log("SMS not sent. Error occurred.");
|
|
}
|
|
// Update the last SMS time
|
|
_lastSMSTime = millis();
|
|
end();
|
|
}
|
|
else
|
|
{
|
|
// Log that the SMS was not sent
|
|
DebugLog::log("SMS not sent. Not enough time has passed since the last SMS was sent.");
|
|
}
|
|
}
|
|
|
|
// GSMMobileDevice::~GSMMobileDevice()
|
|
// {
|
|
// // // close gsmSerial
|
|
// // // close gsmSerial
|
|
// _gsmSerial.end();
|
|
// }
|