DRY - don't repeat yourself

This commit is contained in:
simonox 2023-02-20 16:15:49 +01:00
parent ce07ae0466
commit f2ca4b2d40
2 changed files with 17 additions and 9 deletions

View file

@ -4,6 +4,8 @@ Required libraries (Tools -> manage libraries)
- PubSubClient@2.8.0 - PubSubClient@2.8.0
- Wifi - Wifi
*/ */
#include <stdlib.h>
#include <string.h>
#include "EmonLib.h" #include "EmonLib.h"
#include <WiFi.h> #include <WiFi.h>
#include <PubSubClient.h> #include <PubSubClient.h>
@ -19,6 +21,7 @@ const char* ssid = secrect_ssid;
const char* password = secret_password; const char* password = secret_password;
const char* mqttServer = mqtt_server; const char* mqttServer = mqtt_server;
const int mqttPort = mqtt_port; const int mqttPort = mqtt_port;
const char* mqttPrefix = mqtt_prefix;
// wifi and MQTT // wifi and MQTT
WiFiClient wifiClient; WiFiClient wifiClient;
@ -67,7 +70,7 @@ void reconnect() {
if (client.connect(clientId.c_str())) { if (client.connect(clientId.c_str())) {
Serial.println("connected"); Serial.println("connected");
//Once connected, publish an announcement... //Once connected, publish an announcement...
client.publish("/iot-platform/engergy-montitor/test-device/status", "online"); client.publish(concat(mqttPrefix, "/status"), "online");
// ... and resubscribe // ... and resubscribe
} else { } else {
Serial.print("failed, rc="); Serial.print("failed, rc=");
@ -79,31 +82,35 @@ void reconnect() {
} }
} }
char* concat(const char* str1, const char* str2) {
char* result;
asprintf(&result, "%s%s", str1, str2);
return result;
}
void loop() { void loop() {
// get values
double irms = emon1.calcIrms(1480); double irms = emon1.calcIrms(1480);
double power = irms * voltage; double power = irms * voltage;
// debug, print out on serial // debug, print out on serial
Serial.print(power); Serial.print(power);
Serial.print(" Watt - "); Serial.print(" Watt - ");
Serial.print(irms); Serial.print(irms);
Serial.println(" Ampere"); Serial.println(" Ampere");
// convert double to char array for MQTT // convert double to char array for MQTT
char powerArray[10]; char powerArray[10];
snprintf(powerArray, 10, "%f", power); snprintf(powerArray, 10, "%f", power);
char irmsArray[10]; char irmsArray[10];
snprintf(irmsArray, 10, "%f", irms); snprintf(irmsArray, 10, "%f", irms);
printf("%s", irmsArray);
// publish values // publish values
client.publish("/iot-platform/engergy-montitor/test-device/watt", powerArray); client.publish(concat(mqttPrefix, "/watt"), powerArray);
client.publish("/iot-platform/engergy-montitor/test-device/ampere", irmsArray); client.publish(concat(mqttPrefix, "/ampere"), irmsArray);
// wait a second // wait a second
delay(1000); delay(1000);
} }

View file

@ -3,3 +3,4 @@
#define secret_password "guestguest" #define secret_password "guestguest"
#define mqtt_server "192.168.2.103" #define mqtt_server "192.168.2.103"
#define mqtt_port 1883 #define mqtt_port 1883
#define mqtt_prefix "/iot-platform/engergy-montitor/test-device"