#if defined(ESP8266)
#include <ESP8266WiFi.h>
#elif defined(ESP32)
#include <WiFi.h>
#endif
#include "ThingsBoard.h"
#include <PubSubClient.h>
#define LDR 34
const float GAMMA = 0.7;
const float RL10 = 50;
const char *ssid = "Wokwi-GUEST";
const char *password = "";
#define TOKEN "Wy0CYFea2dxN6ytv6S9i" //Access token of device Display
const char* mqtt_server = "thingsboard.cloud";
WiFiClient wifiClient;
PubSubClient client(wifiClient);
int status = WL_IDLE_STATUS;
void setup()
{
Serial.begin(9600);
delay(10);
pinMode(LDR, INPUT); //pin analog tidak diinisialisasi tidak masalah
Serial.print(" Connect to : ");
Serial.println(ssid);
WiFi.begin(ssid, password);
// WiFi.config(IP, NETWORK, NETMASK, DNS);
while (WiFi.status() != WL_CONNECTED)
{
delay(500);
Serial.print("...");
}
Serial.print("\n");
Serial.print("IP address : ");
Serial.print(WiFi.localIP());
Serial.print("\n");
Serial.print("Connect to : ");
Serial.println(ssid);
client.setServer( mqtt_server, 1883);
// client.setCallback(callback);
}
void loop()
{
if ( !client.connected() )
{
reconnect();
}
getData();
delay(5000);
}
void getData()
{
int analogValue = analogRead(34);
float voltage = analogValue * 5/4095.0;
float resistance = 2000 * voltage / (1 - voltage / 5);
float lux = pow(RL10 * 1e3 * pow(10, GAMMA) / resistance, (1 / GAMMA));
Serial.println(lux);
//script json
String payload = "{";
payload += "\"Intensitas Cahaya\":";payload += lux; // outputnya {"intensitas cahaya": 100}
payload += "}";
//array yang dikirim ke thingsboard
char attributes[1000]; //pembuatan array atribut, array ini jumlahnya 1000 karakter data, array ini akan dikirim ke server
payload.toCharArray( attributes, 1000 ); //variabel payload akan dibuat ke char array dengan nilai 1000
client.publish( "v1/devices/me/telemetry",attributes); //publish data dari array atribut ke topik yang sudah ada dari thingsboard
Serial.println( attributes );
}
//mengkoneksikan ulang esp ke thingsboard
void reconnect() {
// Loop until we're reconnected
while (!client.connected()) {
status = WiFi.status();
if ( status != WL_CONNECTED) {
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("Connected to AP");
}
Serial.print("Connecting to ThingsBoard node ...");
// Attempt to connect (clientId, username, password)
if ( client.connect("3a90f960-1ad1-11ed-b480-cbe4cea4aa70", TOKEN, "") ) {
Serial.println( "[DONE]" );
} else {
Serial.print( "[FAILED] [ rc = " );
Serial.println( " : retrying in 5 seconds]" );
delay( 500 );
}
}
}