#include <WiFi.h>
#include <PubSubClient.h>
// WiFi credentials
const char* ssid = "Wokwi-GUEST";
const char* password = "";
// MQTT broker
const char* mqtt_server = "broker.hivemq.com";
const char* topic = "wokwi/coal-weight-sensor";
// WiFi and MQTT client objects
WiFiClient espClient;
PubSubClient client(espClient);
float baseWeight = 5000.0; // Base weight of coal in kg
long lastMsg = 0;
void setup_wifi() {
delay(10);
Serial.println("Connecting to Wi-Fi...");
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("Wi-Fi connected!");
}
void reconnect() {
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
if (client.connect("ESP32Client")) {
Serial.println("Connected to MQTT broker!");
} else {
Serial.print("Failed, rc=");
Serial.print(client.state());
Serial.println(" trying again in 5 seconds");
delay(5000);
}
}
}
void setup() {
Serial.begin(115200);
setup_wifi();
client.setServer(mqtt_server, 1883);
Serial.println("Weight simulation ready!");
}
float generateWeight() {
// Simulate normal weight fluctuation
float weight = baseWeight + random(-5, 5);
// Introduce occasional significant drops to simulate theft
if (random(100) < 5) { // 5% chance of theft event
weight -= random(50, 200); // Simulate a drop
Serial.println("Warning: Sudden drop detected!");
}
return weight;
}
void loop() {
if (!client.connected()) {
reconnect();
}
client.loop();
// Generate and publish simulated weight data
float weight = generateWeight();
Serial.print("Simulated Weight: ");
Serial.println(weight);
// Publish weight to MQTT
String weightStr = String(weight);
client.publish(topic, weightStr.c_str());
delay(1000); // Delay between readings
}