diff --git a/things.ino b/things.ino index 3963d30..c37bd37 100644 --- a/things.ino +++ b/things.ino @@ -70,6 +70,14 @@ bool isEqual(float a, float b, float epsilon=0.001) { return fabs(a - b) <= epsilon * fabs(a); } +char* topic(const char* this_topic) { + static char topic[34]; + strcpy(topic, mqtt_topic); + strcat(topic, "/"); + strcat(topic, this_topic); + return topic; +} + void read_sensor() { // wait at least 2 seconds seconds between measurements unsigned long currentMillis = millis(); @@ -96,21 +104,14 @@ void read_sensor() { dtostrf(temperature, 1, 2, str_temperature); dtostrf(heatindex, 1, 2, str_heatindex); - char pub_topic[34]; if (!isEqual(humidity, previousHumidity)) { - strcpy(pub_topic,mqtt_topic); - strcat(pub_topic,"/humidity"); - client.publish(pub_topic, str_humidity); + client.publish(topic("humidity"), str_humidity); } if (!isEqual(temperature, previousTemperature)) { - strcpy(pub_topic,mqtt_topic); - strcat(pub_topic,"/temperature"); - client.publish(pub_topic, str_temperature); + client.publish(topic("temperature"), str_temperature); } if (!isEqual(heatindex, previousHeatindex)) { - strcpy(pub_topic,mqtt_topic); - strcat(pub_topic,"/heatindex"); - client.publish(pub_topic, str_heatindex); + client.publish(topic("heatindex"), str_heatindex); } Serial.print("Humidity: "); @@ -151,13 +152,10 @@ void reconnect() { while (!client.connected()) { Serial.print("Attempting MQTT connection..."); // Attempt to connect - char pub_topic[34]; - strcpy(pub_topic,mqtt_topic); - strcat(pub_topic,"/online"); - if (client.connect(wifi_station_get_hostname(), pub_topic, MQTTQOS1, true, "0")) { + if (client.connect(wifi_station_get_hostname(), topic("online"), MQTTQOS1, true, "0")) { Serial.println("connected"); // Once connected, publish an announcement... - client.publish(pub_topic, "1"); + client.publish(topic("online"), "1"); // ... and resubscribe: client.subscribe("inTopic"); } else { @@ -300,16 +298,9 @@ void setup() { // Initial read read_sensor(); - char pub_topic[34]; - strcpy(pub_topic,mqtt_topic); - strcat(pub_topic,"/humidity"); - client.publish(pub_topic, str_humidity); - strcpy(pub_topic,mqtt_topic); - strcat(pub_topic,"/temperature"); - client.publish(pub_topic, str_temperature); - strcpy(pub_topic,mqtt_topic); - strcat(pub_topic,"/heatindex"); - client.publish(pub_topic, str_heatindex); + client.publish(topic("humidity"), str_humidity); + client.publish(topic("temperature"), str_temperature); + client.publish(topic("heatindex"), str_heatindex); // Handle http requests server.on("/", [](){