#include <ESP32Servo.h>
#include <WiFi.h>
#include <ThingsBoard.h>
#include <HTTPClient.h>
String wifiSSID = "Wokwi-GUEST";
String wifiPassword = "";
String tbHost = "demo.thingsboard.io";
String tbToken = "MRJPdzUkKfTDUBwY0dCy";
bool subscribed = false;
int ldr, kunci;
Servo lock1;
RPC_Response processSetGpioState(const RPC_Data &data) {
Serial.println("Received the set GPIO RPC method");
int pin = data["pin"];
bool enabled = data["enabled"];
digitalWrite(pin, enabled);
String responseMessage = "{\"pin\": " + String(pin) + ", \"enabled\": " + String(enabled ? "true" : "false") + "}";
return RPC_Response(responseMessage.c_str(), "pin");
}
// RPC handlers
RPC_Callback callbacks[] = {
{ "setGpioStatus", processSetGpioState },
};
void connectWifi() {
WiFi.begin(wifiSSID.c_str(), wifiPassword.c_str());
while (WiFi.status() != WL_CONNECTED) {
delay(500);
}
}
void sendDataToThingsBoard(String Kondisi) {
HTTPClient http;
String url = "http://" + tbHost + "/api/v1/" + tbToken + "/telemetry";
String payload = "{\"Kondisi\":" + Kondisi + "}";
http.begin(url);
http.addHeader("Content-Type", "application/json");
int httpResponseCode = http.POST(payload);
if (httpResponseCode > 0) {
Serial.println("Data sent to ThingsBoard successfully");
} else {
Serial.println("Error sending data to ThingsBoard");
}
http.end();
}
void setup() {
Serial.begin(115200);
connectWifi();
lock1.attach(23);
}
void loop() {
delay(1000);
if (WiFi.status() != WL_CONNECTED) {
// Reconnect to Wi-Fi
// Your Wi-Fi reconnection logic here
}
if (!tb.connected()) {
// Connect to ThingsBoard
if (!tb.connect(tbHost, tbToken)) {
Serial.println("Failed to connect to ThingsBoard");
return;
}
}
if (!subscribed) {
// Subscribe for RPC
if (!tb.RPC_Subscribe(callbacks)) {
Serial.println("Failed to subscribe for RPC");
return;
}
Serial.println("Subscribe done");
subscribed = true;
}
// Other code for sending data and ThingsBoard loop
// ...
}
// Assuming you want to send the 'kunci' value to ThingsBoard
sendDataToThingsBoard(String(kunci));
delay(1000); // Adjust the delay based on your requirements
}