/* * Connects to a WiFi network and MQTT broker, then publishes WiFi signal strength readings */ #include <WiFi.h> #include <PubSubClient.h> const char* ssid = "your-ssid"; const char* password = "your-password"; const char* mqtt_server = "your_broker_ip"; WiFiClient wifiClient; PubSubClient mqttClient(wifiClient); long lastMsg = 0; void setup() { Serial.begin(115200); delay(10); // We start by connecting to a WiFi network Serial.println(); Serial.print("Connecting to "); Serial.println(ssid); WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } Serial.println(""); Serial.println("WiFi connected"); Serial.println("IP address: "); Serial.println(WiFi.localIP()); // Set up MQTT mqttClient.setServer(mqtt_server, 1883); } void reconnect() { // Loop until we're reconnected while (!mqttClient.connected()) { Serial.print("Attempting MQTT connection..."); // Create a random client ID String clientId = "ESP32Client-"; clientId += String(random(0xffff), HEX); // Attempt to connect if (mqttClient.connect(clientId.c_str())) { Serial.println("Connected"); // Connected - do something useful - subscribe to topics, publish messages, etc. } else { Serial.print("failed, rc="); Serial.print(mqttClient.state()); Serial.println(" try again in 5 seconds"); // Wait 5 seconds before retrying delay(5000); } } } int rssiVal = 0; void loop() { if (!mqttClient.connected()) { reconnect(); } mqttClient.loop(); // Read a value long now = millis(); if (now - lastMsg > 100) { lastMsg = now; rssiVal = WiFi.RSSI(); // wifi signal strength mqttClient.publish("foo", String(rssiVal).c_str()); Serial.println(rssiVal); } }