#include <WiFi.h>
#include <ThingsBoard.h>
#define WIFI_SSID "Wokwi-GUEST"
#define WIFI_PASS ""
#define TB_SERVER "technophys-tb.claurendeau.qc.ca"
#define TB_TOKEN ""
WiFiClient TBclient;
ThingboardSized<32> tb(TBclient,128);
int led_state 0;
bool led_state_change = false;
int maxLoopCount = 15;
#define ledPin 12
RPC_Response setLedSwitchState(RPC_Data &data) {
Serial.println("Received Switch state");
led_state = data;
led_state_change = true;
Serial.print("Switch changed to: "+String(led_state));
return RPC_Response("setLedSwitchValue",led_state);
}
const std::array<RPC_Callback, 1U> cb = {
RPC_Callback("setLedSwitchValue",setLedSwitchState)
};
bool WiFiConnect() {
bool retCode =false;
if(Wifi.status() != WL_CONNECTED) {
int loopCount = 0;
while(!WiFi.status() != WL_CONNECTED && loopCount<maxLoopCount) {
Serial.print(".");
loopCount++;
delay(1000);
}
if (loopCount<maxLoopCount) {
Serial.println("Wifi (re)connected");
retCode = true;
} else {
Serial.println("Wifi connection failed");
}
}
return retCode;
}
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
Serial.println("Hello, ESP32!");
pinMode(ledPin, OUTPUT);
WiFi.begin(WIFI_SSID,WIFI_PASS);
WiFiConnect();
}
void loop() {
if (WiFiConnect()) {
while (!tb.connected()) {
if (tb.connect(TB_SERVER,TB_TOKEN)) {
Serial.println("TB Connected");
if (!tb.RPC_Subscribe(cb.cbegin(),cb.cend())) {
Serial.println("Failed to RPC Subscribe");
}
}
}
}
if (led_state_change) {
if (led_state)
digitalWrite(ledPin,HIGH);
else
digitalWrite(ledPin,LOW);
led_state_change = false;
}
}