#include <Arduino.h>
#include <WiFi.h>
#include <WiFiClientSecure.h>
#include <HTTPClient.h>
#include <OneWire.h>
#include <DallasTemperature.h>
#include <time.h>
#include "config.h"
#include "tls_root.h"
#include "alarm_logic.h"
constexpr int TEMP_PIN = 4, DOOR_PIN = 18, SEAL_PIN = 19;
constexpr int EQUIPMENT_PIN = 23, SENSOR_TEST_PIN = 27;
constexpr int GREEN_PIN = 25, RED_PIN = 26, BUZZER_PIN = 32;
OneWire oneWire(TEMP_PIN);
DallasTemperature sensor(&oneWire);
AlarmLogic logic;
QueueHandle_t latest;
volatile bool cloudHealthy = false;
// A separate task keeps TLS/DNS/server timeouts away from the sensor loop.
// The queue holds the latest reading only. Historical offline backfill is not implemented.
void uploadTask(void*) {
String writeApiKey = WRITE_API_KEY;
String serialCommand;
if (writeApiKey == "PASTE_WRITE_API_KEY_HERE")
Serial.println("[CLOUD] Enter KEY=your_write_key in Serial Monitor.");
else Serial.println("[CLOUD] Using configured educational demo channel. Automatic upload enabled.");
WiFi.mode(WIFI_STA);
WiFi.setAutoReconnect(true);
WiFi.begin(WIFI_SSID, WIFI_PASSWORD, 6);
configTime(0, 0, "pool.ntp.org", "time.google.com");
uint32_t lastAttempt = 0, lastReconnect = 0;
bool attempted = false;
for (;;) {
while (Serial.available()) {
char ch = (char)Serial.read();
if (ch == '\n' || ch == '\r') {
if (serialCommand.startsWith("KEY=") && serialCommand.length() == 20) {
writeApiKey = serialCommand.substring(4);
Serial.println("[CLOUD] Runtime key accepted. Not stored in source or flash.");
}
serialCommand = "";
} else if (serialCommand.length() < 64) serialCommand += ch;
else serialCommand = "";
}
const uint32_t now = millis();
if (WiFi.status() != WL_CONNECTED) {
cloudHealthy = false;
if (uint32_t(now - lastReconnect) >= 15000) {
lastReconnect = now;
WiFi.disconnect();
WiFi.begin(WIFI_SSID, WIFI_PASSWORD, 6);
}
vTaskDelay(pdMS_TO_TICKS(250));
continue;
}
if (writeApiKey == "PASTE_WRITE_API_KEY_HERE") {
if (!attempted) Serial.println("[CLOUD] Waiting for runtime KEY command. Local monitoring active.");
attempted = true;
vTaskDelay(pdMS_TO_TICKS(1000));
continue;
}
// Certificate dates require a synchronized system clock. Fail closed.
if (time(nullptr) < 1700000000) {
vTaskDelay(pdMS_TO_TICKS(250));
continue;
}
if (attempted && uint32_t(now - lastAttempt) < CLOUD_INTERVAL_MS) {
vTaskDelay(pdMS_TO_TICKS(100));
continue;
}
Snapshot s;
if (xQueuePeek(latest, &s, 0) != pdTRUE) {
vTaskDelay(pdMS_TO_TICKS(100));
continue;
}
// field1 is absent on sensor failure: never send -127 or a stale temperature.
String body = "field2=" + String(s.door) + "&field3=" + String(s.seal)
+ "&field4=" + String(s.equipment) + "&field5=" + String(s.valid)
+ "&field6=" + String(s.excursionSeconds) + "&field7=" + String(s.alarm)
+ "&field8=" + String(s.uptimeSeconds);
if (s.valid) body += "&field1=" + String(s.temperature, 2);
body += "&status=sample_uptime_s_" + String(s.uptimeSeconds);
WiFiClientSecure tls;
tls.setCACert(THINGSPEAK_ROOT_CA);
tls.setHandshakeTimeout(8);
HTTPClient http;
http.setConnectTimeout(5000);
http.setTimeout(5000);
lastAttempt = millis();
attempted = true;
if (http.begin(tls, "https://api.thingspeak.com/update")) {
http.addHeader("Content-Type", "application/x-www-form-urlencoded");
http.addHeader("THINGSPEAKAPIKEY", writeApiKey);
const int code = http.POST(body);
String response = code > 0 ? http.getString() : "";
response.trim();
cloudHealthy = code == 200 && response.toInt() > 0;
if (cloudHealthy) Serial.printf("[CLOUD] Saved entry_id=%ld sample_uptime=%lu\n", response.toInt(), (unsigned long)s.uptimeSeconds);
else Serial.printf("[CLOUD] Failed HTTP=%d (check key, channel, interval, TLS/network)\n", code);
http.end();
} else {
cloudHealthy = false;
Serial.println("[CLOUD] HTTPS initialization failed");
}
}
}
void setup() {
Serial.begin(115200);
for (int pin : {DOOR_PIN, SEAL_PIN, EQUIPMENT_PIN, SENSOR_TEST_PIN}) pinMode(pin, INPUT_PULLUP);
for (int pin : {GREEN_PIN, RED_PIN, BUZZER_PIN}) pinMode(pin, OUTPUT);
latest = xQueueCreate(1, sizeof(Snapshot));
if (!latest) { Serial.println("Queue allocation failed"); abort(); }
sensor.begin();
sensor.setResolution(12);
sensor.setWaitForConversion(false);
sensor.requestTemperatures();
if (xTaskCreate(uploadTask, "cloud", 12288, nullptr, 1, nullptr) != pdPASS) {
Serial.println("Cloud task creation failed"); abort();
}
Serial.println("Cold Chain: 1s sampling, 20s cloud; switches LEFT=normal RIGHT=fault");
}
void loop() {
static uint32_t conversionStarted = 0;
static uint32_t lastSample = 0;
static bool converting = true;
static Snapshot current;
const uint32_t now = millis();
if (!converting && uint32_t(now - lastSample) >= 1000) {
sensor.requestTemperatures();
conversionStarted = millis();
converting = true;
}
if (converting && uint32_t(now - conversionStarted) >= 800) {
const float t = sensor.getTempCByIndex(0);
const bool valid = digitalRead(SENSOR_TEST_PIN) == LOW && t != DEVICE_DISCONNECTED_C;
current = logic.update(t, valid, digitalRead(DOOR_PIN) == HIGH,
digitalRead(SEAL_PIN) == HIGH, digitalRead(EQUIPMENT_PIN) == HIGH,
now, TEMP_MIN_C, TEMP_MAX_C, TEMP_ALARM_DELAY_MS, DOOR_ALARM_DELAY_MS);
xQueueOverwrite(latest, ¤t);
lastSample = conversionStarted;
converting = false;
Serial.printf("[SAMPLE] t=%.2f valid=%d door=%d seal=%d equipment=%d excursion_s=%lu alarm=%u cloud=%d\n",
current.temperature, current.valid, current.door, current.seal, current.equipment,
(unsigned long)current.excursionSeconds, current.alarm, cloudHealthy);
}
// Blink red during pending thresholds; solid red and tone for confirmed alarms.
const bool pending = current.door || (current.valid &&
(current.temperature < TEMP_MIN_C || current.temperature > TEMP_MAX_C));
digitalWrite(GREEN_PIN, current.valid && !pending && current.alarm == 0);
digitalWrite(RED_PIN, current.alarm != 0 || (pending && (now / 250) % 2));
static bool sounding = false;
const bool shouldSound = current.alarm && (now % 2000 < 300);
if (shouldSound != sounding) {
sounding = shouldSound;
if (sounding) tone(BUZZER_PIN, 2200); else noTone(BUZZER_PIN);
}
delay(10);
}
EQUIPMENT alarm contact
TEST ONLY: temperature failure
Loading
ssd1306
ssd1306
DOOR: <=8cm closed, >=12cm open