/** * @file debugMqtt.cpp * @author Alexander Klein (alex@kleiax.de) * @brief Implemention of the class debugMqtt.h * @see debugMqtt.h * @version 0.1 * @date 2021-12-13 * * @copyright Copyright (c) 2021 * */ #include "debugMqtt.h" PubSubClient *DebugMqtt::client; Loglevel DebugMqtt::loglevel; bool DebugMqtt::isInit = false; char DebugMqtt::msg[MQTT_BUFFER_SIZE]; char DebugMqtt::topic[MQTT_BUFFER_SIZE]; DebugMqtt::DebugMqtt(const char *name, uint8_t bufSize) : name{name} { if (bufSize != 0) { this->bufSize = bufSize; } this->buf = new char[this->bufSize]; } DebugMqtt::~DebugMqtt() { delete this->buf; } void DebugMqtt::sendMsg(Loglevel loglevel, String topic, String msg) { snprintf(static_cast(DebugMqtt::msg), MQTT_BUFFER_SIZE, static_cast("%s: %s"), this->name, msg.c_str()); this->sendData(loglevel, topic, static_cast(DebugMqtt::msg)); } void DebugMqtt::sendMsg(Loglevel loglevel, String msg) { this->sendMsg(loglevel, "", msg); } void DebugMqtt::sendData(Loglevel loglevel, String topic, String data) { if (!DebugMqtt::isInit) { return; } if (loglevel <= DebugMqtt::loglevel && loglevel > Loglevel::none) { snprintf(static_cast(DebugMqtt::topic), MQTT_BUFFER_SIZE, static_cast("%s%s"), DebugMqtt::enum_to_string(loglevel).c_str(), topic.c_str()); snprintf(static_cast(DebugMqtt::msg), MQTT_BUFFER_SIZE, static_cast("%s"), data.c_str()); client->publish(DebugMqtt::topic, static_cast(DebugMqtt::msg)); } } void DebugMqtt::sendData(Loglevel loglevel, String data) { DebugMqtt::sendData(loglevel, "", data); } void DebugMqtt::writeToInflux(String measurement_name, String field_set, float measurement, uint64_t nanos) { // Example String: "weather temperature=82 1465839830100400200"; snprintf(static_cast(DebugMqtt::msg), MQTT_BUFFER_SIZE, static_cast("%s %s=%f %llu"), measurement_name.c_str(), field_set.c_str(), measurement, nanos); this->sendData(Loglevel::influx, static_cast(DebugMqtt::msg)); } void DebugMqtt::addCharacter(char character) { this->buf[this->bufPos] = character; this->bufPos++; if (character == '\n' || this->bufPos >= this->bufSize - 1) { this->buf[this->bufPos - 1] = '\0'; this->sendMsg(Loglevel::info, buf); this->bufPos = 0; } } void DebugMqtt::init(PubSubClient *client, Loglevel max_loglevel) { DebugMqtt::client = client; DebugMqtt::loglevel = max_loglevel; DebugMqtt::isInit = true; } void DebugMqtt::changeLoglevel(Loglevel loglevel) { DebugMqtt::loglevel = loglevel; } String DebugMqtt::enum_to_string(Loglevel loglevel) { String topic = ""; topic += MQTT_DEBUG_TOPIC; switch (loglevel) { case Loglevel::error: topic += "/Error"; break; case Loglevel::warn: topic += "/Warn"; break; case Loglevel::info: topic += "/Info"; break; case Loglevel::debug: topic += "/Debug"; break; case Loglevel::influx: topic += "/Influx"; break; default: topic += "/NoLoglovel"; break; } return topic; }