#include <WiFi.h>
#include "ThingsBoard.h"
#include "DHTesp.h"
#include <LiquidCrystal_I2C.h>
#define CURRENT_FIRMWARE_TITLE "TEST"
#define CURRENT_FIRMWARE_VERSION "1.0.0"
#define WIFI_SSID "Wokwi-GUEST"
#define WIFI_PASSWORD ""
// See https://thingsboard.io/docs/getting-started-guides/helloworld/
// to understand how to obtain an access token
#define TOKEN "MsF0Mys9pG7sUWxYrHYO"
#define THINGSBOARD_SERVER "thingsboard.cloud"
// Helper macro to calculate array size
#define COUNT_OF(x) ((sizeof(x)/sizeof(0[x])) / ((size_t)(!(sizeof(x) % sizeof(0[x])))))
// Baud rate for debug serial
#define SERIAL_DEBUG_BAUD 115200
const int FAN_PIN = 12;
const int PUMP_PIN = 14;
WiFiClient espClient;
ThingsBoard tb(espClient);
int status = WL_IDLE_STATUS;
bool subscribed = false;
RPC_Response setFanState(const RPC_Data &data)
{
Serial.println("Received the setFanState method");
// Process data
bool state = data["state"] == "on";
digitalWrite(FAN_PIN, state ? HIGH : LOW);
// Just an response example
return RPC_Response("fan_on", state ? HIGH : LOW);
}
RPC_Response setPumpState(const RPC_Data &data)
{
Serial.println("Received the setPumpState method");
// Process data
bool state = data["state"] == "on";
digitalWrite(PUMP_PIN, state ? HIGH : LOW);
// Just an response example
return RPC_Response("pump_on", state ? HIGH : LOW);
}
RPC_Callback callbacks[] = {
{ "setFanState", setFanState },
{ "setPumpState", setPumpState }
};
void InitWiFi()
{
Serial.println("Connecting to AP ...");
WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("Connected to AP");
}
void reconnect() {
status = WiFi.status();
if ( status != WL_CONNECTED) {
WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("Connected to AP");
}
}
void setup() {
pinMode(PUMP_PIN, OUTPUT);
pinMode(FAN_PIN, OUTPUT);
// initialize serial for debugging
Serial.begin(SERIAL_DEBUG_BAUD);
Serial.println();
InitWiFi();
}
void loop() {
if (WiFi.status() != WL_CONNECTED) {
reconnect();
}
if (!tb.connected()) {
subscribed = false;
// Connect to the ThingsBoard
Serial.print("Connecting to: ");
Serial.print(THINGSBOARD_SERVER);
Serial.print(" with token ");
Serial.println(TOKEN);
if (!tb.connect(THINGSBOARD_SERVER, TOKEN)) {
Serial.println("Failed to connect");
return;
}
}
if (!subscribed) {
Serial.println("Subscribing for RPC...");
// Perform a subscription. All consequent data processing will happen in
// processTemperatureChange() and processSwitchChange() functions,
// as denoted by callbacks vector.
if (!tb.RPC_Subscribe(callbacks, COUNT_OF(callbacks))) {
Serial.println("Failed to subscribe for RPC");
return;
}
Serial.println("Subscribe done");
subscribed = true;
}
tb.loop();
delay(2000);
}