Acquario
demo-kit/ è quello che simula il dispositivo per la demo nella pagina di inizio. Il dispositivo stesso non ne ha bisogno.
demo-kit/ è quello che simula il dispositivo per la demo nella pagina di inizio. Il dispositivo stesso non ne ha bisogno.
/*
Aquarium - a light that follows the day, a feeder and a thermometer, with a screen of their own in the
Connectivitizer app
An ESP32 dims the lamp of a fish tank through the day (moonlight, a slow dawn, the day, a slow dusk),
turns a feeder at set times or when asked, and reads the temperature of the water. It serves that as a
small web API, and one HTML page (page.h, made from ../../ui/aquarium.html) that the Connectivitizer app
shows full screen. The web server knows nothing about Connectivitizer; the library makes it reachable
from anywhere, encrypted end to end with the shared key.
Wiring (ESP32 DevKit, 3.3 V logic; change the pins below for another board):
DS18B20 temperature sensor, VDD -> 3V3 GND -> GND DQ -> GPIO4, and 4.7 kOhm from DQ to 3V3
the waterproof kind
LED lamp GPIO25 -> the gate of a logic-level N-channel MOSFET (with 100 Ohm in series and
10 kOhm from the gate to GND) that switches the lamp's minus wire, or -> the PWM
dimming input of the lamp's driver. The lamp has its own supply.
Feeder servo (SG90 or similar) signal -> GPIO18 plus -> its own 5 V supply minus -> that supply and GND
Never power the servo or the lamp from the ESP32's 3V3 pin.
Each of the three can be simulated (SIMULATE_... below), so that the sketch runs on a board with nothing
connected to it.
What you need (https://connectivitizer.com):
1. a device key - Credentials > Create credential > Device key -> DEVICE_KEY
2. a shared key - Credentials > Generate a shared key -> SHARED_KEY, and the same key in the app
Copy secrets.example.h to secrets.h and fill it in. The Connectivitizer library is the only one to install;
Preferences comes with the ESP32 board package, and the sketch talks to the DS18B20 itself.
*/
// ---------- simulated hardware ----------
// Set one to true and the sketch invents that part instead of using its pin. /state then says
// "simulated": true and the page shows "Simulated hardware". All three false is the real tank.
const bool SIMULATE_TEMPERATURE = false; // true: no DS18B20; a temperature that drifts around 25 degrees
const bool SIMULATE_LIGHT = false; // true: no PWM on PIN_LIGHT; the brightness is only computed
const bool SIMULATE_FEEDER = false; // true: no servo pulses on PIN_FEEDER; a feeding only takes its time
// ---------- pins ----------
const int PIN_TEMPERATURE = 4; // DS18B20 data, with 4.7 kOhm to 3V3
const int PIN_LIGHT = 25; // PWM for the lamp
const int PIN_FEEDER = 18; // servo signal
const bool LIGHT_ACTIVE_HIGH = true; // false when the lamp is brightest with the pin LOW
// ---------- the clock ----------
// The light and the feeder follow the time of day, which the ESP32 gets from the internet (NTP) once
// Wi-Fi is up. A POSIX time zone; this one is Central European Time with summer time.
const char *TIME_ZONE = "CET-1CEST,M3.5.0,M10.5.0/3";
const char *TIME_SERVER_1 = "pool.ntp.org";
const char *TIME_SERVER_2 = "time.nist.gov";
// ---------- light ----------
const uint32_t LIGHT_PWM_HZ = 5000;
const uint8_t LIGHT_PWM_BITS = 12;
const uint8_t LIGHT_CHANNEL = 0; // LEDC channels 0 and 2 use different timers, so the two
const float LIGHT_GAMMA = 2.2f; // frequencies do not disturb each other
const float LIGHT_PERCENT_PER_SECOND = 20.0f; // the lamp never jumps: it moves to a new brightness at this pace
// ---------- feeder ----------
const uint32_t SERVO_HZ = 50;
const uint8_t SERVO_BITS = 16;
const uint8_t SERVO_CHANNEL = 2;
const uint32_t FEEDER_REST_MICROS = 600; // pulse width with the drum's opening up
const uint32_t FEEDER_DUMP_MICROS = 2300; // pulse width with the opening down
const uint32_t FEED_HOLD_MS = 1200; // the drum stays turned over this long
const uint32_t FEED_TURN_MS = 2400; // one portion, from start to back at rest
const int MAX_FEED_TIMES = 4;
// ---------- history: one sample every 15 minutes, 24 hours ----------
const uint32_t HISTORY_INTERVAL_SECONDS = 900;
const int HISTORY_STORED = 95; // /history adds the current reading as the 96th point
const int16_t NO_SAMPLE = INT16_MIN;
WebServer server(80);
Preferences settings;
// The day of the tank, in minutes since midnight and percent. Kept in flash.
struct Schedule {
uint16_t sunrise = 480; // the light starts to rise
uint16_t sunset = 1200; // the light starts to fall
uint16_t ramp = 45; // how long a dawn and a dusk take
uint8_t dayLevel = 85;
uint8_t moonLevel = 4;
};
Schedule schedule;
uint16_t feedTimes[MAX_FEED_TIMES] = { 450, 1110 };
int feedTimeCount = 2;
bool manualMode = false; // not kept: after a restart the tank follows its schedule again
float manualLevel = 60.0f;
float lightPercent = 0.0f; // what the lamp shows right now
float temperatureC = NAN; // NAN until the sensor has answered, and again when it stops answering
int temperatureFailures = 0;
bool conversionStarted = false;
bool feeding = false;
uint64_t feedStartedMs = 0;
bool fedSinceBoot = false;
uint64_t lastFedMs = 0;
int lastCheckedMinute = -1;
int16_t historyTemperature[HISTORY_STORED]; // hundredths of a degree
uint8_t historyLight[HISTORY_STORED];
int historyCount = 0;
int historyNext = 0; // where the next sample goes
// Milliseconds since the start, 64 bit: millis() starts again at zero after 49 days.
uint64_t nowMs() {
return (uint64_t)(esp_timer_get_time() / 1000);
}
// Seconds since midnight, local time. False until the clock has been set from the internet.
bool secondOfDay(uint32_t &second) {
time_t now = time(nullptr);
if (now < 1600000000) return false; // still counting from 1970
struct tm local;
localtime_r(&now, &local);
second = (uint32_t)local.tm_hour * 3600 + (uint32_t)local.tm_min * 60 + (uint32_t)local.tm_sec;
return true;
}
// ---------- the DS18B20, on its one wire ----------
// The pin is open drain: LOW pulls the wire down, HIGH lets the resistor pull it up, and it can be read
// either way. The short parts of each bit run without interrupts, because their timing is what the bit is.
bool wireReset() {
digitalWrite(PIN_TEMPERATURE, LOW);
delayMicroseconds(480);
noInterrupts();
digitalWrite(PIN_TEMPERATURE, HIGH);
delayMicroseconds(70);
bool present = digitalRead(PIN_TEMPERATURE) == LOW; // a sensor answers by pulling the wire down
interrupts();
delayMicroseconds(410);
return present;
}
void wireWriteBit(bool bit) {
noInterrupts();
digitalWrite(PIN_TEMPERATURE, LOW);
delayMicroseconds(bit ? 6 : 60);
digitalWrite(PIN_TEMPERATURE, HIGH);
delayMicroseconds(bit ? 64 : 10);
interrupts();
}
bool wireReadBit() {
noInterrupts();
digitalWrite(PIN_TEMPERATURE, LOW);
delayMicroseconds(3);
digitalWrite(PIN_TEMPERATURE, HIGH);
delayMicroseconds(10);
bool bit = digitalRead(PIN_TEMPERATURE) == HIGH;
interrupts();
delayMicroseconds(53);
return bit;
}
void wireWrite(uint8_t value) {
for (int bit = 0; bit < 8; bit++) wireWriteBit((value >> bit) & 1);
}
uint8_t wireRead() {
uint8_t value = 0;
for (int bit = 0; bit < 8; bit++) {
if (wireReadBit()) value |= (uint8_t)(1 << bit);
}
return value;
}
uint8_t wireCrc(const uint8_t *data, int length) {
uint8_t crc = 0;
for (int i = 0; i < length; i++) {
uint8_t in = data[i];
for (int bit = 0; bit < 8; bit++) {
bool mix = (crc ^ in) & 1;
crc >>= 1;
if (mix) crc ^= 0x8C;
in >>= 1;
}
}
return crc;
}
// Reads what the conversion that the last call started has measured. False when no sensor answered or
// the answer was damaged.
bool readSensor(float &celsius) {
if (!wireReset()) return false;
wireWrite(0xCC); // the only sensor on the wire
wireWrite(0xBE); // read its memory
uint8_t data[9];
bool allZero = true;
for (int i = 0; i < 9; i++) {
data[i] = wireRead();
if (data[i] != 0) allZero = false;
}
if (allZero || wireCrc(data, 8) != data[8]) return false; // a wire held down reads as zeros, and their checksum fits
int16_t raw = (int16_t)((data[1] << 8) | data[0]);
if (raw == 0x0550) return false; // 85 degrees: what the sensor holds before its first measurement
celsius = (float)raw / 16.0f;
return true;
}
// Called every two seconds: takes the last measurement and starts the next. A measurement takes 750 ms.
void readTemperature() {
if (SIMULATE_TEMPERATURE) {
float seconds = (float)(nowMs() / 1000);
temperatureC = 25.0f + 0.5f * sinf(seconds / 600.0f) + 0.08f * sinf(seconds / 37.0f);
return;
}
float celsius = 0;
if (conversionStarted && readSensor(celsius)) {
temperatureC = celsius;
temperatureFailures = 0;
} else if (conversionStarted && ++temperatureFailures >= 5) {
temperatureC = NAN; // ten seconds without an answer: an old temperature is worse than none
}
conversionStarted = wireReset();
if (conversionStarted) {
wireWrite(0xCC);
wireWrite(0x44); // measure
}
}
// ---------- light ----------
void pwmStart(int pin, uint8_t channel, uint32_t hertz, uint8_t bits) {
ledcAttachChannel(pin, hertz, bits, channel);
ledcSetup(channel, hertz, bits);
ledcAttachPin(pin, channel);
}
void pwmWrite(int pin, uint8_t channel, uint32_t duty) {
(void)channel;
ledcWrite(pin, duty);
(void)pin;
ledcWrite(channel, duty);
}
// Puts a brightness in percent on the lamp. The eye sees brightness in ratios, so the duty cycle follows
// a gamma curve: 50 % looks half as bright as 100 %.
void showLight(float percent) {
if (SIMULATE_LIGHT) return;
const uint32_t full = (1u << LIGHT_PWM_BITS) - 1;
uint32_t duty = (uint32_t)lroundf(powf(constrain(percent, 0.0f, 100.0f) / 100.0f, LIGHT_GAMMA) * (float)full);
if (percent > 0.0f && duty == 0) duty = 1; // moonlight is dim, not off
pwmWrite(PIN_LIGHT, LIGHT_CHANNEL, LIGHT_ACTIVE_HIGH ? duty : full - duty);
}
// The brightness the schedule asks for at a second of the day: moonlight, a ramp up from sunrise, the day,
// a ramp down from sunset. `phase` gets the name of that part of the day.
float scheduledLevel(uint32_t second, const char *&phase) {
float minute = (float)second / 60.0f;
float moon = (float)schedule.moonLevel;
float day = (float)schedule.dayLevel;
if (minute < (float)schedule.sunrise || minute >= (float)(schedule.sunset + schedule.ramp)) {
phase = "moon";
return moon;
}
if (minute < (float)(schedule.sunrise + schedule.ramp)) {
phase = "dawn";
return moon + (day - moon) * (minute - (float)schedule.sunrise) / (float)schedule.ramp;
}
if (minute < (float)schedule.sunset) {
phase = "day";
return day;
}
phase = "dusk";
return day - (day - moon) * (minute - (float)schedule.sunset) / (float)schedule.ramp;
}
// What the lamp should show now. Without the time of day the schedule cannot be followed: the lamp
// stays at moonlight until the clock is set, and `phase` is null.
float wantedLevel(const char *&phase) {
phase = nullptr;
uint32_t second = 0;
float level = (float)schedule.moonLevel;
if (secondOfDay(second)) level = scheduledLevel(second, phase);
return manualMode ? manualLevel : level;
}
void watchLight() {
static uint64_t lastStep = 0;
uint64_t now = nowMs();
if (now - lastStep < 20) return;
float seconds = (float)(now - lastStep) / 1000.0f;
lastStep = now;
const char *phase = nullptr;
float wanted = wantedLevel(phase);
float step = LIGHT_PERCENT_PER_SECOND * seconds;
if (fabsf(wanted - lightPercent) <= step) lightPercent = wanted;
else lightPercent += wanted > lightPercent ? step : -step;
showLight(lightPercent);
}
// ---------- feeder ----------
void servoPulse(uint32_t pulseMicros) {
if (SIMULATE_FEEDER) return;
// One period at 50 Hz is 20000 microseconds; zero stops the pulses and the servo stops holding.
pwmWrite(PIN_FEEDER, SERVO_CHANNEL, (uint32_t)((uint64_t)pulseMicros * ((1u << SERVO_BITS) - 1) / 20000));
}
// Starts one portion. False while the feeder is still turning.
bool startFeeding() {
if (feeding) return false;
feeding = true;
feedStartedMs = nowMs();
fedSinceBoot = true;
lastFedMs = feedStartedMs;
servoPulse(FEEDER_DUMP_MICROS);
return true;
}
void watchFeeder() {
if (feeding) {
uint64_t since = nowMs() - feedStartedMs;
if (since >= FEED_TURN_MS) {
feeding = false;
servoPulse(0);
} else if (since >= FEED_HOLD_MS) {
servoPulse(FEEDER_REST_MICROS);
}
}
// The feeding times: once in the minute they name.
uint32_t second = 0;
if (!secondOfDay(second)) return;
int minute = (int)(second / 60);
if (minute == lastCheckedMinute) return;
bool first = lastCheckedMinute < 0;
lastCheckedMinute = minute;
if (first) return; // a restart inside a feeding minute does not feed a second time
for (int i = 0; i < feedTimeCount; i++) {
if (feedTimes[i] == minute) startFeeding();
}
}
// ---------- history ----------
void storeSample() {
historyTemperature[historyNext] = isnan(temperatureC) ? NO_SAMPLE : (int16_t)lroundf(temperatureC * 100.0f);
historyLight[historyNext] = (uint8_t)lroundf(lightPercent);
historyNext = (historyNext + 1) % HISTORY_STORED;
if (historyCount < HISTORY_STORED) historyCount++;
}
// ---------- settings ----------
// The day keeps its order: a dawn, at least an hour of day, a dusk that ends before midnight.
void tidySchedule() {
schedule.ramp = constrain(schedule.ramp, 5, 120);
schedule.sunrise = constrain((int)schedule.sunrise, 0, 1425 - 2 * (int)schedule.ramp - 60);
schedule.sunset = constrain((int)schedule.sunset, (int)schedule.sunrise + (int)schedule.ramp + 60, 1425 - (int)schedule.ramp);
schedule.dayLevel = constrain(schedule.dayLevel, 10, 100);
schedule.moonLevel = constrain(schedule.moonLevel, 0, 10);
}
void sortFeedTimes() {
for (int i = 1; i < feedTimeCount; i++) {
for (int j = i; j > 0 && feedTimes[j - 1] > feedTimes[j]; j--) {
uint16_t swap = feedTimes[j];
feedTimes[j] = feedTimes[j - 1];
feedTimes[j - 1] = swap;
}
}
}
void loadSettings() {
settings.begin("aquarium", false);
schedule.sunrise = settings.getUShort("sunrise", schedule.sunrise);
schedule.sunset = settings.getUShort("sunset", schedule.sunset);
schedule.ramp = settings.getUShort("ramp", schedule.ramp);
schedule.dayLevel = settings.getUChar("day", schedule.dayLevel);
schedule.moonLevel = settings.getUChar("moon", schedule.moonLevel);
tidySchedule();
int stored = settings.getUChar("feeds", 255);
if (stored <= MAX_FEED_TIMES) {
uint16_t times[MAX_FEED_TIMES] = { 0 };
settings.getBytes("feedTimes", times, sizeof(times));
feedTimeCount = 0;
for (int i = 0; i < stored; i++) {
if (times[i] < 1440) feedTimes[feedTimeCount++] = times[i];
}
sortFeedTimes();
}
}
void saveSchedule() {
settings.putUShort("sunrise", schedule.sunrise);
settings.putUShort("sunset", schedule.sunset);
settings.putUShort("ramp", schedule.ramp);
settings.putUChar("day", schedule.dayLevel);
settings.putUChar("moon", schedule.moonLevel);
}
void saveFeedTimes() {
settings.putUChar("feeds", (uint8_t)feedTimeCount);
settings.putBytes("feedTimes", feedTimes, sizeof(feedTimes));
}
// ---------- JSON ----------
void addNumber(String &json, float value, int decimals) {
if (isnan(value)) json += "null";
else json += String(value, (unsigned int)decimals);
}
String stateJson() {
uint64_t now = nowMs();
const char *phase = nullptr;
wantedLevel(phase);
uint32_t second = 0;
bool hasClock = secondOfDay(second);
String json;
json.reserve(420);
json += "{\"temperature\":";
addNumber(json, temperatureC, 2);
json += ",\"light\":";
addNumber(json, lightPercent, 1);
json += ",\"phase\":";
if (phase != nullptr) {
json += "\"";
json += phase;
json += "\"";
} else {
json += "null"; // the time of day is not known yet
}
json += ",\"mode\":";
json += manualMode ? "\"manual\"" : "\"auto\"";
json += ",\"minuteOfDay\":";
if (hasClock) json += second / 60;
else json += "null";
json += ",\"schedule\":{\"sunrise\":";
json += schedule.sunrise;
json += ",\"sunset\":";
json += schedule.sunset;
json += ",\"ramp\":";
json += schedule.ramp;
json += ",\"dayLevel\":";
json += schedule.dayLevel;
json += ",\"moonLevel\":";
json += schedule.moonLevel;
json += "},\"feeding\":";
json += feeding ? "true" : "false";
json += ",\"feedTimes\":[";
for (int i = 0; i < feedTimeCount; i++) {
if (i > 0) json += ",";
json += feedTimes[i];
}
json += "],\"nextFeedMinutes\":";
if (hasClock && feedTimeCount > 0) {
uint32_t next = 86400;
for (int i = 0; i < feedTimeCount; i++) {
uint32_t wait = ((uint32_t)feedTimes[i] * 60 + 86400 - second) % 86400;
if (wait < next) next = wait;
}
json += (next + 59) / 60;
} else {
json += "null";
}
json += ",\"lastFedSecondsAgo\":";
if (fedSinceBoot) json += (uint32_t)((now - lastFedMs) / 1000);
else json += "null"; // when the tank was last fed is not kept over a restart
json += ",\"simulated\":";
json += (SIMULATE_TEMPERATURE || SIMULATE_LIGHT || SIMULATE_FEEDER) ? "true" : "false";
json += ",\"rssi\":";
json += WiFi.RSSI();
json += ",\"uptimeSeconds\":";
json += (uint32_t)(now / 1000);
json += "}";
return json;
}
String historyJson() {
String json;
json.reserve(1300);
json += "{\"intervalSeconds\":";
json += HISTORY_INTERVAL_SECONDS;
int first = historyCount < HISTORY_STORED ? 0 : historyNext; // the oldest sample
json += ",\"temperature\":[";
for (int i = 0; i < historyCount; i++) {
int16_t sample = historyTemperature[(first + i) % HISTORY_STORED];
if (sample == NO_SAMPLE) json += "null";
else json += String((float)sample / 100.0f, 2U);
json += ",";
}
addNumber(json, temperatureC, 2); // the last point is the reading of this moment
json += "],\"light\":[";
for (int i = 0; i < historyCount; i++) {
json += historyLight[(first + i) % HISTORY_STORED];
json += ",";
}
json += (int)lroundf(lightPercent);
json += "]}";
return json;
}
// Just enough JSON reading for the bodies of /light and /schedule: flat objects with numbers, one text
// and one list of numbers. Returns where the value of a key starts, or -1.
int jsonValueAt(const String &body, const char *key) {
String quoted = String("\"") + key + "\"";
int at = body.indexOf(quoted);
if (at < 0) return -1;
at = body.indexOf(':', at + quoted.length());
if (at < 0) return -1;
at++;
while (at < (int)body.length() && isspace((unsigned char)body[at])) at++;
return at < (int)body.length() ? at : -1;
}
bool jsonNumber(const String &body, const char *key, float &value) {
int at = jsonValueAt(body, key);
if (at < 0) return false;
char first = body[at];
if (!isdigit((unsigned char)first) && first != '-' && first != '.') return false;
value = body.substring(at).toFloat();
return true;
}
bool jsonTextIs(const String &body, const char *key, const char *text) {
int at = jsonValueAt(body, key);
return at >= 0 && body.startsWith(String("\"") + text + "\"", at);
}
// Reads "key": [450, 1110] into `values`. False when the key is not there or is not a list.
bool jsonMinutes(const String &body, const char *key, uint16_t *values, int capacity, int &count) {
int at = jsonValueAt(body, key);
if (at < 0 || body[at] != '[') return false;
int end = body.indexOf(']', at);
if (end < 0) return false;
count = 0;
at++;
while (at < end) {
while (at < end && !isdigit((unsigned char)body[at])) at++;
if (at >= end) break;
long value = body.substring(at, end).toInt();
if (value >= 0 && value < 1440 && count < capacity) values[count++] = (uint16_t)value;
while (at < end && body[at] != ',') at++;
}
return true;
}
// ---------- the web server ----------
void sendJson(int status, const String &json) {
server.sendHeader("Cache-Control", "no-store");
server.send(status, "application/json", json);
}
void sendError(int status, const char *message) {
String json = "{\"error\":\"";
json += message; // only fixed texts without quotes are passed here
json += "\"}";
sendJson(status, json);
}
void handleLight() {
String body = server.arg("plain");
float level = 0;
bool hasLevel = jsonNumber(body, "level", level);
bool wantsAuto = jsonTextIs(body, "mode", "auto");
bool wantsManual = jsonTextIs(body, "mode", "manual");
if (!wantsAuto && !wantsManual && !hasLevel) {
sendError(400, "Send { 'mode': 'auto' } or { 'mode': 'manual', 'level': percent }.");
return;
}
if (wantsAuto) {
manualMode = false;
} else {
if (!manualMode && !hasLevel) manualLevel = roundf(lightPercent); // stays as bright as it is
manualMode = true;
if (hasLevel) manualLevel = roundf(constrain(level, 0.0f, 100.0f));
}
sendJson(200, stateJson());
}
void handleFeed() {
if (!startFeeding()) {
sendError(409, "The feeder is still turning.");
return;
}
sendJson(200, stateJson());
}
void handleSchedule() {
String body = server.arg("plain");
float sunrise = 0, sunset = 0, ramp = 0, dayLevel = 0, moonLevel = 0;
uint16_t times[MAX_FEED_TIMES];
int timeCount = 0;
bool hasSunrise = jsonNumber(body, "sunrise", sunrise);
bool hasSunset = jsonNumber(body, "sunset", sunset);
bool hasRamp = jsonNumber(body, "ramp", ramp);
bool hasDay = jsonNumber(body, "dayLevel", dayLevel);
bool hasMoon = jsonNumber(body, "moonLevel", moonLevel);
bool hasTimes = jsonMinutes(body, "feedTimes", times, MAX_FEED_TIMES, timeCount);
if (!hasSunrise && !hasSunset && !hasRamp && !hasDay && !hasMoon && !hasTimes) {
sendError(400, "Send sunrise, sunset, ramp, dayLevel, moonLevel or feedTimes.");
return;
}
if (hasSunrise || hasSunset || hasRamp || hasDay || hasMoon) {
if (hasRamp) schedule.ramp = (uint16_t)constrain(lroundf(ramp), 5L, 120L);
if (hasSunrise) schedule.sunrise = (uint16_t)constrain(lroundf(sunrise), 0L, 1439L);
if (hasSunset) schedule.sunset = (uint16_t)constrain(lroundf(sunset), 0L, 1439L);
if (hasDay) schedule.dayLevel = (uint8_t)constrain(lroundf(dayLevel), 10L, 100L);
if (hasMoon) schedule.moonLevel = (uint8_t)constrain(lroundf(moonLevel), 0L, 10L);
tidySchedule();
saveSchedule();
}
if (hasTimes) {
feedTimeCount = timeCount;
for (int i = 0; i < timeCount; i++) feedTimes[i] = times[i];
sortFeedTimes();
saveFeedTimes();
}
sendJson(200, stateJson());
}
void setup() {
Serial.begin(115200);
// The lamp is dark and the feeder is still before anything else happens.
if (!SIMULATE_LIGHT) {
pwmStart(PIN_LIGHT, LIGHT_CHANNEL, LIGHT_PWM_HZ, LIGHT_PWM_BITS);
showLight(0);
}
if (!SIMULATE_FEEDER) {
pwmStart(PIN_FEEDER, SERVO_CHANNEL, SERVO_HZ, SERVO_BITS);
servoPulse(0);
}
if (!SIMULATE_TEMPERATURE) {
pinMode(PIN_TEMPERATURE, OUTPUT_OPEN_DRAIN);
digitalWrite(PIN_TEMPERATURE, HIGH);
}
// What was set in the app survives a restart.
loadSettings();
WiFi.mode(WIFI_STA);
WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
configTzTime(TIME_ZONE, TIME_SERVER_1, TIME_SERVER_2); // asks once Wi-Fi is up, and again every hour
// An ordinary web server. It knows nothing about Connectivitizer.
server.on("/state", HTTP_GET, []() { sendJson(200, stateJson()); });
server.on("/history", HTTP_GET, []() { sendJson(200, historyJson()); });
server.on("/light", HTTP_POST, handleLight);
server.on("/feed", HTTP_POST, handleFeed);
server.on("/schedule", HTTP_POST, handleSchedule);
// The screen of the device: the app asks for the manifest, then for the page it names.
server.on("/.cz/ui.json", HTTP_GET, []() { server.send_P(200, "application/json", MANIFEST_JSON); });
server.on("/.cz/ui.html", HTTP_GET, []() {
server.sendHeader("Cache-Control", "no-cache");
server.send_P(200, "text/html; charset=utf-8", PAGE_HTML, PAGE_HTML_LENGTH);
});
server.onNotFound([]() { sendError(404, "Not found."); });
server.begin();
Connectivitizer.setLog(Serial);
Connectivitizer.setServer(SERVER_URL);
Connectivitizer.setSharedKey(SHARED_KEY);
Connectivitizer.expose("api", 80); // the web server above, under the name "api"
if (!Connectivitizer.begin(DEVICE_KEY, DEVICE_NAME)) {
Serial.println("Connectivitizer: check DEVICE_KEY, DEVICE_NAME and SHARED_KEY");
}
}
void loop() {
server.handleClient();
watchLight();
watchFeeder();
// Every two seconds: the temperature. Talking to the sensor takes about 10 ms.
static uint64_t lastRead = 0;
static bool readOnce = false;
if (!readOnce || nowMs() - lastRead >= 2000) {
lastRead = nowMs();
readOnce = true;
readTemperature();
}
static uint64_t lastSample = 0;
if (nowMs() - lastSample >= (uint64_t)HISTORY_INTERVAL_SECONDS * 1000) {
lastSample = nowMs();
storeSample();
}
// On the serial monitor: the address in the Wi-Fi, to open http://<address>/.cz/ui.html in a browser.
static bool hadWifi = false;
bool hasWifi = WiFi.status() == WL_CONNECTED;
if (hasWifi != hadWifi) {
hadWifi = hasWifi;
if (hasWifi) {
Serial.print("Wi-Fi connected: http://");
Serial.print(WiFi.localIP());
Serial.println("/.cz/ui.html");
} else {
Serial.println("Wi-Fi lost.");
}
}
static bool wasConnected = false;
bool isConnected = Connectivitizer.connected();
if (isConnected != wasConnected) {
wasConnected = isConnected;
Serial.println(isConnected ? "Reachable through Connectivitizer." : "Not reachable right now.");
}
if (Connectivitizer.refused()) {
static uint64_t lastComplaint = 0;
if (lastComplaint == 0 || nowMs() - lastComplaint > 10000) { // no delay(): the lamp and the feeder must not wait
lastComplaint = nowMs();
Serial.printf("The platform refused this device: %s\n", Connectivitizer.lastError());
}
}
}