#include <WiFi.h>
#include <PubSubClient.h>
#define GLUCOSE_SENSOR_PIN 34 // Analog pin for glucose sensor
// WiFi credentials
const char* ssid = "Wokwi-GUEST";
const char* password = "";
// HiveMQ Cloud MQTT Broker details (secure connection)
const char* mqtt_server = "9ac40e0208a5481d9b58a4b8aad9004e.s1.eu.hivemq.cloud";
const int mqtt_port = 8883;
const char* topic = "iot/glucose";
// HiveMQ Cloud credentials
const char* mqtt_username = "hivemq.webclient.1744651559796";
const char* mqtt_password = "WA!&rhH2Pa%Z.f09T7dy";
WiFiClient espClient; // Insecure WiFi client
PubSubClient client(espClient); // MQTT client using the insecure client
// Connect to WiFi
void setup_wifi() {
delay(10);
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("\nWiFi connected");
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
}
// Callback for receiving MQTT messages (if subscribed)
void callback(char* topic, byte* payload, unsigned int length) {
Serial.print("Message arrived [");
Serial.print(topic);
Serial.print("] ");
for (unsigned int i = 0; i < length; i++) {
Serial.print((char)payload[i]);
}
Serial.println();
}
// Reconnect to MQTT broker if connection is lost
void reconnect() {
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
String clientId = "ESP32Client-";
clientId += String(random(0xffff), HEX);
// Attempt to connect using the provided MQTT credentials (if any)
if (client.connect(clientId.c_str(), mqtt_username, mqtt_password)) {
Serial.println(" connected");
// Resubscribe to topic(s) if needed
client.subscribe(topic);
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 3 seconds");
delay(3000);
}
}
}
void setup() {
Serial.begin(115200);
setup_wifi();
client.setServer(mqtt_server, mqtt_port);
client.setCallback(callback);
}
void loop() {
if (!client.connected()) {
reconnect();
}
client.loop();
// Simulate reading the glucose sensor and create JSON payload
int glucoseLevel = analogRead(GLUCOSE_SENSOR_PIN);
String payload = "{\"glucoseLevel\": " + String(glucoseLevel) + "}";
// Publish the JSON payload to the MQTT topic
client.publish(topic, payload.c_str());
Serial.print("Published: ");
Serial.println(payload);
delay(2000); // Wait 2 seconds between readings
}