More refactoring

This commit is contained in:
DTTerastar 2021-08-23 15:21:58 -04:00
parent b8625588cd
commit 56d3c93d05
4 changed files with 33 additions and 30 deletions

View File

@ -24,8 +24,8 @@ binary_sensor:
# One entry per sensor node to understand when the device is online/offline and see device metadata such as IP address and settings values
- platform: mqtt
name: ESP32 A
state_topic: "espresense/esp32_a/telemetry/availability"
json_attributes_topic: "espresense/esp32_a/telemetry
state_topic: "espresense/rooms/esp32_a/status"
json_attributes_topic: "espresense/rooms/esp32_a/telemetry"
payload_on: "online"
payload_off: "offline"
device_class: connectivity

View File

@ -46,7 +46,7 @@ Stopping wifi reconnect timer
If your device won't connect to your wireless network, copy and paste any logs you see into your issue.
### ESP32 MQTT (yellow arrow)
To report devices, the ESP32 must be connected to your MQTT server. It will attempt to connect once it has established a connection to your wireless network. Once connected, the device will publish a status message ("CONNECTED") to the `availabilityTopic` as defined in your settings. It also publishes your configuration information to the `telemetryTopic` which consists of:
To report devices, the ESP32 must be connected to your MQTT server. It will attempt to connect once it has established a connection to your wireless network. Once connected, the device will publish a status message ("CONNECTED") to the `statusTopic` as defined in your settings. It also publishes your configuration information to the `telemetryTopic` which consists of:
* **room**: the configured room name
* **ip**: the assigned IP address of the device
* **hostname**: the host name, used for WiFi as well as client ID for MQTT (must be unique on your network)
@ -58,7 +58,7 @@ To report devices, the ESP32 must be connected to your MQTT server. It will atte
![Home Assistant telemetry](./images/home_assistant_telemetry.jpg)
If you do not see any information being published to either the `availabilityTopic` or `telemetryTopic` then you will want to connect to the serial monitor and check the logs. Verify that your MQTT user name and password is correct, and check the logs on your MQTT server itself. You should see it reporting a new client connected from the ESP32's IP address:
If you do not see any information being published to either the `statusTopic` or `telemetryTopic` then you will want to connect to the serial monitor and check the logs. Verify that your MQTT user name and password is correct, and check the logs on your MQTT server itself. You should see it reporting a new client connected from the ESP32's IP address:
```
New client connected from 192.168.1.104 as esp32_d (c1, k60, u'my_mqtt_username').
```

View File

