2021-03-10 15:33:21 +01:00

208 lines
5.3 KiB
C++

// Load Wi-Fi library
#include <WiFi.h>
#include <analogWrite.h>
#include <PubSubClient.h>
#include "ArduinoJson.h"
// Replace with your network credentials
const char* ssid = "Xiaomi_Router";
const char* password = "UYQQMTHF";
// Assign output variables to GPIO pins
const int redPin = 26;
const int greenPin = 27;
const int bluePin = 25;
const int soundPin = 4;
// MQTT Infos
const char* subscribeLedTopic = "DIY/BedroomLed/set";
const char* subscribeClapTopic = "DIY/BedroomClap/set";
const char* getClapTopic = "DIY/BedroomClap/get";
const int mqtt_port = 1883;
const char* mqtt_server = "192.168.31.140";
const char* mqtt_client = "ESP32Client-BedroomLed";
boolean isClapEnabled = 1;
int greenValue = 0;
int redValue = 0;
int blueValue = 0;
boolean isSoundThreshold =0;
boolean isOpen = 0;
int thresholdNum = 0;
unsigned long firstClapMillis;
unsigned long secondClapMillis;
unsigned long currentMillis;
char message_buff[100];
WiFiClient espClient;
PubSubClient client(espClient);
void setup() {
Serial.begin(115200);
pinMode(soundPin, INPUT);
// Connect to Wi-Fi network with SSID and password
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
// Print local IP address and start web server
Serial.println("");
Serial.println("WiFi connected.");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
analogWriteResolution(8);
client.setServer(mqtt_server, mqtt_port);
client.setCallback(callback);
}
void loop(){
if(WiFi.status() != WL_CONNECTED){
setColor(1, 0, 0); // red
Serial.println("Trying to reconnect !");
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("Connected !");
//setColor(0, 255, 0); // green
}
if (!client.connected()) {
reconnect();
}
else
{
if(isClapEnabled) {
clapLogic();
}
}
client.loop();
}
void setColor(int redValue, int greenValue, int blueValue)
{
analogWrite(redPin, redValue);
analogWrite(greenPin, greenValue);
analogWrite(bluePin, blueValue);
if(redValue > 0 || greenValue > 0 || blueValue > 0) {
isOpen = 1;
} else {
isOpen = 0;
}
}
void callback(char* topic, byte* payload, unsigned int length) {
Serial.print("Message arrived [");
Serial.print(topic);
Serial.print("] ");
String payloadString;
for (int i = 0; i < length; i++) {
Serial.print((char)payload[i]);
payloadString += (char)payload[i];
}
DynamicJsonDocument result(1024);
deserializeJson(result, payloadString);
if(strcmp(topic, subscribeLedTopic) == 0) {
int red = result["red"];
int green = result["green"];
int blue = result["blue"];
setColor(red, green, blue);
}
if(strcmp(topic, subscribeClapTopic) == 0) {
boolean isEnabled = result["enabled"];
if(isEnabled) {
isClapEnabled = 1;
} else {
isClapEnabled = 0;
}
}
}
void clapLogic() {
isSoundThreshold = digitalRead(soundPin);
currentMillis = millis();
if(currentMillis - firstClapMillis > 1100 && firstClapMillis != 0 && secondClapMillis == 0) {
firstClapMillis = 0;
thresholdNum = 0;
Serial.println("reset first clap");
}
if(currentMillis - secondClapMillis > 2000 && secondClapMillis != 0) {
firstClapMillis = 0;
secondClapMillis = 0;
thresholdNum = 0;
Serial.println("ready for listening");
}
if(!isSoundThreshold) {
if (thresholdNum == 0) {
Serial.println("Set first clap");
firstClapMillis = millis();
thresholdNum ++;
}
if(currentMillis - firstClapMillis > 300 && firstClapMillis != 0 && secondClapMillis == 0) {
Serial.println("we have a two clap");
//String pubStringPost = String("{\"Temperature\":\""+String((double)bme.readTemperature())+"\",\"Pressure\":\""+String((int)bme.readPressure())+"\",\"Smoke\":\""+String((int)analogRead(gasPin))+"\"}");
String pubStringPost = String("{\"action\":\"clap\"}");
pubStringPost.toCharArray(message_buff, pubStringPost.length()+1);
client.publish(getClapTopic, message_buff);
if(isOpen) {
setColor(0, 0, 0); // Close led
Serial.println("CLOSE LED");
} else {
setColor(255, 255, 255); // WHITE CLEAR
Serial.println("WHITE CLEAR");
}
secondClapMillis = millis();
}
}
}
void reconnect() {
// Loop until we're reconnected
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
// Attempt to connect
if (client.connect(mqtt_client)) {
Serial.println("connected");
//setColor(0, 255, 255); // green
setColor(0, 0, 0); // Everything ok, it's connected to mqtt broker
client.subscribe(subscribeLedTopic);
client.subscribe(subscribeClapTopic);
String ipString = "{\"Name\":\"BedroomLed\",\"IpAddress\":\""+ WiFi.localIP().toString()+"\"}";
ipString.toCharArray(message_buff, ipString.length()+1);
client.publish("IpAddress",message_buff);
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
setColor(1, 0, 1); // not connected to mqtt broker
// Wait 5 seconds before retrying
delay(5000);
}
}
}