Created
August 1, 2016 00:39
-
-
Save sadv1r/54613a6b3f163b2af01fcc7c9fe352e5 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* WeMos MQTT Client | |
* | |
* Depends on Adafruit DHT Arduino library | |
* https://github.com/adafruit/DHT-sensor-library | |
*/ | |
#include <ESP8266WiFi.h> | |
#include <PubSubClient.h> | |
#include <DHT.h> | |
// Existing WiFi network | |
#define wifi_ssid "ASUS_Wemos_Network" | |
#define wifi_password "YBgHo4[YVvr89qu8FoW)d2}K9@" | |
#define in_topic "home/bathroom/#" | |
#define temperature_topic "home/bathroom/node/temperature" | |
#define humidity_topic "home/bathroom/node/humidity" | |
#define cold_water_topic "home/bathroom/node/water/cold" | |
#define hot_water_topic "home/bathroom/node/water/hot" | |
#define mqtt_server "m21.cloudmqtt.com" | |
#define mqtt_port 10477 | |
#define mqtt_user "ovixujus" | |
#define mqtt_password "Mdydf8dOHTpZ" | |
#define DHTTYPE DHT22 // DHT Shield uses DHT 22 | |
#define DHTPIN D4 // DHT Shield uses pin D4 | |
const int powerPin = D2; | |
const int servoPin = D3; | |
const int coldWaterPin = D5; | |
const int hotWaterPin = D6; | |
char payload_buff[100]; | |
WiFiClient espClient; | |
PubSubClient client(espClient); | |
// Initialize DHT sensor | |
DHT dht(DHTPIN, DHTTYPE); | |
float humidity, temperature; // Raw float values from the sensor | |
char str_humidity[10], str_temperature[10], str_heatindex[10]; // Rounded sensor values and as strings | |
// Generally, you should use "unsigned long" for variables that hold time | |
unsigned long previousMillis = 0; // When the sensor was last read | |
const long interval = 2000; // Wait this long until reading again | |
void read_sensor() { | |
// Wait at least 2 seconds seconds between measurements. | |
// If the difference between the current time and last time you read | |
// the sensor is bigger than the interval you set, read the sensor. | |
// Works better than delay for things happening elsewhere also. | |
unsigned long currentMillis = millis(); | |
if (currentMillis - previousMillis >= interval) { | |
// Save the last time you read the sensor | |
previousMillis = currentMillis; | |
// Reading temperature and humidity takes about 250 milliseconds! | |
// Sensor readings may also be up to 2 seconds 'old' (it's a very slow sensor) | |
humidity = dht.readHumidity(); // Read humidity as a percent | |
temperature = dht.readTemperature(); // Read temperature as Celsius | |
// Compute heat index in Celsius (isFahreheit = false) | |
float hic = dht.computeHeatIndex(temperature, humidity, false); | |
// Check if any reads failed and exit early (to try again). | |
if (isnan(humidity) || isnan(temperature)) { | |
Serial.println("Failed to read from DHT sensor!"); | |
return; | |
} | |
// Convert the floats to strings and round to 2 decimal places | |
dtostrf(humidity, 1, 2, str_humidity); | |
dtostrf(temperature, 1, 2, str_temperature); | |
dtostrf(hic, 1, 2, str_heatindex); | |
Serial.print("Humidity: "); | |
Serial.print(str_humidity); | |
Serial.print(" %\t"); | |
Serial.print("Temperature: "); | |
Serial.print(str_temperature); | |
Serial.println(" °C\t"); | |
Serial.print("Heat index: "); | |
Serial.print(str_heatindex); | |
Serial.println(" °C"); | |
} | |
void setup(void) | |
{ | |
// Open the Arduino IDE Serial Monitor to see what the code is doing | |
Serial.begin(9600); | |
delay(10); | |
Serial.println("\n\n=========================\n= WeMos D1 mini =\n= Bathroom node =\n========================="); | |
pinMode(powerPin, OUTPUT); | |
pinMode(servoPin, OUTPUT); | |
pinMode(coldWaterPin, INPUT); | |
pinMode(hotWaterPin, INPUT); | |
dht.begin(); | |
client.setServer(mqtt_server, mqtt_port); | |
Serial.println("Setup completed."); | |
Serial.println(""); | |
} | |
long lastMsg = 0; | |
float temp = 0.0; | |
float hum = 0.0; | |
float diff = 0.0; | |
bool coldWaterPinLastState; | |
bool hotWaterPinLastState; | |
int coldWater = 0; | |
int hotWater = 0; | |
bool checkBound(float newValue, float prevValue, float maxDiff) { | |
return !isnan(newValue) && | |
(newValue < prevValue - maxDiff || newValue > prevValue + maxDiff); | |
} | |
void loop() { | |
if (!client.connected()) { | |
reconnect(); | |
} | |
client.loop(); | |
long now = millis(); | |
if (now - lastMsg > 5000) { | |
lastMsg = now; | |
read_sensor(); | |
if (checkBound(temperature, temp, diff)) { | |
temp = temperature; | |
Serial.print("New temperature:"); | |
Serial.println(String(temp).c_str()); | |
client.publish(temperature_topic, String(temp).c_str(), false); | |
} | |
if (checkBound(humidity, hum, diff)) { | |
hum = humidity; | |
Serial.print("New humidity:"); | |
Serial.println(String(hum).c_str()); | |
client.publish(humidity_topic, String(hum).c_str(), false); | |
} | |
} | |
if (coldWaterPin == HIGH && coldWaterPinLastState == false) { | |
coldWater = coldWater + 1; | |
if (client.publish(cold_water_topic, String(coldWater).c_str(), false)) { | |
coldWater = 0; | |
} | |
coldWaterPinLastState = true; | |
} | |
if (hotWaterPin == HIGH && hotWaterPinLastState == false) { | |
hotWater = hotWater + 1; | |
if (client.publish(hot_water_topic, String(hotWater).c_str(), false)) { | |
hotWater = 0; | |
} | |
hotWaterPinLastState = true; | |
} | |
} | |
void setup_wifi() { | |
// Connect to your WiFi network | |
WiFi.begin(wifi_ssid, wifi_password); | |
Serial.print("Connecting"); | |
// Wait for successful connection | |
while (WiFi.status() != WL_CONNECTED) { | |
delay(500); | |
Serial.print("."); | |
} | |
Serial.println(""); | |
Serial.print("Connected to: "); | |
Serial.println(wifi_ssid); | |
Serial.print("IP address: "); | |
Serial.println(WiFi.localIP()); | |
} | |
void reconnect() { | |
// Loop until we're reconnected | |
while (!client.connected()) { | |
Serial.println("Attempting MQTT connection..."); | |
if (client.connect("ESP8266BathroomClient", mqtt_user, mqtt_password, "home/bathroom/node", 2, 0, "disconnected")) { | |
Serial.println("connected"); | |
client.setCallback(callback); | |
client.subscribe(in_topic); | |
} else { | |
Serial.print("failed, rc="); | |
Serial.print(client.state()); | |
Serial.println(" try again in 5 seconds"); | |
// Wait 5 seconds before retrying | |
delay(5000); | |
} | |
} | |
} | |
// handles message arrived on subscribed topic(s) | |
void callback(char* topic, byte* payload, unsigned int length) { | |
// create character buffer with ending null terminator (string) | |
int i = 0; | |
for(i=0; i<length; i++) { | |
payload_buff[i] = payload[i]; | |
} | |
payload_buff[i] = '\0'; | |
String payloadString = String(payload_buff); | |
Serial.println(String(topic) + " => " + payloadString); | |
if (String(topic) == "home/bathroom/washer/water") { // проверяем из нужного ли нам топика пришли данные | |
int stled = payloadString.toInt(); // преобразуем полученные данные в тип integer | |
digitalWrite(servoPin,stled); // включаем или выключаем свет в зависимоти от полученных значений данных | |
} | |
if (String(topic) == "home/bathroom/washer/power") { // проверяем из нужного ли нам топика пришли данные | |
int stled = payloadString.toInt(); // преобразуем полученные данные в тип integer | |
digitalWrite(powerPin,stled); // включаем или выключаем свет в зависимоти от полученных значений данных | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment