#include <WiFi.h>
#include <PubSubClient.h>
#define LDR 35
const float GAMMA = 0.7;
const float RL10 = 50;
const char *ssid = "Wokwi-GUEST";
const char *password = "";
#define DEVICEID "DEV6659cf3d0616223552" // Device ID Telkom IoT
#define KEY "18fced22c305117f" // Access Key Telkom IoT
#define TOKEN "18fced22c30b6d0a" // Access Token Telkom IoT
const char* mqtt_server = "mqtt.telkomiot.id"; // MQTT Server Telkom IoT
const char* mqtt_topic = "/v2.0/subs/APP6659cf125317f26883/DEV6659cf3d0616223552"; // MQTT Topic Telkom IoT
WiFiClient wifiClient;
PubSubClient client(wifiClient);
int status = WL_IDLE_STATUS;
void setup()
{
Serial.begin(9600);
delay(10);
pinMode(LDR, INPUT);
Serial.print(" Connect to : ");
Serial.println(ssid);
WiFi.begin(ssid, password, 6);
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.telkomiot.id", 1883);
}
void loop()
{
if ( !client.connected() )
{
reconnect();
}
getData();
delay(5000);
}
void getData()
{
int analogValue = analogRead(LDR);
float voltage = analogValue / 4095. * 5;
float resistance = 2000 * voltage / (1 - voltage / 5);
float lux = pow(RL10 * 1e3 * pow(10, GAMMA) / resistance, (1 / GAMMA));
Serial.println(lux);
String payload = "{";
payload += "\"intensitas_cahaya\":";payload += lux;
payload += "}";
char telemetry[1000];
payload.toCharArray( telemetry, 1000 );
client.publish("v2.0/subs/APP6659cf125317f26883/DEV6659cf3d0616223552", telemetry);
Serial.println( telemetry );
// mqtt://mqtt.telkomiot.id/v2.0/subs/APP6659c41b9794262928/DEV6659c454bbc6526032
}
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 server node ...");
if ( client.connect("DEV6659cf3d0616223552", "18fced22c305117f", "18fced22c30b6d0a")) {
Serial.println( "[DONE]" );
} else {
Serial.print( "[FAILED] [ rc = " );
Serial.println( " : retrying in 5 seconds]" );
delay( 1000 );
}
}
}