#include "secret.h"
#include<WiFiClientSecure.h>
#include <PubSubClient.h>
#include <ArduinoJson.h>
#define R 18
#define RL 19
#define B 32
#define BL 33
#define G 27
#define GL 14
#define sub_topic "esp32/sub"
#define pub_topic "esp32/sub"
WiFiClientSecure n=WiFiClientSecure();
PubSubClient client(n);
void wifiConnect();
void alarm();
void callback(char*, byte*, unsigned int);
int state=0;
void wifiConnect() {
WiFi.mode(WIFI_STA);
WiFi.begin(WIFI_SSID,WIFI_PASS);
while (WiFi.status() != WL_CONNECTED) {
delay(300);
Serial.print(".");
}
Serial.println();
Serial.println("Wifi Connected!");
Serial.print("WIFI STATUS:");
Serial.println(WiFi.status());
}
void callback(char* topic, byte* payload, unsigned int length) {
StaticJsonDocument<200> d;
deserializeJson(d,payload);
if(d["state"])state = d["state"];
Serial.println(state);
if(d["msg"])Serial.println((const char*)d["msg"]);
if(d["t"])Serial.println((int)d["t"]);
if(d["h"])Serial.println((int)d["h"]);
}
void setup() {
pinMode(R, OUTPUT);
pinMode(RL, OUTPUT);
pinMode(G, OUTPUT);
pinMode(GL, OUTPUT);
pinMode (B,OUTPUT);
pinMode(BL,OUTPUT);
Serial.begin(115200);
wifiConnect();
n.setCACert(AWS_CERT_CA);
n.setCertificate(AWS_CERT_CRT);
n.setPrivateKey(AWS_CERT_PRIVATE);
client.setServer(AWS_IOT_ENDPOINT,8883);
client.setCallback(callback);
}
void loop() {
if(!client.connected()) {
while(!client.connect(THINGNAME)){
delay(500);
Serial.println("connecting to endpoint");
}
Serial.println("at line 69,outside while ");
client.subscribe(sub_topic);
Serial.println("aws connected");
}
digitalWrite(R, LOW);
digitalWrite(RL, LOW);
digitalWrite(G,LOW);
digitalWrite(GL,LOW);
digitalWrite(B, LOW);
digitalWrite(BL,LOW);
alarm();
if(Serial.available()){
String a=Serial.readString();
StaticJsonDocument<200> d ;
a.trim();
if(a=="t"){
Serial.println("enter temperature limit");
while(!Serial.available());
int b=Serial.parseInt();
Serial.println(b);
d["t"]=b;
char jb[512];
serializeJson(d,jb);
client.publish(pub_topic,jb);
}
else if(a=="h"){
Serial.println("enter humidity limit");
while(!Serial.available());
int b=Serial.parseInt();
d["h"]=b;
char jb[512];
serializeJson(d,jb);
client.publish(pub_topic,jb);
}
}
client.loop();
}
void alarm(){
int b=state;
if(b==1){
digitalWrite(R,HIGH);
tone(25,2222,300);
tone(25,1111,200);
delay(300);
noTone(25);
}
else if(b==2){
digitalWrite(B,HIGH);
}
else if(b==3){
digitalWrite( G, HIGH);
}
}