Initial commit
This commit is contained in:
63
src/mqtt_client.cpp
Normal file
63
src/mqtt_client.cpp
Normal file
@@ -0,0 +1,63 @@
|
||||
#include "mqtt_client.h"
|
||||
#include <WiFi.h>
|
||||
#include <PubSubClient.h>
|
||||
#include "json_codec.h"
|
||||
|
||||
static WiFiClient wifi_client;
|
||||
static PubSubClient mqtt_client(wifi_client);
|
||||
static WifiMqttConfig g_cfg;
|
||||
static String g_client_id;
|
||||
|
||||
void mqtt_init(const WifiMqttConfig &config, const char *device_id) {
|
||||
g_cfg = config;
|
||||
mqtt_client.setServer(config.mqtt_host.c_str(), config.mqtt_port);
|
||||
if (device_id && device_id[0] != '\0') {
|
||||
g_client_id = String("dd3-bridge-") + device_id;
|
||||
} else {
|
||||
g_client_id = String("dd3-bridge-") + String(random(0xffff), HEX);
|
||||
}
|
||||
}
|
||||
|
||||
static bool mqtt_connect() {
|
||||
if (mqtt_client.connected()) {
|
||||
return true;
|
||||
}
|
||||
String client_id = g_client_id.length() > 0 ? g_client_id : String("dd3-bridge-") + String(random(0xffff), HEX);
|
||||
if (g_cfg.mqtt_user.length() > 0) {
|
||||
return mqtt_client.connect(client_id.c_str(), g_cfg.mqtt_user.c_str(), g_cfg.mqtt_pass.c_str());
|
||||
}
|
||||
return mqtt_client.connect(client_id.c_str());
|
||||
}
|
||||
|
||||
void mqtt_loop() {
|
||||
if (!mqtt_connect()) {
|
||||
return;
|
||||
}
|
||||
mqtt_client.loop();
|
||||
}
|
||||
|
||||
bool mqtt_is_connected() {
|
||||
return mqtt_client.connected();
|
||||
}
|
||||
|
||||
bool mqtt_publish_state(const MeterData &data) {
|
||||
if (!mqtt_connect()) {
|
||||
return false;
|
||||
}
|
||||
String payload;
|
||||
if (!meterDataToJson(data, payload)) {
|
||||
return false;
|
||||
}
|
||||
String topic = String("smartmeter/") + data.device_id + "/state";
|
||||
return mqtt_client.publish(topic.c_str(), payload.c_str());
|
||||
}
|
||||
|
||||
#ifdef ENABLE_TEST_MODE
|
||||
bool mqtt_publish_test(const char *device_id, const String &payload) {
|
||||
if (!mqtt_connect()) {
|
||||
return false;
|
||||
}
|
||||
String topic = String("smartmeter/") + device_id + "/test";
|
||||
return mqtt_client.publish(topic.c_str(), payload.c_str());
|
||||
}
|
||||
#endif
|
||||
Reference in New Issue
Block a user