-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathArduinoCellular.cpp
356 lines (288 loc) · 10.6 KB
/
ArduinoCellular.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
#include "ArduinoCellular.h"
unsigned long ArduinoCellular::getTime() {
int year, month, day, hour, minute, second;
float tz;
modem.getNetworkTime(&year, &month, &day, &hour, &minute, &second, &tz);
return Time(year, month, day, hour, minute, second).getUNIXTimestamp();
}
ArduinoCellular::ArduinoCellular() {
}
void ArduinoCellular::begin() {
// set sim slot
modem.init();
String modemInfo = this ->sendATCommand("I");
if(modemInfo.indexOf("EC200A") > 0){
this->model = ModemModel::EC200;
} else if (modemInfo.indexOf("EG95") > 0){
this->model = ModemModel::EG95;
} else {
this->model = ModemModel::Unsupported;
}
// Set GSM module to text mode
modem.sendAT("+CMGF=1");
modem.waitResponse();
modem.sendAT(GF("+CSCS=\"GSM\""));
modem.waitResponse();
// Send intrerupt when SMS has been received
modem.sendAT("+CNMI=2,1,0,0,0");
modem.waitResponse();
ArduinoBearSSL.onGetTime(ArduinoCellular::getTime);
}
bool ArduinoCellular::connect(String apn, String gprsUser, String gprsPass, String pin){
SimStatus simStatus = getSimStatus();
if(simStatus == SimStatus::SIM_LOCKED && pin.length() > 0){
unlockSIM(pin.c_str());
}
simStatus = getSimStatus();
if(simStatus == SimStatus::SIM_READY) {
if(awaitNetworkRegistration()){
if(connectToGPRS(apn.c_str(), gprsUser.c_str(), gprsPass.c_str())){
if(this->debugStream != nullptr){
this->debugStream->println("Setting DNS...");
}
auto response = this->sendATCommand("+QIDNSCFG=1,\"8.8.8.8\",\"8.8.4.4\"");
if(this->debugStream != nullptr){
this->debugStream->println(response);
}
return true;
}
} else {
return false;
}
}
return false;
}
Location ArduinoCellular::getGPSLocation(unsigned long timeout){
if (model == ModemModel::EG95){
float latitude = 0.00000;
float longitude = 0.00000;
unsigned long startTime = millis();
while((latitude == 0.00000 || longitude == 0.00000) && (millis() - startTime < timeout)) {
modem.getGPS(&latitude, &longitude);
delay(1000);
}
Location loc;
loc.latitude = latitude;
loc.longitude = longitude;
return loc;
} else {
if(this->debugStream != nullptr){
this->debugStream->println("Unsupported modem model");
}
return Location();
}
}
Time ArduinoCellular::getGPSTime(){
int year, month, day, hour, minute, second;
modem.getGPSTime(&year, &month, &day, &hour, &minute, &second);
return Time(year, month, day, hour, minute, second);
}
Time ArduinoCellular::getCellularTime(){
int year, month, day, hour, minute, second;
float tz;
modem.getNetworkTime(&year, &month, &day, &hour, &minute, &second, &tz);
return Time(year, month, day, hour, minute, second);
}
void ArduinoCellular::sendSMS(String number, String message){
modem.sendAT(GF("+CMGS=\""), number, GF("\""));
if (modem.waitResponse(GF(">")) != 1) { }
modem.stream->print(message); // Actually send the message
modem.stream->write(static_cast<char>(0x1A)); // Terminate the message
modem.stream->flush();
auto response = modem.waitResponse(10000L);
if(this->debugStream != nullptr){
this->debugStream->println("Response: " + String(response));
}
}
IPAddress ArduinoCellular::getIPAddress(){
return modem.localIP();
}
int ArduinoCellular::getSignalQuality(){
return modem.getSignalQuality();
}
TinyGsmClient ArduinoCellular::getNetworkClient(){
return TinyGsmClient(modem);
}
HttpClient ArduinoCellular::getHTTPClient(const char * server, const int port){
return HttpClient(* new TinyGsmClient(modem), server, port);
}
HttpClient ArduinoCellular::getHTTPSClient(const char * server, const int port){
return HttpClient(* new BearSSLClient(* new TinyGsmClient(modem)), server, port);
}
BearSSLClient ArduinoCellular::getSecureNetworkClient(){
return BearSSLClient(* new TinyGsmClient(modem));
}
bool ArduinoCellular::isConnectedToOperator(){
return modem.isNetworkConnected();
}
bool ArduinoCellular::connectToGPRS(const char * apn, const char * gprsUser, const char * gprsPass){
if(this->debugStream != nullptr){
this->debugStream->println("Connecting to 4G network...");
}
while(!modem.gprsConnect(apn, gprsUser, gprsPass)) {
if(this->debugStream != nullptr){
this->debugStream->print(".");
}
delay(2000);
}
return true;
}
bool ArduinoCellular::isConnectedToInternet(){
return modem.isGprsConnected();
}
SimStatus ArduinoCellular::getSimStatus(){
int simStatus = modem.getSimStatus();
if(this->debugStream != nullptr){
this->debugStream->println("SIM Status: " + String(simStatus));
}
if (modem.getSimStatus() == 0) {
return SimStatus::SIM_ERROR;
} else if (modem.getSimStatus() == 1) {
return SimStatus::SIM_READY;
} else if (modem.getSimStatus() == 2) {
return SimStatus::SIM_LOCKED;
} else if (modem.getSimStatus() == 3) {
return SimStatus::SIM_ANTITHEFT_LOCKED;
} else {
return SimStatus::SIM_ERROR;
}
}
bool ArduinoCellular::unlockSIM(const char * pin){
if(this->debugStream != nullptr){
this->debugStream->println("Unlocking SIM...");
}
return modem.simUnlock(pin);
}
bool ArduinoCellular::awaitNetworkRegistration(){
if(this->debugStream != nullptr){
this->debugStream->println("Waiting for network registration...");
}
while (!modem.waitForNetwork()) {
if(this->debugStream != nullptr){
this->debugStream->print(".");
}
delay(2000);
}
return true;
}
bool ArduinoCellular::enableGPS(bool assisted){
if(this->debugStream != nullptr){
this->debugStream->println("Enabling GPS...");
}
if(assisted){
sendATCommand("AT+QGPSCFG=\"agpsposmode\",33488767");
} else {
sendATCommand("AT+QGPSCFG=\"agpsposmode\",8388608");
}
//modem.sendAT(GF("+UTIME=1,1"));
//modem.waitResponse();
//modem.sendAT(GF("+UGPIOC=23,0,1"));
//modem.waitResponse();
return modem.enableGPS();
//delay(10000);
}
String ArduinoCellular::sendATCommand( char * command, unsigned long timeout){
String resp;
modem.sendAT(const_cast<char *>(command));
modem.waitResponse(timeout, resp);
return resp;
}
Time parseTimestamp(const String ×tampStr) {
int hour, minute, second, day, month, year, offset;
int commaIndex = timestampStr.indexOf(',');
String date = timestampStr.substring(0, commaIndex);
String time = timestampStr.substring(commaIndex + 1, timestampStr.indexOf('+'));
String offsetStr = timestampStr.substring(timestampStr.indexOf('+') + 1);
int firstSlashIndex = date.indexOf('/');
int secondSlashIndex = date.lastIndexOf('/');
day = date.substring(0, firstSlashIndex).toInt();
month = date.substring(firstSlashIndex + 1, secondSlashIndex).toInt();
year = date.substring(secondSlashIndex + 1).toInt() + 2000;
int firstColonIndex = time.indexOf(':');
int secondColonIndex = time.lastIndexOf(':');
hour = time.substring(0, firstColonIndex).toInt();
minute = time.substring(firstColonIndex + 1, secondColonIndex).toInt();
second = time.substring(secondColonIndex + 1).toInt();
offset = offsetStr.toInt();
return Time(year, month, day, hour, minute, second, offset);
}
// Parses a single SMS entry from the data
SMS parseSMSEntry(const String& entry, const String& message) {
SMS sms;
int firstQuoteIndex = entry.indexOf('"');
int secondQuoteIndex = entry.indexOf('"', firstQuoteIndex + 1);
int thirdQuoteIndex = entry.indexOf('"', secondQuoteIndex + 1);
int fourthQuoteIndex = entry.indexOf('"', thirdQuoteIndex + 1);
int commaIndexBeforeTimestamp = entry.lastIndexOf(',', entry.lastIndexOf(',') - 1);
// Extracting number and raw timestamp
sms.number = entry.substring(thirdQuoteIndex + 1, fourthQuoteIndex);
String rawTimestamp = entry.substring(commaIndexBeforeTimestamp + 2, entry.indexOf('+', commaIndexBeforeTimestamp) + 3);
// Parse the timestamp
sms.timestamp = parseTimestamp(rawTimestamp);
sms.message = message;
return sms;
}
// Function to split a string into lines based on a delimiter character
// Filters out empty lines
std::vector<String> splitStringByLines(const String& input, char delimiter = '\n') {
std::vector<String> lines;
int startIndex = 0;
while (startIndex < input.length()) {
int endIndex = input.indexOf(delimiter, startIndex);
if (endIndex == -1)
endIndex = input.length();
String line = input.substring(startIndex, endIndex);
if(line.length() > 0 && line != "\r" && line != "\n" && line != "\r\n"){
// Remove trailing \r if it exists
if (line.endsWith("\r")) {
line.remove(line.length() - 1);
}
lines.push_back(line);
}
startIndex = endIndex + 1;
}
return lines;
}
// Splits the entire message string into individual SMS entries and parses them
std::vector<SMS> parseSMSData(const String& data) {
std::vector<SMS> smsList = std::vector<SMS>();
std::vector<String> lines = splitStringByLines(data);
// Remove last line if it's "OK"
if (lines.size() > 0 && lines[lines.size() - 1] == "OK") {
lines.pop_back();
}
for(int i = 0; i < lines.size(); i += 2){
if (lines[i].startsWith("+CMGL:")) {
String message = "";
if(i + 1 < lines.size()){
message = lines[i + 1];
}
SMS sms = parseSMSEntry(lines[i], message);
smsList.push_back(sms);
}
}
return smsList;
}
std::vector<SMS> ArduinoCellular::getReadSMS(){
String rawMessages = sendATCommand("+CMGL=\"REC READ\"");
if(rawMessages.indexOf("OK") == -1){
return std::vector<SMS>();
} else if (rawMessages.indexOf("ERROR") != -1){
return std::vector<SMS>();
} else {
return parseSMSData(rawMessages);
}
}
std::vector<SMS> ArduinoCellular::getUnreadSMS(){
String rawMessages = sendATCommand("+CMGL=\"REC UNREAD\"");
if(rawMessages.indexOf("OK") == -1){
return std::vector<SMS>();
} else if (rawMessages.indexOf("ERROR") != -1){
return std::vector<SMS>();
} else {
return parseSMSData(rawMessages);
}
}
void ArduinoCellular::setDebugStream(Stream &stream){
this->debugStream = &stream;
}