#include "RMaker.h"
#include "WiFi.h"
// Hardware Pins
const int relay_pins[] = {23, 22, 21, 19, 18, 5, 4, 15};
const int switch_pins[] = {32, 33, 25, 26, 27, 14, 12, 13};
const char *switch_names[] = {"Fan", "Light 1", "Light 2", "Light 3", "Light 4", "Light 5", "Light 6", "Socket"};
static Switch *my_switches[8];
void write_callback(Device *device, Param *param, const param_val_t val, void *priv_data, write_ctx_t *ctx) {
for (int i = 0; i < 8; i++) {
if (strcmp(device->getDeviceName(), switch_names[i]) == 0) {
digitalWrite(relay_pins[i], val.val.b ? LOW : HIGH);
}
}
}
void setup() {
Serial.begin(115200);
for (int i = 0; i < 8; i++) {
pinMode(relay_pins[i], OUTPUT);
digitalWrite(relay_pins[i], HIGH);
pinMode(switch_pins[i], INPUT_PULLUP);
}
// Node Initialize
Node my_node = RMaker.initNode("ESP32_Home");
for (int i = 0; i < 8; i++) {
my_switches[i] = new Switch(switch_names[i], (void *)&relay_pins[i]);
my_switches[i]->addCb(write_callback);
my_node.addDevice(*my_switches[i]);
}
RMaker.start();
// Wokwi Testing ke liye Direct WiFi
WiFi.begin("Wokwi-GUEST", "");
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("\nWiFi Connected! Please wait for RainMaker...");
}
void loop() {
static bool last_s[8] = {1,1,1,1,1,1,1,1};
for (int i = 0; i < 8; i++) {
bool curr = digitalRead(switch_pins[i]);
if (curr != last_s[i]) {
delay(50);
if (digitalRead(switch_pins[i]) == curr) {
bool r_state = !digitalRead(relay_pins[i]);
digitalWrite(relay_pins[i], r_state);
if(my_switches[i] != NULL) {
my_switches[i]->updateAndReportParam(ESP_RMAKER_DEF_POWER_NAME, (r_state == LOW));
}
last_s[i] = curr;
}
}
}
}