/*
TransitGuardian_SD_LoRa.ino
Heltec V3 – Safe transit monitor for Gem Bot machines
- Real sensors from your kit
- MicroSD logging (main log + daily + per-crash)
- LoRa live packets
- WiFi JSON endpoint at /data
*/
#include
#include
#include
#include
#include
#include // Heltec WiFi LoRa 32 V3 library
// ---------- USER CONFIG ----------
const char* WIFI_SSID = "YOUR_WIFI_SSID";
const char* WIFI_PASSWORD = "YOUR_WIFI_PASSWORD";
// LoRa frequency (US)
const long LORA_FREQ = 915E6;
// SD card
const int SD_CS_PIN = 10;
// ---------- SENSOR PINS ----------
const int PIN_LDR = 1; // ADC
const int PIN_TEMP = 2; // ADC
const int PIN_SOUND = 3; // ADC
const int PIN_SHOCK = 4; // digital
const int PIN_TILT = 5; // digital
const int PIN_REED = 6; // digital
// ---------- TIMING ----------
const unsigned long SENSOR_UPDATE_MS = 1000;
const unsigned long LORA_UPDATE_MS = 5000;
const unsigned long SD_FLUSH_MS = 10000;
// ---------- SOUND CRASH THRESHOLDS ----------
struct CrashThresholds {
int ampConservative;
int ampBalanced;
int ampStrict;
int jumpConservative;
int jumpBalanced;
int jumpStrict;
};
CrashThresholds crashCfg = {
600, 900, 1200, // amplitude thresholds
300, 500, 800 // jump thresholds
};
// ---------- GLOBAL STATE ----------
WebServer server(80);
unsigned long lastSensorUpdate = 0;
unsigned long lastLoRaUpdate = 0;
unsigned long lastSDFlush = 0;
int ldrRaw = 0;
int tempRaw = 0;
int soundRaw = 0;
int soundPeak = 0;
int soundCrashLevel = 0; // 0–3
bool shockState = false;
bool tiltState = false;
bool reedState = false;
int batteryPct = 100; // placeholder, can be wired to ADC later
int lastSoundRaw = 0;
// ---------- SD FILE HANDLES ----------
File mainLog; // /transit_log.csv
File crashLog; // /crash_events.txt
// ---------- UTILS ----------
String millisToTimeString(unsigned long ms) {
unsigned long seconds = ms / 1000;
unsigned long s = seconds % 60;
unsigned long m = (seconds / 60) % 60;
unsigned long h = (seconds / 3600);
char buf[32];
snprintf(buf, sizeof(buf), "%02lu:%02lu:%02lu", h, m, s);
return String(buf);
}
int getDayIndexFromMillis(unsigned long ms) {
return ms / (24UL * 60UL * 60UL * 1000UL);
}
// ---------- WIFI ----------
void setupWiFi() {
Serial.print("Connecting to WiFi: ");
Serial.println(WIFI_SSID);
WiFi.mode(WIFI_STA);
WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
int retries = 0;
while (WiFi.status() != WL_CONNECTED && retries < 40) {
delay(500);
Serial.print(".");
retries++;
}
Serial.println();
if (WiFi.status() == WL_CONNECTED) {
Serial.print("WiFi connected. IP address: ");
Serial.println(WiFi.localIP());
} else {
Serial.println("WiFi connection failed. Continuing without WiFi.");
}
}
// ---------- HTTP HANDLERS ----------
void handleRoot() {
server.send(200, "text/plain", "TransitGuardian online. Use /data for JSON feed.");
}
void handleData() {
StaticJsonDocument<512> doc;
doc["ldr_raw"] = ldrRaw;
doc["temp_raw"] = tempRaw;
doc["sound_amp"] = soundRaw;
doc["sound_peak"] = soundPeak;
doc["sound_crash_level"]= soundCrashLevel;
doc["shock"] = shockState;
doc["tilt"] = tiltState;
doc["reed"] = reedState;
doc["battery_pct"] = batteryPct;
doc["timestamp_ms"] = millis();
// Simple status classification
const char* status = "SAFE";
if (soundCrashLevel >= 3 || shockState || (tiltState && reedState)) {
status = "COMPROMISED";
} else if (soundCrashLevel >= 2 || tiltState || reedState) {
status = "WATCH";
}
doc["status"] = status;
String json;
serializeJson(doc, json);
server.send(200, "application/json", json);
}
void setupServer() {
server.on("/", handleRoot);
server.on("/data", handleData);
server.begin();
Serial.println("HTTP server started.");
}
// ---------- SD ----------
bool initSD() {
if (!SD.begin(SD_CS_PIN)) {
Serial.println("SD init failed.");
return false;
}
Serial.println("SD init OK.");
// Main log
if (!SD.exists("/transit_log.csv")) {
mainLog = SD.open("/transit_log.csv", FILE_WRITE);
if (mainLog) {
mainLog.println("timestamp_ms,time_str,shock,tilt,reed,ldr,temp,sound_amp,sound_peak,sound_crash_level,battery_pct");
mainLog.close();
}
}
// Crash log
if (!SD.exists("/crash_events.txt")) {
crashLog = SD.open("/crash_events.txt", FILE_WRITE);
if (crashLog) {
crashLog.println("=== Crash Events Log ===");
crashLog.close();
}
}
return true;
}
void appendMainLog() {
mainLog = SD.open("/transit_log.csv", FILE_APPEND);
if (!mainLog) return;
unsigned long t = millis();
String line = String(t) + "," +
millisToTimeString(t) + "," +
String(shockState) + "," +
String(tiltState) + "," +
String(reedState) + "," +
String(ldrRaw) + "," +
String(tempRaw) + "," +
String(soundRaw) + "," +
String(soundPeak) + "," +
String(soundCrashLevel) + "," +
String(batteryPct);
mainLog.println(line);
mainLog.close();
}
void appendDailyLog() {
int dayIndex = getDayIndexFromMillis(millis());
char fname[32];
snprintf(fname, sizeof(fname), "/day_%03d.csv", dayIndex);
bool newFile = !SD.exists(fname);
File f = SD.open(fname, FILE_APPEND);
if (!f) return;
if (newFile) {
f.println("timestamp_ms,time_str,shock,tilt,reed,ldr,temp,sound_amp,sound_peak,sound_crash_level,battery_pct");
}
unsigned long t = millis();
String line = String(t) + "," +
millisToTimeString(t) + "," +
String(shockState) + "," +
String(tiltState) + "," +
String(reedState) + "," +
String(ldrRaw) + "," +
String(tempRaw) + "," +
String(soundRaw) + "," +
String(soundPeak) + "," +
String(soundCrashLevel) + "," +
String(batteryPct);
f.println(line);
f.close();
}
void logCrashEvent(int level) {
// Append to crash_events.txt
crashLog = SD.open("/crash_events.txt", FILE_APPEND);
if (crashLog) {
unsigned long t = millis();
crashLog.println("---- CRASH EVENT ----");
crashLog.print("Time: ");
crashLog.print(t);
crashLog.print(" ms (");
crashLog.print(millisToTimeString(t));
crashLog.println(")");
crashLog.print("Level: ");
crashLog.println(level);
crashLog.print("Sound peak: ");
crashLog.println(soundPeak);
crashLog.print("Shock: ");
crashLog.println(shockState);
crashLog.print("Tilt: ");
crashLog.println(tiltState);
crashLog.print("Reed: ");
crashLog.println(reedState);
crashLog.println("---------------------");
crashLog.close();
}
// Per-event file
char fname[32];
snprintf(fname, sizeof(fname), "/crash_%lu.txt", millis());
File cf = SD.open(fname, FILE_WRITE);
if (cf) {
unsigned long t = millis();
cf.println("CRASH EVENT");
cf.print("Time: ");
cf.print(t);
cf.print(" ms (");
cf.print(millisToTimeString(t));
cf.println(")");
cf.print("Level: ");
cf.println(level);
cf.print("Sound peak: ");
cf.println(soundPeak);
cf.print("Shock: ");
cf.println(shockState);
cf.print("Tilt: ");
cf.println(tiltState);
cf.print("Reed: ");
cf.println(reedState);
cf.close();
}
}
// ---------- LORA ----------
void setupLoRa() {
Heltec.begin(true, true, true, true, LORA_FREQ);
Serial.println("LoRa init done.");
}
void sendLoRaPacket() {
// Simple compact CSV-like payload
String payload = String("TG,") +
String(millis()) + "," +
String(shockState) + "," +
String(tiltState) + "," +
String(reedState) + "," +
String(ldrRaw) + "," +
String(tempRaw) + "," +
String(soundRaw) + "," +
String(soundPeak) + "," +
String(soundCrashLevel) + "," +
String(batteryPct);
Heltec.LoRa.beginPacket();
Heltec.LoRa.print(payload);
Heltec.LoRa.endPacket();
Serial.print("LoRa sent: ");
Serial.println(payload);
}
// ---------- SENSORS ----------
void readSensors() {
ldrRaw = analogRead(PIN_LDR);
tempRaw = analogRead(PIN_TEMP);
soundRaw = analogRead(PIN_SOUND);
shockState = digitalRead(PIN_SHOCK);
tiltState = digitalRead(PIN_TILT);
reedState = digitalRead(PIN_REED);
if (soundRaw > soundPeak) soundPeak = soundRaw;
int delta = abs(soundRaw - lastSoundRaw);
lastSoundRaw = soundRaw;
int level = 0;
if (soundRaw > crashCfg.ampConservative || delta > crashCfg.jumpConservative) {
level = 1;
}
if (soundRaw > crashCfg.ampBalanced || delta > crashCfg.jumpBalanced) {
level = 2;
}
if (soundRaw > crashCfg.ampStrict || delta > crashCfg.jumpStrict) {
level = 3;
}
if (level > soundCrashLevel) {
soundCrashLevel = level;
if (level >= 1) {
logCrashEvent(level);
}
}
}
// ---------- SETUP / LOOP ----------
void setup() {
Serial.begin(115200);
delay(1000);
Serial.println("\nTransitGuardian SD + LoRa booting...");
pinMode(PIN_SHOCK, INPUT);
pinMode(PIN_TILT, INPUT);
pinMode(PIN_REED, INPUT);
// ADC pins are input by default
setupWiFi();
setupServer();
initSD();
setupLoRa();
lastSensorUpdate = millis();
lastLoRaUpdate = millis();
lastSDFlush = millis();
}
void loop() {
server.handleClient();
unsigned long now = millis();
if (now - lastSensorUpdate >= SENSOR_UPDATE_MS) {
lastSensorUpdate = now;
readSensors();
appendMainLog();
appendDailyLog();
}
if (now - lastLoRaUpdate >= LORA_UPDATE_MS) {
lastLoRaUpdate = now;
sendLoRaPacket();
}
if (now - lastSDFlush >= SD_FLUSH_MS) {
lastSDFlush = now;
// SD library flushes on close; nothing extra needed here,
// but this is a hook if you keep files open later.
}
}