void setup(){
webSocket.begin(); // init the Websocketserver
webSocket.onEvent(webSocketEvent); // init the webSocketEvent function when a websocket event occurs
dht.begin(); // Init DHT sensor
randomSeed(analogRead(0));
}
void loop() {
server.handleClient(); // webserver methode that handles all Client
webSocket.loop(); // websocket server methode that handles all Client
unsigned long currentMillis = millis(); // call millis and Get snapshot of time
if ((unsigned long)(currentMillis - previousMillis) >= interval) { // How much time has passed, accounting for rollover with subtraction!
update_temp_hum(); // update temperature data.
update_webpage(); // Update Humidity Data
previousMillis = currentMillis; // Use the snapshot to set track time until next event
}
}
// This function gets a call when a WebSocket event occurs
void webSocketEvent(byte num, WStype_t type, uint8_t * payload, size_t length) {
switch (type) {
case WStype_DISCONNECTED: // enum that read status this is used for debugging.
Serial.print("WS Type ");
Serial.print(type);
Serial.println(": DISCONNECTED");
break;
case WStype_CONNECTED: // Check if a WebSocket client is connected or not
Serial.print("WS Type ");
Serial.print(type);
Serial.println(": CONNECTED");
if (digitalRead(22) == HIGH) { //check if pin 22 is high or low
pin_status = "ON";
update_webpage(); // update the webpage accordingly
}
else {
pin_status = "OFF"; //check if pin 22 is high or low
update_webpage();// update the webpage accordingly
}
break;
case WStype_TEXT: // check responce from client
Serial.println(); // the payload variable stores teh status internally
Serial.println(payload[0]);
if (payload[0] == '1') {
pin_status = "ON";
digitalWrite(22, HIGH);
}
if (payload[0] == '0') {
pin_status = "OFF";
digitalWrite(22, LOW);
}
break;
}
}
void update_temp_hum(){
//h = dht.readHumidity(); // Read temperature as Celsius (the default)
//t = dht.readTemperature(); // Read temperature as Fahrenheit (isFahrenheit = true
h = random(100);
t = random(40);
}
void update_webpage()
{
StaticJsonDocument<100> doc;
// create an object
JsonObject object = doc.to<JsonObject>();
object["PIN_Status"] = pin_status ;
object["Temp"] = t ;
object["Hum"] = h ;
serializeJson(doc, jsonString); // serialize the object and save teh result to teh string variable.
Serial.println( jsonString ); // print the string for debugging.
webSocket.broadcastTXT(jsonString); // send the JSON object through the websocket
jsonString = ""; // clear the String.
}