-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSource-Code
More file actions
574 lines (503 loc) · 19.9 KB
/
Copy pathSource-Code
File metadata and controls
574 lines (503 loc) · 19.9 KB
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
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
/*
* MultiZoneGeofence.ino
* GL868_ESP32 Library — Multi-Zone Geofencing with Cloud Tracking (v12)
*
* FIXES vs v11:
* [F1] SMS fires only once on ENTER, once on EXIT — never while staying inside:
* - loadZoneStates() now RESTORES insideNow from NVS flash instead of
* clearing it. prefs.clear() was the root cause — it reset insideNow
* to false every boot so checkGeofences() always saw a fresh "entry"
* and sent a new SMS on every poll cycle.
* - A firstFixDone flag is used so the very first fix after a cold boot
* does a silent boundary sync (sets insideNow without alerting) before
* alerts are armed. This prevents false ENTER alerts on power-on.
* - checkGeofences() only calls sendGeofenceAlert() when
* nowInside != zones[i].insideNow (genuine transition).
*
* [F2] Zone coordinates corrected back to original values (v11 had
* Office and Restricted Area lat/lon swapped in zones[]).
*
* ALL WORKING FEATURES RETAINED FROM v11:
* - Raw AT SMS with CRLF line endings (no "No SMS prompt" error)
* - GPRS detach before SMS/call, reattach after
* - Non-blocking voice call ticker
* - Manual GPRS attach + custom HTTP POST (no library sleep loop)
* - GPS-loss SMS alert
* - Zone state saved to NVS on every transition
*/
#include <GL868_ESP32.h>
#include <math.h>
#include <Preferences.h>
// ============================================================================
// Configuration
// ============================================================================
#define DEVICE_ID "YourdeviceID"
#define API_KEY "YourAPIKey"
#define ALERT_NUMBER "YourPhoneNumber"
#define GPS_TIMEOUT 30000UL
#define GPS_MAX_RETRIES 3
#define GPS_POLL_INTERVAL 5000UL
#define CLOUD_SEND_INTERVAL 30 // seconds
#define GPS_LOSS_ALERT_POLLS 3
#define CALL_RING_DURATION 15000UL
#define CALL_PENDING_DELAY 3000UL
#define TIME_OFFSET_HOURS 5
#define TIME_OFFSET_MINS 30
#define HYSTERESIS_METERS 20.0
#define CIPSHUT_SETTLE_MS 2000UL
#ifndef DEG_TO_RAD
static constexpr double DEG_TO_RAD = M_PI / 180.0;
#endif
// ============================================================================
// Geofence zones
// restricted = false → SMS only on enter/exit
// restricted = true → SMS + voice call on enter/exit
// ============================================================================
struct GeofenceZone {
const char *name;
double latitude;
double longitude;
double radiusMeters;
bool restricted;
bool insideNow; // runtime — persisted to NVS on every change
};
GeofenceZone zones[] = {
{ "Home", 12.971600, 77.594600, 150.0, false, false },
{ "College", 12.934500, 77.626000, 200.0, false, false },
{ "Office", 12.958000, 77.650000, 200.0, false, false },
{ "Restricted Area", 11.011158, 77.013307, 200.0, true, false },
};
constexpr int ZONE_COUNT = sizeof(zones) / sizeof(zones[0]);
static_assert(ZONE_COUNT > 0, "zones[] must not be empty");
// ============================================================================
// Runtime state
// ============================================================================
static Preferences prefs;
static uint32_t lastPollTime = 0;
static uint32_t lastCloudPush = 0;
static int gpsFailStreak = 0;
static bool gpsLossAlertSent = false;
static bool gprsAttached = false;
static bool callInProgress = false;
static uint32_t callStartTime = 0;
static bool pendingCall = false;
static uint32_t pendingCallTimer = 0;
// [F1] After cold boot, first fix silently syncs insideNow without alerting.
// This prevents false ENTER SMS when the device powers on inside a zone.
static bool firstFixDone = false;
// ============================================================================
// [F1] Zone state persistence — RESTORE from flash, never clear on boot
// ============================================================================
static void saveZoneStates() {
prefs.begin("gfence", false);
for (int i = 0; i < ZONE_COUNT; i++) {
char key[8];
snprintf(key, sizeof(key), "z%d", i);
prefs.putBool(key, zones[i].insideNow);
}
prefs.end();
}
static void loadZoneStates() {
prefs.begin("gfence", true); // read-only open
for (int i = 0; i < ZONE_COUNT; i++) {
char key[8];
snprintf(key, sizeof(key), "z%d", i);
// getBool returns the stored value, or false if key doesn't exist yet
zones[i].insideNow = prefs.getBool(key, false);
}
prefs.end();
Serial.println("[INIT] Zone states loaded from NVS:");
for (int i = 0; i < ZONE_COUNT; i++) {
Serial.printf(" %s → %s\n",
zones[i].name,
zones[i].insideNow ? "INSIDE (remembered)" : "outside");
}
}
// ============================================================================
// GPRS helpers
// ============================================================================
static void gprsDetach() {
if (!gprsAttached) return;
Serial.println("[GPRS] Detaching...");
GeoLinker.sendATCommand("+CIPSHUT", 5000);
gprsAttached = false;
delay(CIPSHUT_SETTLE_MS);
Serial.println("[GPRS] Detached.");
}
static void gprsReattach() {
if (gprsAttached) return;
Serial.println("[GPRS] Reattaching...");
if (GeoLinker.gsm.attachGPRS()) {
gprsAttached = true;
Serial.println("[GPRS] Attached.");
} else {
Serial.println("[GPRS] Failed — will retry next push.");
}
}
// ============================================================================
// Raw SMS (direct AT commands, CRLF line endings)
// ============================================================================
static bool sendRawSMS(const char *number, const char *message) {
HardwareSerial &mdm = GeoLinker.getModemSerial();
GeoLinker.sendATCommand("+CMGF=1", 2000);
GeoLinker.sendATCommand("+CSCS=\"GSM\"", 2000);
delay(200);
mdm.printf("AT+CMGS=\"%s\"\r", number);
Serial.printf("[SMS] AT+CMGS → %s\n", number);
// Wait up to 8 s for '>' prompt
uint32_t t = millis();
bool gotPrompt = false;
while (millis() - t < 8000) {
if (mdm.available()) {
if (mdm.read() == '>') { gotPrompt = true; break; }
}
delay(10);
}
if (!gotPrompt) {
Serial.println("[SMS] No '>' prompt — aborting.");
mdm.write(0x1B); // ESC
return false;
}
// Convert bare \n → \r\n on the wire
for (const char *p = message; *p; p++) {
if (*p == '\n' && (p == message || *(p - 1) != '\r')) mdm.write('\r');
mdm.write(*p);
}
mdm.write(0x1A); // Ctrl+Z to send
// Wait up to 30 s for +CMGS confirmation
t = millis();
while (millis() - t < 30000) {
if (mdm.available()) {
String line = mdm.readStringUntil('\n');
line.trim();
if (line.startsWith("+CMGS:")) {
Serial.println("[SMS] Delivered ✓");
return true;
}
if (line.indexOf("ERROR") >= 0) {
Serial.printf("[SMS] Error: %s\n", line.c_str());
return false;
}
}
delay(10);
}
Serial.println("[SMS] Timeout waiting for +CMGS.");
return false;
}
static bool sendReliableSMS(const char *number, const char *message) {
gprsDetach();
bool ok = sendRawSMS(number, message);
gprsReattach();
return ok;
}
// ============================================================================
// Raw voice call
// ============================================================================
static bool makeRawCall(const char *number) {
HardwareSerial &mdm = GeoLinker.getModemSerial();
while (mdm.available()) mdm.read(); // flush
mdm.printf("ATD%s;\r", number);
Serial.printf("[CALL] ATD → %s\n", number);
uint32_t t = millis();
while (millis() - t < 5000) {
if (mdm.available()) {
String line = mdm.readStringUntil('\n');
line.trim();
if (line == "OK") { Serial.println("[CALL] Ringing."); return true; }
if (line.indexOf("ERROR") >= 0 || line.indexOf("NO CARRIER") >= 0) {
Serial.printf("[CALL] Rejected: %s\n", line.c_str());
return false;
}
}
delay(20);
}
Serial.println("[CALL] No explicit OK — assuming ringing.");
return true;
}
// ============================================================================
// Non-blocking call ticker
// ============================================================================
static void tickCall() {
if (!callInProgress) return;
GeoLinker.update();
if (millis() - callStartTime >= CALL_RING_DURATION) {
GeoLinker.sendATCommand("H", 2000);
Serial.println("[CALL] Ring timeout — hung up.");
callInProgress = false;
delay(500);
gprsReattach();
}
}
// ============================================================================
// Haversine distance (metres)
// ============================================================================
static double haversineDistance(double lat1, double lon1,
double lat2, double lon2) {
const double R = 6371000.0;
double dLat = (lat2 - lat1) * DEG_TO_RAD;
double dLon = (lon2 - lon1) * DEG_TO_RAD;
double a = sin(dLat / 2) * sin(dLat / 2) +
cos(lat1 * DEG_TO_RAD) * cos(lat2 * DEG_TO_RAD) *
sin(dLon / 2) * sin(dLon / 2);
return R * 2.0 * atan2(sqrt(a), sqrt(1.0 - a));
}
static void sanitiseForSMS(char *dst, int dstLen, const char *src) {
int j = 0;
for (int i = 0; src[i] && j < dstLen - 1; i++) {
char c = src[i];
if (c == '\r') continue;
if (c == '"') { dst[j++] = '\''; continue; }
dst[j++] = c;
}
dst[j] = '\0';
}
// ============================================================================
// SMS body builder
// ============================================================================
static void buildAlertMessage(char *buf, int bufLen,
const char *verb, const char *zoneName,
GPSData *gps, bool hasLoc) {
char safe[64];
sanitiseForSMS(safe, sizeof(safe), zoneName);
int bat = GeoLinker.getBatteryPercent();
if (hasLoc) {
snprintf(buf, bufLen,
"%s %s\n%.6f,%.6f\nSpd:%.1f Bat:%d%%\nmaps.google.com/?q=%.6f,%.6f",
verb, safe,
gps->latitude, gps->longitude,
gps->speed, bat,
gps->latitude, gps->longitude);
} else {
snprintf(buf, bufLen,
"%s %s\nNo GPS fix\nBat:%d%%",
verb, safe, bat);
}
}
// ============================================================================
// Geofence alert dispatcher
// ============================================================================
static void sendGeofenceAlert(const char *zoneName, bool entered,
bool restricted, GPSData *gps, bool hasLoc) {
const char *verb = entered ? "ENTERED" : "LEFT";
Serial.printf("[ALERT] %s %s restricted:%s\n",
verb, zoneName, restricted ? "YES" : "NO");
char msg[256];
buildAlertMessage(msg, sizeof(msg), verb, zoneName, gps, hasLoc);
sendReliableSMS(ALERT_NUMBER, msg);
if (restricted && !callInProgress && !pendingCall) {
Serial.println("[ALERT] Scheduling voice call in 3 s...");
pendingCall = true;
pendingCallTimer = millis();
}
}
// ============================================================================
// GPS-loss alert
// ============================================================================
static void sendGPSLossAlert() {
char msg[160];
snprintf(msg, sizeof(msg),
"GPS Loss!\nDevice:%s\nFailed:%d polls\nBat:%d%%",
DEVICE_ID, gpsFailStreak, GeoLinker.getBatteryPercent());
Serial.println("[GPS] Sending GPS-loss SMS...");
sendReliableSMS(ALERT_NUMBER, msg);
}
// ============================================================================
// GPS acquisition
// ============================================================================
static bool getValidLocation(GPSData *gps) {
Serial.println("[GPS] Acquiring fix...");
for (int retry = 0; retry < GPS_MAX_RETRIES; retry++) {
Serial.printf("[GPS] Attempt %d/%d\n", retry + 1, GPS_MAX_RETRIES);
uint32_t start = millis();
while (millis() - start < GPS_TIMEOUT) {
GeoLinker.update();
if (GeoLinker.getLocationNow(gps) && gps->valid) {
Serial.printf("[GPS] Fix: %.6f, %.6f Sats:%d\n",
gps->latitude, gps->longitude, gps->satellites);
return true;
}
uint32_t sub = millis();
while (millis() - sub < 1000) { GeoLinker.update(); delay(25); }
}
Serial.println("[GPS] Timed out, retrying...");
}
Serial.println("[GPS] All retries failed.");
return false;
}
// ============================================================================
// [F1] Geofence checker
//
// firstFixDone == false (cold boot):
// Silently sync insideNow to current position. No alerts fired.
// This prevents a false "ENTERED" SMS when the device powers on
// inside a zone it was already in.
//
// firstFixDone == true (normal operation):
// Alert only on genuine transition (nowInside != zones[i].insideNow).
// While staying inside a zone, insideNow remains true and no alert fires.
// Alert fires exactly once on ENTER and once on EXIT.
// ============================================================================
static void checkGeofences(GPSData *gps, bool hasLoc) {
if (!hasLoc) { Serial.println("[FENCE] No fix — skipping."); return; }
bool stateChanged = false;
for (int i = 0; i < ZONE_COUNT; i++) {
double dist = haversineDistance(gps->latitude, gps->longitude,
zones[i].latitude, zones[i].longitude);
double enterThresh = zones[i].radiusMeters;
double exitThresh = zones[i].radiusMeters + HYSTERESIS_METERS;
// Hysteresis: use wider exit threshold once inside
bool nowInside = zones[i].insideNow ? (dist <= exitThresh)
: (dist <= enterThresh);
Serial.printf("[FENCE] %-18s | %7.1f m | enter:%.0f exit:%.0f | %-7s | %s\n",
zones[i].name, dist, enterThresh, exitThresh,
nowInside ? "INSIDE" : "outside",
zones[i].restricted ? "RESTRICTED" : "normal");
if (nowInside != zones[i].insideNow) {
zones[i].insideNow = nowInside;
stateChanged = true;
if (!firstFixDone) {
// Silent sync — just record position, no alert
Serial.printf("[FENCE] (silent sync) %s → %s\n",
zones[i].name, nowInside ? "inside" : "outside");
} else {
// Genuine transition after first fix — alert
sendGeofenceAlert(zones[i].name, nowInside,
zones[i].restricted, gps, hasLoc);
}
}
}
if (stateChanged) saveZoneStates();
// Arm alerts after the first real fix is processed
if (!firstFixDone) {
firstFixDone = true;
Serial.println("[FENCE] First-fix sync complete — alerts now armed.");
}
}
// ============================================================================
// Cloud push
// ============================================================================
static void cloudPush(GPSData *gps, bool hasLoc) {
if (!gprsAttached) { gprsReattach(); if (!gprsAttached) return; }
GeoLinker.json.clear();
const GPSData &src = hasLoc ? *gps : GeoLinker.getLastGPS();
GeoLinker.json.addDataPoint(src,
GeoLinker.getBatteryPercent(),
GeoLinker.getSignalStrength());
char payload[1024];
if (!GeoLinker.json.build(payload, sizeof(payload))) {
Serial.println("[CLOUD] JSON build failed."); return;
}
Serial.printf("[CLOUD] Push: %.6f, %.6f Bat:%d%%\n",
src.latitude, src.longitude, GeoLinker.getBatteryPercent());
int code = GeoLinker.gsm.httpPOST(
"http://www.circuitdigest.cloud/api/v1/geolinker",
API_KEY, "application/json", payload);
Serial.printf("[CLOUD] HTTP %d\n", code);
if (code == -1) {
Serial.println("[CLOUD] Failed — will reattach next push.");
gprsAttached = false;
}
}
// ============================================================================
// setup()
// ============================================================================
void setup() {
Serial.begin(115200);
delay(1000);
Serial.println("==============================================");
Serial.println(" Multi-Zone Geofencing GL868_ESP32 (v12)");
Serial.println("==============================================");
// [F1] Restore remembered zone positions from NVS (does NOT clear them)
loadZoneStates();
GeoLinker.setOperatingMode(MODE_SMS_CALL);
GeoLinker.setTimeOffset(TIME_OFFSET_HOURS, TIME_OFFSET_MINS);
GeoLinker.enableFullPowerOff(false);
GeoLinker.begin(DEVICE_ID, API_KEY);
Serial.println("[INIT] Waiting for modem IDLE...");
{
uint32_t t = millis();
while (GeoLinker.getState() != STATE_IDLE && millis() - t < 50000UL) {
GeoLinker.update(); delay(100);
}
Serial.printf("[INIT] Modem ready (%lu ms)\n", millis() - t);
}
Serial.println("[INIT] Attaching GPRS...");
if (GeoLinker.gsm.attachGPRS()) {
gprsAttached = true;
Serial.println("[INIT] GPRS attached.");
} else {
Serial.println("[INIT] GPRS failed — retrying on first push.");
}
GeoLinker.gpsOn();
Serial.println("[GPS] GPS powered on.");
Serial.println("\nConfigured Zones:");
Serial.println(" # Name Lat Lon Radius Alert Inside?");
Serial.println(" -- ------------------ ----------- ---------- -------- --------- -------");
for (int i = 0; i < ZONE_COUNT; i++) {
Serial.printf(" %d %-18s %.6f %.6f %.0f m %-9s %s\n",
i + 1, zones[i].name,
zones[i].latitude, zones[i].longitude,
zones[i].radiusMeters,
zones[i].restricted ? "SMS+CALL" : "SMS only",
zones[i].insideNow ? "YES (remembered)" : "no");
}
Serial.printf("\nAlert number : %s\n", ALERT_NUMBER);
Serial.printf("Poll interval : %lu ms\n", GPS_POLL_INTERVAL);
Serial.printf("Cloud interval: %d s\n\n", CLOUD_SEND_INTERVAL);
Serial.println("Monitoring started.\n");
lastPollTime = millis();
lastCloudPush = millis();
}
// ============================================================================
// loop()
// ============================================================================
void loop() {
GeoLinker.update();
// Pending call state machine
if (pendingCall && (millis() - pendingCallTimer >= CALL_PENDING_DELAY)) {
if (!callInProgress) {
gprsDetach();
Serial.println("[CALL] Initiating voice call...");
if (makeRawCall(ALERT_NUMBER)) {
callInProgress = true;
callStartTime = millis();
} else {
Serial.println("[CALL] Dial failed — reattaching GPRS.");
gprsReattach();
}
pendingCall = false;
}
}
tickCall();
// GPS poll gate
if (millis() - lastPollTime < GPS_POLL_INTERVAL) return;
lastPollTime = millis();
if (callInProgress) {
Serial.println("[LOOP] Call in progress — skipping poll.");
return;
}
GPSData gps = {};
bool hasLoc = getValidLocation(&gps);
if (hasLoc) {
if (gpsFailStreak > 0)
Serial.printf("[GPS] Restored after %d failure(s).\n", gpsFailStreak);
gpsFailStreak = 0;
gpsLossAlertSent = false;
} else {
gpsFailStreak++;
Serial.printf("[GPS] Failure %d/%d\n", gpsFailStreak, GPS_LOSS_ALERT_POLLS);
if (gpsFailStreak >= GPS_LOSS_ALERT_POLLS && !gpsLossAlertSent) {
sendGPSLossAlert();
gpsLossAlertSent = true;
}
}
// STEP 1: geofence alerts (SMS first, cloud after)
checkGeofences(&gps, hasLoc);
// STEP 2: cloud push (only if no alert/call activity)
if (!pendingCall && !callInProgress &&
millis() - lastCloudPush >= (uint32_t)CLOUD_SEND_INTERVAL * 1000UL) {
lastCloudPush = millis();
cloudPush(&gps, hasLoc);
}
Serial.printf("[LOOP] Done. Next in %lu ms\n\n", GPS_POLL_INTERVAL);
}