-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSource-Code
More file actions
424 lines (373 loc) · 14.3 KB
/
Copy pathSource-Code
File metadata and controls
424 lines (373 loc) · 14.3 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
/*
* TempGPSTracker.ino
* GL868_ESP32 (GeoLinker Board) + DS18B20 Temperature Probe
*
* FEATURES:
* - DS18B20 temperature reading every poll cycle (GPIO 42, internal pull-up)
* - SMS alert when temp > 75°C (HIGH) or < -5°C (LOW)
* - One alert per threshold crossing — no repeat spam
* - GPS location tracked and pushed to CircuitDigest cloud every 30s
* - Temperature included in cloud payload via setPayloads()
* - Raw AT SMS (reliable, bypasses modem state issues)
* - GPRS detach before SMS, reattach after
* - Cloud push skipped when no GPS fix (prevents HTTP 400)
*
* WIRING:
* DS18B20 DATA → GPIO 42 (internal pull-up used, no resistor needed)
* DS18B20 VCC → 3.3V
* DS18B20 GND → GND
*
* LIBRARIES (install via Arduino Library Manager):
* - OneWire by Paul Stoffregen
* - DallasTemperature by Miles Burton
*/
#include <GL868_ESP32.h>
#include <OneWire.h>
#include <DallasTemperature.h>
// ============================================================================
// Configuration
// ============================================================================
#define DEVICE_ID "yourdeviceid"
#define API_KEY "yourapikey"
#define ALERT_NUMBER "yourphonenumber"
#define ONE_WIRE_PIN 12
#define TEMP_HIGH_THRESHOLD 75.0f // °C — alert above this
#define TEMP_LOW_THRESHOLD -5.0f // °C — alert below this
#define TEMP_ERROR_VALUE -127.0f // DS18B20 error sentinel
#define GPS_TIMEOUT 60000UL // ms per GPS attempt
#define GPS_MAX_RETRIES 5
#define GPS_POLL_INTERVAL 5000UL // ms between polls
#define CLOUD_SEND_INTERVAL 30 // seconds between cloud pushes
#define GPS_LOSS_ALERT_POLLS 3
#define TIME_OFFSET_HOURS 5
#define TIME_OFFSET_MINS 30
#define CIPSHUT_SETTLE_MS 2000UL
// ============================================================================
// DS18B20
// ============================================================================
static OneWire oneWire(ONE_WIRE_PIN);
static DallasTemperature tempSensor(&oneWire);
// ============================================================================
// Runtime state
// ============================================================================
static uint32_t lastPollTime = 0;
static uint32_t lastCloudPush = 0;
static int gpsFailStreak = 0;
static bool gpsLossAlertSent = false;
static bool gprsAttached = false;
static bool highTempAlertSent = false;
static bool lowTempAlertSent = false;
// ============================================================================
// 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 via direct AT commands
// ============================================================================
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);
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);
return false;
}
for (const char *p = message; *p; p++) {
if (*p == '\n' && (p == message || *(p - 1) != '\r')) mdm.write('\r');
mdm.write(*p);
}
mdm.write(0x1A);
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.");
return false;
}
static bool sendReliableSMS(const char *number, const char *message) {
gprsDetach();
bool ok = sendRawSMS(number, message);
gprsReattach();
return ok;
}
// ============================================================================
// Temperature reading
// ============================================================================
static float readTemperature() {
tempSensor.requestTemperatures();
return tempSensor.getTempCByIndex(0);
}
// ============================================================================
// Temperature alert logic
// SMS fires once on threshold crossing, resets with 5°C hysteresis
// ============================================================================
static void checkTemperatureAlerts(float temp, GPSData *gps, bool hasLoc) {
if (temp == TEMP_ERROR_VALUE) {
Serial.println("[TEMP] Sensor error — skipping alert check.");
return;
}
// HIGH alert
if (temp > TEMP_HIGH_THRESHOLD && !highTempAlertSent) {
Serial.printf("[TEMP] HIGH ALERT: %.2f°C\n", temp);
char msg[200];
if (hasLoc) {
snprintf(msg, sizeof(msg),
"TEMP HIGH ALERT!\nDevice:%s\nTemp:%.2f C\nLimit:>%.0f C\n"
"Lat:%.6f\nLon:%.6f\nMap:maps.google.com/?q=%.6f,%.6f",
DEVICE_ID, temp, TEMP_HIGH_THRESHOLD,
gps->latitude, gps->longitude,
gps->latitude, gps->longitude);
} else {
snprintf(msg, sizeof(msg),
"TEMP HIGH ALERT!\nDevice:%s\nTemp:%.2f C\nLimit:>%.0f C\nNo GPS",
DEVICE_ID, temp, TEMP_HIGH_THRESHOLD);
}
sendReliableSMS(ALERT_NUMBER, msg);
highTempAlertSent = true;
}
if (temp <= TEMP_HIGH_THRESHOLD - 5.0f && highTempAlertSent) {
Serial.println("[TEMP] High temp resolved — alert reset.");
highTempAlertSent = false;
}
// LOW alert
if (temp < TEMP_LOW_THRESHOLD && !lowTempAlertSent) {
Serial.printf("[TEMP] LOW ALERT: %.2f°C\n", temp);
char msg[200];
if (hasLoc) {
snprintf(msg, sizeof(msg),
"TEMP LOW ALERT!\nDevice:%s\nTemp:%.2f C\nLimit:<%.0f C\n"
"Lat:%.6f\nLon:%.6f\nMap:maps.google.com/?q=%.6f,%.6f",
DEVICE_ID, temp, TEMP_LOW_THRESHOLD,
gps->latitude, gps->longitude,
gps->latitude, gps->longitude);
} else {
snprintf(msg, sizeof(msg),
"TEMP LOW ALERT!\nDevice:%s\nTemp:%.2f C\nLimit:<%.0f C\nNo GPS",
DEVICE_ID, temp, TEMP_LOW_THRESHOLD);
}
sendReliableSMS(ALERT_NUMBER, msg);
lowTempAlertSent = true;
}
if (temp >= TEMP_LOW_THRESHOLD + 5.0f && lowTempAlertSent) {
Serial.println("[TEMP] Low temp resolved — alert reset.");
lowTempAlertSent = false;
}
}
// ============================================================================
// 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;
}
// ============================================================================
// Cloud push — GPS + temperature
// Skips push if no GPS fix to avoid HTTP 400 (empty timestamp)
// ============================================================================
static void cloudPush(GPSData *gps, float temp) {
if (!gprsAttached) { gprsReattach(); if (!gprsAttached) return; }
// Block push entirely if sensor is not working
if (temp == TEMP_ERROR_VALUE) {
Serial.println("[CLOUD] Skipping — temperature sensor error (-127).");
return;
}
GeoLinker.setPayloads({ { "temperature", temp } });
GeoLinker.json.clear();
GeoLinker.json.addDataPoint(*gps,
GeoLinker.getBatteryPercent(),
GeoLinker.getSignalStrength());
char payload[1024];
if (!GeoLinker.json.build(payload, sizeof(payload))) {
Serial.println("[CLOUD] JSON build failed.");
GeoLinker.clearPayloads();
return;
}
Serial.printf("[CLOUD] Push: %.6f, %.6f Temp:%.2f°C Bat:%d%%\n",
gps->latitude, gps->longitude,
temp, 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);
GeoLinker.clearPayloads();
if (code == -1) {
Serial.println("[CLOUD] Failed — will reattach next push.");
gprsAttached = false;
}
}
// ============================================================================
// GPS-loss SMS
// ============================================================================
static void sendGPSLossAlert(float temp) {
char msg[160];
snprintf(msg, sizeof(msg),
"GPS Loss!\nDevice:%s\nFailed:%d polls\nTemp:%.2f C\nBat:%d%%",
DEVICE_ID, gpsFailStreak, temp, GeoLinker.getBatteryPercent());
Serial.println("[GPS] Sending GPS-loss SMS...");
sendReliableSMS(ALERT_NUMBER, msg);
}
// ============================================================================
// setup()
// ============================================================================
void setup() {
Serial.begin(115200);
delay(1000);
Serial.println("==============================================");
Serial.println(" Temp + GPS Tracker GL868_ESP32 + DS18B20");
Serial.println("==============================================");
// DS18B20 — internal pull-up, no external resistor needed
pinMode(ONE_WIRE_PIN, INPUT_PULLUP);
tempSensor.begin();
tempSensor.setResolution(12);
int sensorCount = tempSensor.getDeviceCount();
Serial.printf("[TEMP] DS18B20 sensors found: %d\n", sensorCount);
if (sensorCount == 0) {
Serial.println("[TEMP] WARNING: No sensor detected on GPIO 42 — check wiring!");
}
// Scan OneWire bus and print addresses (useful for debugging)
DeviceAddress addr;
oneWire.reset_search();
while (oneWire.search(addr)) {
Serial.print("[TEMP] Device address: ");
for (int i = 0; i < 8; i++) Serial.printf("%02X ", addr[i]);
Serial.println();
}
// GeoLinker init
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("\n──────────────────────────────────────");
Serial.printf("Device ID : %s\n", DEVICE_ID);
Serial.printf("Alert number : %s\n", ALERT_NUMBER);
Serial.printf("Temp HIGH alert: > %.0f C\n", TEMP_HIGH_THRESHOLD);
Serial.printf("Temp LOW alert: < %.0f C\n", TEMP_LOW_THRESHOLD);
Serial.printf("Poll interval : %lu ms\n", GPS_POLL_INTERVAL);
Serial.printf("Cloud interval : %d s\n", CLOUD_SEND_INTERVAL);
Serial.println("──────────────────────────────────────");
Serial.println("Monitoring started.\n");
lastPollTime = millis();
lastCloudPush = millis();
}
// ============================================================================
// loop()
// ============================================================================
void loop() {
GeoLinker.update();
if (millis() - lastPollTime < GPS_POLL_INTERVAL) return;
lastPollTime = millis();
// STEP 1: Read temperature
float temp = readTemperature();
if (temp == TEMP_ERROR_VALUE) {
Serial.println("[TEMP] Read failed — check wiring on GPIO 12");
} else {
Serial.printf("[TEMP] %.2f °C\n", temp);
}
// STEP 2: Get GPS fix
GPSData gps = {};
bool hasLoc = getValidLocation(&gps);
if(hasLoc)
{
Serial.printf("Speed = %.2f km/h\n", gps.speed);
}
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(temp);
gpsLossAlertSent = true;
}
}
// STEP 3: Temperature alerts
checkTemperatureAlerts(temp, &gps, hasLoc);
// STEP 4: Cloud push — only when GPS fix available
if (millis() - lastCloudPush >= (uint32_t)CLOUD_SEND_INTERVAL * 1000UL) {
if (hasLoc) {
lastCloudPush = millis();
cloudPush(&gps, temp);
} else {
Serial.println("[CLOUD] Skipping — no GPS fix.");
}
}
Serial.printf("[LOOP] Done. Temp:%.2f°C Next in %lu ms\n\n",
temp, GPS_POLL_INTERVAL);
}