Gewächshaus
Der Ordner demo-kit/ simuliert das Gerät für die Demo auf der Startseite. Auf dem Gerät wird er nicht benötigt.
Der Ordner demo-kit/ simuliert das Gerät für die Demo auf der Startseite. Auf dem Gerät wird er nicht benötigt.
/*
Greenhouse - a plant monitor with a pump, and a screen of its own in the Connectivitizer app
An ESP32 reads soil moisture, air temperature and humidity, light and the level of a water tank, and
switches a pump through a relay: when asked, or by itself when the soil is drier than a threshold.
It serves that as a small web API, and one HTML page (page.h, made from ../../ui/greenhouse.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):
Capacitive soil moisture sensor VCC -> 3V3 GND -> GND AOUT -> GPIO34 (ADC1; ADC2 pins do not work with Wi-Fi)
SHT31 temperature and humidity VIN -> 3V3 GND -> GND SDA -> GPIO21 SCL -> GPIO22 (I2C address 0x44)
BH1750 light sensor VCC -> 3V3 GND -> GND SDA -> GPIO21 SCL -> GPIO22 (I2C address 0x23, ADDR to GND)
HC-SR04 ultrasonic sensor, VCC -> 5V GND -> GND TRIG -> GPIO5
in the lid of the tank ECHO -> GPIO18 through a divider (1 kOhm from ECHO, 2 kOhm to GND): ECHO is 5 V
Relay module for the pump VCC -> 5V GND -> GND IN -> GPIO26
The pump has its own supply, switched by the relay's COM and NO contacts. Never power a pump from the ESP32.
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;
Wire and Preferences come with the ESP32 board package.
*/
// ---------- pins ----------
const int PIN_SOIL = 34; // analog output of the soil sensor
const int PIN_I2C_SDA = 21; // SHT31 and BH1750
const int PIN_I2C_SCL = 22;
const int PIN_TANK_TRIG = 5; // HC-SR04
const int PIN_TANK_ECHO = 18; // through a voltage divider
const int PIN_PUMP = 26; // relay input
const bool PUMP_ACTIVE_HIGH = true; // false for a relay module that switches on when its input is LOW
// ---------- calibration: measure these once with your own sensor and tank ----------
const int SOIL_RAW_DRY = 2900; // analogRead() with the sensor in dry air
const int SOIL_RAW_WET = 1250; // analogRead() with the sensor in a glass of water
const float TANK_EMPTY_CM = 24.0f; // distance from the sensor to the bottom of the tank
const float TANK_FULL_CM = 4.0f; // distance from the sensor to the water when the tank is full
// ---------- watering ----------
const uint32_t PUMP_MAX_SECONDS = 30; // safety: the pump never runs longer than this in one go, whoever asked
const uint32_t AUTO_WATER_SECONDS = 8; // how long an automatic watering runs
const uint32_t AUTO_PAUSE_MINUTES = 30; // after any watering, automatic watering waits for the water to spread
const float TANK_MIN_PERCENT = 5.0f; // below this the pump does not start, and stops: it must not run dry
const int THRESHOLD_MIN = 5;
const int THRESHOLD_MAX = 90;
// ---------- 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;
const uint8_t SHT31_ADDRESS = 0x44;
const uint8_t BH1750_ADDRESS = 0x23;
WebServer server(80);
Preferences settings;
// The latest readings. NAN until the sensor has answered once; a sensor that stops answering keeps its last value.
float soilPercent = NAN;
float temperatureC = NAN;
float humidityPercent = NAN;
float lightLux = NAN;
float tankPercent = NAN;
bool soilPlausible = false; // false when the soil sensor reads far outside its calibration (unplugged, broken cable)
bool autoMode = true;
int thresholdPercent = 35;
bool pumpOn = false;
uint64_t pumpStartedMs = 0;
uint64_t pumpRunMs = 0;
bool wateredSinceBoot = false;
uint64_t lastWateredMs = 0;
int16_t historySoil[HISTORY_STORED];
int16_t historyTemperature[HISTORY_STORED];
int16_t historyHumidity[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);
}
// ---------- sensors ----------
void readSoil() {
uint32_t sum = 0;
for (int i = 0; i < 8; i++) sum += analogRead(PIN_SOIL);
int raw = sum / 8;
soilPlausible = raw > SOIL_RAW_WET - 400 && raw < SOIL_RAW_DRY + 400;
if (!soilPlausible) return;
float percent = 100.0f * (float)(SOIL_RAW_DRY - raw) / (float)(SOIL_RAW_DRY - SOIL_RAW_WET);
percent = constrain(percent, 0.0f, 100.0f);
soilPercent = isnan(soilPercent) ? percent : soilPercent + 0.2f * (percent - soilPercent); // smoothed
}
uint8_t sht31Crc(const uint8_t *data) {
uint8_t crc = 0xFF;
for (int i = 0; i < 2; i++) {
crc ^= data[i];
for (int bit = 0; bit < 8; bit++) crc = (crc & 0x80) ? (uint8_t)((crc << 1) ^ 0x31) : (uint8_t)(crc << 1);
}
return crc;
}
void readAir() {
Wire.beginTransmission(SHT31_ADDRESS);
Wire.write(0x24); // one measurement, high repeatability, no clock stretching
Wire.write(0x00);
if (Wire.endTransmission() != 0) return;
delay(16);
if (Wire.requestFrom(SHT31_ADDRESS, (uint8_t)6) != 6) return;
uint8_t data[6];
for (int i = 0; i < 6; i++) data[i] = Wire.read();
if (sht31Crc(data) != data[2] || sht31Crc(data + 3) != data[5]) return;
temperatureC = -45.0f + 175.0f * (float)((data[0] << 8) | data[1]) / 65535.0f;
humidityPercent = 100.0f * (float)((data[3] << 8) | data[4]) / 65535.0f;
}
void startLight() {
Wire.beginTransmission(BH1750_ADDRESS);
Wire.write(0x10); // continuous measurement, 1 lx resolution
Wire.endTransmission();
}
void readLight() {
if (Wire.requestFrom(BH1750_ADDRESS, (uint8_t)2) != 2) {
startLight(); // perhaps it was plugged in later
return;
}
uint16_t raw = (uint16_t)(Wire.read() << 8);
raw |= (uint16_t)Wire.read();
lightLux = (float)raw / 1.2f;
}
void readTank() {
digitalWrite(PIN_TANK_TRIG, LOW);
delayMicroseconds(3);
digitalWrite(PIN_TANK_TRIG, HIGH);
delayMicroseconds(10);
digitalWrite(PIN_TANK_TRIG, LOW);
unsigned long echoMicros = pulseIn(PIN_TANK_ECHO, HIGH, 25000); // 0 when no echo came
if (echoMicros == 0) return;
float cm = (float)echoMicros / 58.0f;
float percent = 100.0f * (TANK_EMPTY_CM - cm) / (TANK_EMPTY_CM - TANK_FULL_CM);
percent = constrain(percent, 0.0f, 100.0f);
tankPercent = isnan(tankPercent) ? percent : tankPercent + 0.3f * (percent - tankPercent);
}
// ---------- pump ----------
void switchPump(bool on) {
digitalWrite(PIN_PUMP, on == PUMP_ACTIVE_HIGH ? HIGH : LOW);
}
bool tankEmpty() {
return !isnan(tankPercent) && tankPercent < TANK_MIN_PERCENT;
}
// Starts the pump for a number of seconds, at most PUMP_MAX_SECONDS. False when the tank is empty.
bool startPump(uint32_t seconds) {
if (tankEmpty()) return false;
if (seconds < 1) seconds = 1;
if (seconds > PUMP_MAX_SECONDS) seconds = PUMP_MAX_SECONDS;
pumpOn = true;
pumpStartedMs = nowMs();
pumpRunMs = (uint64_t)seconds * 1000;
switchPump(true);
return true;
}
void stopPump() {
switchPump(false);
if (pumpOn) {
wateredSinceBoot = true;
lastWateredMs = nowMs();
}
pumpOn = false;
}
void watchPump() {
if (pumpOn && (nowMs() - pumpStartedMs >= pumpRunMs || tankEmpty())) stopPump();
// Automatic watering needs a soil reading it can believe and a tank level it knows: a soil sensor that
// fell out of the pot reads "dry" for ever.
if (!autoMode || pumpOn || !soilPlausible || isnan(soilPercent) || isnan(tankPercent)) return;
if (wateredSinceBoot && nowMs() - lastWateredMs < (uint64_t)AUTO_PAUSE_MINUTES * 60000) return;
if (soilPercent < (float)thresholdPercent) startPump(AUTO_WATER_SECONDS);
}
// ---------- history ----------
int16_t tenths(float value) {
return isnan(value) ? NO_SAMPLE : (int16_t)lroundf(value * 10.0f);
}
void storeSample() {
historySoil[historyNext] = tenths(soilPercent);
historyTemperature[historyNext] = tenths(temperatureC);
historyHumidity[historyNext] = tenths(humidityPercent);
historyNext = (historyNext + 1) % HISTORY_STORED;
if (historyCount < HISTORY_STORED) historyCount++;
}
// ---------- 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();
uint32_t secondsLeft = 0;
if (pumpOn && now - pumpStartedMs < pumpRunMs) secondsLeft = (uint32_t)((pumpRunMs - (now - pumpStartedMs) + 999) / 1000);
String json;
json.reserve(260);
json += "{\"soil\":";
addNumber(json, soilPlausible ? soilPercent : NAN, 1);
json += ",\"temperature\":";
addNumber(json, temperatureC, 1);
json += ",\"humidity\":";
addNumber(json, humidityPercent, 1);
json += ",\"light\":";
addNumber(json, lightLux, 0);
json += ",\"tank\":";
addNumber(json, tankPercent, 1);
json += ",\"pump\":";
json += pumpOn ? "true" : "false";
json += ",\"pumpSecondsLeft\":";
json += secondsLeft;
json += ",\"auto\":";
json += autoMode ? "true" : "false";
json += ",\"threshold\":";
json += thresholdPercent;
json += ",\"lastWateredSecondsAgo\":";
if (wateredSinceBoot) json += (uint32_t)((now - lastWateredMs) / 1000);
else json += "null"; // the ESP32 has no clock that survives a restart
json += ",\"rssi\":";
json += WiFi.RSSI();
json += ",\"uptimeSeconds\":";
json += (uint32_t)(now / 1000);
json += "}";
return json;
}
void addSeries(String &json, const char *name, const int16_t *samples, float current) {
json += ",\"";
json += name;
json += "\":[";
int first = historyCount < HISTORY_STORED ? 0 : historyNext; // the oldest sample
for (int i = 0; i < historyCount; i++) {
int16_t sample = samples[(first + i) % HISTORY_STORED];
if (sample == NO_SAMPLE) json += "null";
else json += String((float)sample / 10.0f, 1U);
json += ",";
}
addNumber(json, current, 1); // the last point is the reading of this moment
json += "]";
}
String historyJson() {
String json;
json.reserve(2200);
json += "{\"intervalSeconds\":";
json += HISTORY_INTERVAL_SECONDS;
addSeries(json, "soil", historySoil, soilPlausible ? soilPercent : NAN);
addSeries(json, "temperature", historyTemperature, temperatureC);
addSeries(json, "humidity", historyHumidity, humidityPercent);
json += "}";
return json;
}
// Just enough JSON reading for { "on": true }, { "seconds": 8 } and { "auto": true, "threshold": 35 }.
// Returns where the value of a key starts in a flat JSON object, 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 jsonBool(const String &body, const char *key, bool &value) {
int at = jsonValueAt(body, key);
if (at < 0) return false;
if (body.startsWith("true", at)) value = true;
else if (body.startsWith("false", at)) value = false;
else return false;
return true;
}
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;
}
// ---------- 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 handlePump() {
String body = server.arg("plain");
bool on = false;
float seconds = 0;
bool hasOn = jsonBool(body, "on", on);
bool hasSeconds = jsonNumber(body, "seconds", seconds);
if (!hasOn && !hasSeconds) {
sendError(400, "Send { 'on': true|false } or { 'seconds': n }.");
return;
}
if (hasOn && !on) {
stopPump();
} else {
// "on" without a time runs until it is switched off, and at most PUMP_MAX_SECONDS.
uint32_t wanted = hasSeconds ? (uint32_t)constrain(seconds, 1.0f, (float)PUMP_MAX_SECONDS) : PUMP_MAX_SECONDS;
if (!startPump(wanted)) {
sendError(409, "The tank is empty.");
return;
}
}
sendJson(200, stateJson());
}
void handleConfig() {
String body = server.arg("plain");
bool wantedAuto = false;
float wantedThreshold = 0;
bool hasAuto = jsonBool(body, "auto", wantedAuto);
bool hasThreshold = jsonNumber(body, "threshold", wantedThreshold);
if (!hasAuto && !hasThreshold) {
sendError(400, "Send { 'auto': true|false, 'threshold': percent }.");
return;
}
if (hasAuto && wantedAuto != autoMode) {
autoMode = wantedAuto;
settings.putBool("auto", autoMode);
}
if (hasThreshold) {
int threshold = (int)lroundf(constrain(wantedThreshold, (float)THRESHOLD_MIN, (float)THRESHOLD_MAX));
if (threshold != thresholdPercent) {
thresholdPercent = threshold;
settings.putUChar("threshold", (uint8_t)thresholdPercent);
}
}
sendJson(200, stateJson());
}
void setup() {
Serial.begin(115200);
// The pump is off before anything else happens.
pinMode(PIN_PUMP, OUTPUT);
switchPump(false);
pinMode(PIN_TANK_TRIG, OUTPUT);
pinMode(PIN_TANK_ECHO, INPUT);
analogReadResolution(12);
analogSetPinAttenuation(PIN_SOIL, ADC_11db); // the sensor's output goes up to about 3 V
Wire.begin(PIN_I2C_SDA, PIN_I2C_SCL);
startLight();
// What was set in the app survives a restart.
settings.begin("greenhouse", false);
autoMode = settings.getBool("auto", true);
thresholdPercent = constrain((int)settings.getUChar("threshold", 35), THRESHOLD_MIN, THRESHOLD_MAX);
WiFi.mode(WIFI_STA);
WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
// 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("/pump", HTTP_POST, handlePump);
server.on("/config", HTTP_POST, handleConfig);
// 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();
watchPump();
// Every two seconds: read everything. It takes about 50 ms.
static uint64_t lastRead = 0;
static bool readOnce = false;
if (!readOnce || nowMs() - lastRead >= 2000) {
lastRead = nowMs();
readOnce = true;
readSoil();
readAir();
readLight();
readTank();
}
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 pump's stop must not wait
lastComplaint = nowMs();
Serial.printf("The platform refused this device: %s\n", Connectivitizer.lastError());
}
}
}