@ -34,17 +34,17 @@ BleFingerprint *getFingerprint(BLEAdvertisedDevice *advertisedDevice)
bool sendTelemetry(int totalSeen = -1, int totalReported = -1, int totalAdverts = -1)
{
if (initial)
if (!online)
{
initial = false;
if (mqttClient.publish(availabilityTopic.c_str(), 0, 1, "online") == true)
if (mqttClient.publish(statusTopic.c_str(), 0, 1, "online"))
{
online = true;
Display.status("Connected to MQTT");
reconnectTries = 0;
}
else
{
Serial.println(F("Error sending availability"));
log_e("Error sending status=online");
}
}
@ -65,8 +65,8 @@ bool sendTelemetry(int totalSeen = -1, int totalReported = -1, int totalAdverts
tele["reported"] = totalReported;
if (totalAdverts > 0)
tele["adverts"] = totalAdverts;
if (sendFailures > 0)
tele["sendFails"] = sendFailures;
if (teleFails > 0)
tele["teleFails"] = teleFails;
if (reconnectTries > 0)
tele["reconnectTries"] = reconnectTries;
@ -79,17 +79,15 @@ bool sendTelemetry(int totalSeen = -1, int totalReported = -1, int totalAdverts
char teleMessageBuffer[512];
serializeJson(tele, teleMessageBuffer);
String teleTopic = CHANNEL + "/" + room + "/telemetry";
for (int i = 0; i < 10; i++)
{
if (mqttClient.publish(teleTopic.c_str(), 0, 0, teleMessageBuffer) == true)
if (!publishTele || mqttClient.publish(teleTopic.c_str(), 0, 0, teleMessageBuffer))
return true;
delay(20);
delay(50);
}
sendFailures++;
log_e("Error sending telemetry");
teleFails++;
Serial.printf("Error after 10 tries sending telemetry (%d times since boot)\n", teleFails);
return false;
}
@ -138,24 +136,25 @@ void connectToWifi()
Serial.println(room);
localIp = WiFi.localIP().toString();
roomsTopic = CHANNEL + "/rooms/" + room;
statusTopic = roomsTopic + "/status";
teleTopic = roomsTopic + "/telemetry";
}
void onMqttConnect(bool sessionPresent)
{
xTimerStop(reconnectTimer, 0);
initial = true;
}
void onMqttDisconnect(AsyncMqttClientDisconnectReason reason)
{
Serial.printf("Disconnected from MQTT; reason %d\n", (int)reason);
log_e("Disconnected from MQTT; reason %d\n", reason);
xTimerStart(reconnectTimer, 0);
online = false;
}
void reconnect(TimerHandle_t xTimer)
{
Serial.println("Reconnecting...");
if (updateInProgress) return;
if (WiFi.isConnected() && mqttClient.connected()) return;
@ -166,21 +165,24 @@ void reconnect(TimerHandle_t xTimer)
}
if (!WiFi.isConnected())
{
Serial.println("Reconnecting to WiFi...");
if (!WiFiSettings.connect(true, 60))
ESP.restart();
}
Serial.println("Reconnecting to MQTT...");
mqttClient.connect();
}
void connectToMqtt()
{
availabilityTopic = CHANNEL + "/" + room + "/telemetry/availability";
reconnectTimer = xTimerCreate("reconnectionTimer", pdMS_TO_TICKS(3000), pdTRUE, (void *)0, reconnect);
Serial.printf("Connecting to MQTT %s %d\n", mqttHost.c_str(), mqttPort);
mqttClient.onConnect(onMqttConnect);
mqttClient.onDisconnect(onMqttDisconnect);
mqttClient.setServer(mqttHost.c_str(), mqttPort);
mqttClient.setWill(availabilityTopic.c_str(), 0, 1, "offline");
mqttClient.setWill(statusTopic.c_str(), 0, 1, "offline");
mqttClient.setCredentials(mqttUser.c_str(), mqttPass.c_str());
mqttClient.connect();
}
@ -214,8 +216,7 @@ bool reportDevice(BleFingerprint *f)
char JSONmessageBuffer[512];
serializeJson(doc, JSONmessageBuffer);
String publishTopic = CHANNEL + "/" + room;
String publishTopic2 = CHANNEL + "/devices/" + f->getId() + "/" + room;
String devicesTopic = CHANNEL + "/devices/" + f->getId() + "/" + room;
bool p1 = false, p2 = false;
for (int i = 0; i < 10; i++)
@ -223,17 +224,17 @@ bool reportDevice(BleFingerprint *f)
if (!mqttClient.connected())
return false;
if (!p1 && mqttClient.publish((char *)publishTopic.c_str(), 0, 0, JSONmessageBuffer))
if (!p1 && (!publishRooms || mqttClient.publish((char *)roomsTopic.c_str(), 0, 0, JSONmessageBuffer)))
p1 = true;
if (!p2 && mqttClient.publish((char *)publishTopic2.c_str(), 0, 0, JSONmessageBuffer))
if (!p2 && (!publishDevices || mqttClient.publish((char *)devicesTopic.c_str(), 0, 0, JSONmessageBuffer)))
p2 = true;
if (p1 && p2)
return true;
delay(20);
}
sendFailures++;
teleFails++;
return false;
}

View File

@ -29,18 +29,20 @@ TaskHandle_t scannerTask;
bool updateInProgress = false;
String localIp;
int reconnectTries = 0;
int sendFailures = 0;
int teleFails = 0;
String mqttHost;
int mqttPort;
String mqttUser;
String mqttPass;
String room;
String availabilityTopic;
String statusTopic;
String teleTopic;
String roomsTopic;
bool publishTele;
bool publishRooms;
bool publishDevices;
bool initial = true; // First contact with mqtt
bool online; // Have we successfully sent status=online
static SemaphoreHandle_t fingerprintSemaphore;
static std::list<BleFingerprint *> fingerprints;