#include <WiFi.h>
#include <ThingsBoard.h>
#define WIFI_AP "Wokwi-GUEST"
#define WIFI_PASS ""
#define TB_SERVER "demo.thingsboard.io"
#define TOKEN "9h2ylwrwjropeb5scigw"
#define led1 26
#define led2 14
#define led3 12
WiFiClient wifiClient;
ThingsBoard tb(wifiClient);
int led_state = 0;
RPC_Response setLedSwitchState(RPC_Data &data) {
Serial.println("Received Switch State");
led_state = data;
Serial.println("Switch State Change");
Serial.print(led_state);
return RPC_Response("setLedSwitchValue", led_state);
}
const std::array<RPC_Callback, 1U> cb = {
RPC_Callback("setLedSwitchValue", setLedSwitchState)
};
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
Serial.println("Hello, ESP32!");
pinMode(led1, OUTPUT);
pinMode(led2, OUTPUT);
pinMode(led3, OUTPUT);
WiFi.begin(WIFI_AP, WIFI_PASS, 6);
while(WiFi.status() != WL_CONNECTED){
Serial.print(".");
delay(500);
}
}
void loop() {
if((WiFi.status() != WL_CONNECTED)) {
while(WiFi.status() != WL_CONNECTED){
Serial.print(".");
delay(500);
}
Serial.println("Connected");
}
while(!tb.connected()){
if(!tb.connect(TB_SERVER, TOKEN)){
Serial.println("Connected to server!");
if(!tb.RPC_Subscribe(cb.cbegin(), cb.cend())){
Serial.println("Failed to Subscribe RPC");
return;
}
}
}
if(led_state){
digitalWrite(led1, HIGH);
}
else{
digitalWrite(led1, LOW);
}
tb.loop();
}