From 2d8a30572b49875a2aa027b349d915572fa63bc9 Mon Sep 17 00:00:00 2001 From: Timo Volkmann Date: Mon, 29 Jun 2020 00:48:05 +0200 Subject: [PATCH] implemented WiFi & MQTT and some improvements in existing code --- platformio.ini | 4 +- src/capacitiveSoilMoistureSensor.cpp | 35 +------ src/connections.cpp | 151 +++++++++++++++++++++++++++ src/header.h | 34 ++++-- src/lightSensor.cpp | 5 +- src/main.cpp | 50 ++++++--- src/temperatureSensor.cpp | 4 +- 7 files changed, 223 insertions(+), 60 deletions(-) create mode 100644 src/connections.cpp diff --git a/platformio.ini b/platformio.ini index 8c210a4..fe810f5 100644 --- a/platformio.ini +++ b/platformio.ini @@ -18,5 +18,7 @@ lib_deps = 439 #ID of Lightsensor library BH1750 19 #DHT sensor library 31 #Adafruit Unified Sensor - ; AutoConnect@^1.1.7 + AutoConnect@^1.1.7 + ; ESPRandom@^1.3.3 + AsyncMqttClient@^0.8.2 ; PubSubClient@^2.8 \ No newline at end of file diff --git a/src/capacitiveSoilMoistureSensor.cpp b/src/capacitiveSoilMoistureSensor.cpp index b73b462..b5184f9 100644 --- a/src/capacitiveSoilMoistureSensor.cpp +++ b/src/capacitiveSoilMoistureSensor.cpp @@ -4,37 +4,12 @@ #include -const int numReadings = 10; - -int readings[numReadings]; // the readings from the analog input -int readIndex = 0; // the index of the current reading -int total = 0; // the running total -int average = 0; // the average - void setupCapacitiveSoilMoistureSensor() { - for (int thisReading = 0; thisReading < numReadings; thisReading++) { - readings[thisReading] = 0; - } + // pinMode(PIN_MS, INPUT); } -int loopCapacitiveSoilMoistureSensor() { - // subtract the last reading: - total = total - readings[readIndex]; - // read from the sensor: - readings[readIndex] = analogRead(PIN_MS); - // add the reading to the total: - total = total + readings[readIndex]; - // advance to the next position in the array: - readIndex = readIndex + 1; - - // if we're at the end of the array... - if (readIndex >= numReadings) { - // ...wrap around to the beginning: - readIndex = 0; - } - - // calculate the average: - average = total / numReadings; - - return average; +int readCapacitiveSoilMoistureSensor() +{ + int measurement = analogRead(PIN_MS); + return map(measurement, VALUE_AIR, VALUE_WATER, 0, 100); } \ No newline at end of file diff --git a/src/connections.cpp b/src/connections.cpp new file mode 100644 index 0000000..ead2694 --- /dev/null +++ b/src/connections.cpp @@ -0,0 +1,151 @@ +#include + +extern "C" +{ +#include "freertos/FreeRTOS.h" +#include "freertos/timers.h" +} + +AsyncMqttClient mqttClient; +TimerHandle_t mqttReconnectTimer; +TimerHandle_t wifiReconnectTimer; + +WebServer Server; +AutoConnect Portal(Server); +WiFiClient client; + +AutoConnectConfig Config; +// Config.autoReconnect = true; +// WiFi.config(Config); + +void connectWiFi() +{ + Serial.println("Start WiFi..."); + if (Portal.begin()) + { + digitalWrite(PIN_LED_G, HIGH); + } +} + +void connectMQTT() +{ + Serial.println("Connecting to MQTT..."); + mqttClient.setClientId(MQTT_DEVICE_ID); + mqttClient.connect(); +} + +void WiFiEvent(WiFiEvent_t event) +{ + Serial.printf("[WiFi-event] event: %d\n", event); + switch (event) + { + case SYSTEM_EVENT_STA_GOT_IP: + Serial.println("WiFi connected"); + Serial.println("IP address: "); + Serial.println(WiFi.localIP()); + connectMQTT(); + break; + case SYSTEM_EVENT_STA_DISCONNECTED: + digitalWrite(PIN_LED_G, LOW); + Serial.println("WiFi lost connection"); + xTimerStop(mqttReconnectTimer, 0); // ensure we don't reconnect to MQTT while reconnecting to Wi-Fi + xTimerStart(wifiReconnectTimer, 0); + break; + } +} + +void onMqttConnect(bool sessionPresent) +{ + Serial.println("Connected to MQTT."); + Serial.print("Session present: "); + Serial.println(sessionPresent); + uint16_t packetIdSub = mqttClient.subscribe("smartgarden/test", 2); + Serial.print("Subscribing at QoS 2, packetId: "); + Serial.println(packetIdSub); + mqttClient.publish("test/lol", 0, true, "test 1"); + Serial.println("Publishing at QoS 0"); + uint16_t packetIdPub1 = mqttClient.publish("smartgarden/test", 1, true, "test 2"); + Serial.print("Publishing at QoS 1, packetId: "); + Serial.println(packetIdPub1); + uint16_t packetIdPub2 = mqttClient.publish("smartgarden/test", 2, true, "test 3"); + Serial.print("Publishing at QoS 2, packetId: "); + Serial.println(packetIdPub2); +} + +void onMqttDisconnect(AsyncMqttClientDisconnectReason reason) +{ + Serial.println("Disconnected from MQTT."); + + if (WiFi.isConnected()) + { + xTimerStart(mqttReconnectTimer, 0); + } +} + +void onMqttSubscribe(uint16_t packetId, uint8_t qos) +{ + Serial.println("Subscribe acknowledged."); + Serial.print(" packetId: "); + Serial.println(packetId); + Serial.print(" qos: "); + Serial.println(qos); +} + +void onMqttUnsubscribe(uint16_t packetId) +{ + Serial.println("Unsubscribe acknowledged."); + Serial.print(" packetId: "); + Serial.println(packetId); +} + +void onMqttMessage(char *topic, char *payload, AsyncMqttClientMessageProperties properties, size_t len, size_t index, size_t total) +{ + Serial.println("Publish received."); + Serial.print(" topic: "); + Serial.println(topic); + Serial.print(" qos: "); + Serial.println(properties.qos); + Serial.print(" dup: "); + Serial.println(properties.dup); + Serial.print(" retain: "); + Serial.println(properties.retain); + Serial.print(" len: "); + Serial.println(len); + Serial.print(" index: "); + Serial.println(index); + Serial.print(" total: "); + Serial.println(total); +} + +void onMqttPublish(uint16_t packetId) +{ + Serial.println("Publish acknowledged."); + Serial.print(" packetId: "); + Serial.println(packetId); +} + +void setupConnections() +{ + pinMode(PIN_LED_G, OUTPUT); + Serial.println(); + Serial.println(); + + mqttReconnectTimer = xTimerCreate("mqttTimer", pdMS_TO_TICKS(2000), pdFALSE, (void *)0, reinterpret_cast(connectMQTT)); + wifiReconnectTimer = xTimerCreate("wifiTimer", pdMS_TO_TICKS(2000), pdFALSE, (void *)0, reinterpret_cast(connectWiFi)); + + WiFi.onEvent(WiFiEvent); + + mqttClient.onConnect(onMqttConnect); + mqttClient.onDisconnect(onMqttDisconnect); + mqttClient.onSubscribe(onMqttSubscribe); + mqttClient.onUnsubscribe(onMqttUnsubscribe); + mqttClient.onMessage(onMqttMessage); + mqttClient.onPublish(onMqttPublish); + mqttClient.setServer(MQTT_HOST, MQTT_PORT); + + connectWiFi(); +} + +void publishMessage(const char *topic, const char *msg) { + mqttClient.publish(topic, 1, true, msg); +} diff --git a/src/header.h b/src/header.h index 1fddfd2..7eab5cf 100644 --- a/src/header.h +++ b/src/header.h @@ -12,9 +12,10 @@ #include #include -// BH1750 LIGHT METER -// #define PIN_BH1750_SDA -// #define PIN_BH1750_SCL +#include +#include +#include +#include // DHT11 #define PIN_DHT11 14 @@ -23,8 +24,10 @@ #define PIN_MQ135_A 12 #define PIN_MQ135_D 13 -// MOISTURE SENSOR -#define PIN_MS 27 +// MOISTURE SENSOR // A7 +#define PIN_MS 35 +#define VALUE_WATER 275 +#define VALUE_AIR 430 // Ventil #define PIN_VENTIL 26 @@ -34,16 +37,29 @@ #define PIN_LED_G 0 #define PIN_LED_B 4 +// MQTT +#define MQTT_HOST "mqtt.timovolkmann.de" +#define MQTT_PORT 1883 +#define MQTT_DEVICE_ID "esp-timo" +#define MQTT_TOPIC_BASE_SUBSCRIBE "smartgarden/commands" +#define MQTT_TOPIC_BASE_PUBLISH "smartgarden/updates" + +// PUBLISH FREQUENCY (MS) +#define FREQUENCY 3000 // moisture extern void setupCapacitiveSoilMoistureSensor(); -extern int loopCapacitiveSoilMoistureSensor(); +extern int readCapacitiveSoilMoistureSensor(); // light extern void setupLightSensor(); -extern int readLightSensorValue(); +extern float readLightSensorValue(); // temperature & humidity extern void setupTemperatureSensor(); -extern int readHumidity(); -extern int readTemperature(); \ No newline at end of file +extern float readHumidity(); +extern float readTemperature(); + +// mqtt & wifi +extern void setupConnections(); +extern void publishMessage(const char *topic, const char *msg); \ No newline at end of file diff --git a/src/lightSensor.cpp b/src/lightSensor.cpp index 6b2c566..1dca49b 100644 --- a/src/lightSensor.cpp +++ b/src/lightSensor.cpp @@ -8,7 +8,8 @@ void setupLightSensor() { Serial.println("Sensor started..."); } -int readLightSensorValue() { - uint16_t intensity = lightMeter.readLightLevel(); +float readLightSensorValue() +{ + float intensity = lightMeter.readLightLevel(); return intensity; } \ No newline at end of file diff --git a/src/main.cpp b/src/main.cpp index 0990fda..198940a 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -4,31 +4,49 @@ #include +unsigned long pingTimer = 0; +char buffer[16]; + void setup() { Serial.begin(115200); - setupCapacitiveSoilMoistureSensor(); + pingTimer = millis(); + setupConnections(); setupLightSensor(); setupTemperatureSensor(); + setupCapacitiveSoilMoistureSensor(); + Serial.println("Setup complete..."); + Serial.println(); + Serial.println(); } void loop() { - uint16_t lxValue = readLightSensorValue(); - Serial.print("Light intensity: "); - Serial.print(lxValue); - Serial.println(" lx"); + if (millis() - pingTimer >= FREQUENCY) { + float lxValue = readLightSensorValue(); + Serial.print("Light intensity: "); + Serial.print(lxValue); + Serial.println(" lx"); + sprintf(buffer, "%f", lxValue); + publishMessage("smartgarden/updates/esp-N2Ff4kaDgs45/brightness", buffer); - uint16_t mstValue = loopCapacitiveSoilMoistureSensor(); - Serial.print("Soil moisture: "); - Serial.println(mstValue); + int mstValue = readCapacitiveSoilMoistureSensor(); + Serial.print("Soil moisture: "); + Serial.println(mstValue); + sprintf(buffer, "%i", mstValue); + publishMessage("smartgarden/updates/esp-N2Ff4kaDgs45/moisture", buffer); - uint16_t humidityValue = readHumidity(); - Serial.print("Humidity: "); - Serial.println(humidityValue); + float humidityValue = readHumidity(); + Serial.print("Humidity: "); + Serial.println(humidityValue); + sprintf(buffer, "%f", humidityValue); + publishMessage("smartgarden/updates/esp-N2Ff4kaDgs45/humidity", buffer); - uint16_t temperatureValue = readTemperature(); - Serial.print("Temperature: "); - Serial.println(temperatureValue); - Serial.print("\n"); + float temperatureValue = readTemperature(); + Serial.print("Temperature: "); + Serial.println(temperatureValue); + sprintf(buffer, "%f", temperatureValue); + publishMessage("smartgarden/updates/esp-N2Ff4kaDgs45/temperature", buffer); + Serial.print("\n"); - delay(2000); // delay in between reads for stability + pingTimer = millis(); + } } \ No newline at end of file diff --git a/src/temperatureSensor.cpp b/src/temperatureSensor.cpp index 66e006e..61ba0be 100644 --- a/src/temperatureSensor.cpp +++ b/src/temperatureSensor.cpp @@ -17,7 +17,7 @@ void setupTemperatureSensor() { } // Get humidity event and its value. -int readHumidity(){ +float readHumidity(){ sensors_event_t event; dht.humidity().getEvent(&event); @@ -25,7 +25,7 @@ int readHumidity(){ } // Get temperature event and its value. -int readTemperature(){ +float readTemperature(){ sensors_event_t event; dht.temperature().getEvent(&event); return event.temperature;