|
| 1 | +#include "MqttManager.h" |
| 2 | +#include <ArduinoLog.h> |
| 3 | + |
| 4 | +extern void onMqttMessage(int messageSize); |
| 5 | + |
| 6 | +int MqttManager::initialise() |
| 7 | +{ |
| 8 | + if (!_p_mqttClient->connect(_serverIP.c_str(), _port)) { |
| 9 | + Log.error(F("Mqtt connection failed - error code %d"), _p_mqttClient->connectError()); |
| 10 | + return _p_mqttClient->connectError(); |
| 11 | + } |
| 12 | + _p_mqttClient->setId(_clientID); |
| 13 | + |
| 14 | + // set message handler for callback |
| 15 | + _p_mqttClient->onMessage(::onMqttMessage); |
| 16 | + |
| 17 | + // subscribe to config topic |
| 18 | + _p_mqttClient->subscribe(topicConfig); |
| 19 | + |
| 20 | + return 0; |
| 21 | +} |
| 22 | + |
| 23 | +void MqttManager::publish(RackState_t& rs) { |
| 24 | + |
| 25 | + if (!_p_mqttClient->connected()) { |
| 26 | + Log.error(F("Mqtt connection lost ... attempting reconnection")); |
| 27 | + initialise(); |
| 28 | + } |
| 29 | + |
| 30 | + Log.notice(F("Publishing temperature events")); |
| 31 | + sendMessage(topicTempRackTop, String(rs.thermos["topRack"].tempCelsuis)); |
| 32 | + sendMessage(topicTempRackBase, String(rs.thermos["baseRack"].tempCelsuis)); |
| 33 | + sendMessage(topicTempRackAve, String(rs.aveTempCelsius)); |
| 34 | + |
| 35 | + //Log.notice(F("Publishing fan events")); |
| 36 | + /* |
| 37 | + sendMessage(topicFanBaseLeft + subtopicFanRPM, String(rs.fanTopLeft.rpm)); |
| 38 | + sendMessage(topicFanTopRight + subtopicFanRPM, String(rs.fanTopRight.rpm)); |
| 39 | + sendMessage(topicFanBaseLeft + subtopicFanRPM, String(rs.fanBaseLeft.rpm)); |
| 40 | + sendMessage(topicFanTopRight + subtopicFanRPM, String(rs.fanBaseRight.rpm)); |
| 41 | + */ |
| 42 | + |
| 43 | + // if (rs.hasFanError()) { |
| 44 | + // for each fan in error |
| 45 | + // sendMessage(topicRackFanError, rs.fanid) |
| 46 | + //} |
| 47 | + |
| 48 | +} |
| 49 | + |
| 50 | +void MqttManager::poll() { |
| 51 | + _p_mqttClient->poll(); |
| 52 | +} |
| 53 | + |
| 54 | +void MqttManager::sendMessage(const String& topic, const String& msg) |
| 55 | +{ |
| 56 | + _p_mqttClient->beginMessage(topic); |
| 57 | + _p_mqttClient->print(msg); |
| 58 | + if (!_p_mqttClient->endMessage()) |
| 59 | + Log.error(F("Failed to send message to topic %s"), topic.c_str()); |
| 60 | +} |
| 61 | + |
| 62 | +/** |
| 63 | + * From Print.h |
| 64 | + * Enables writing all log events to the topicRackLog |
| 65 | + */ |
| 66 | +size_t MqttManager::write(uint8_t c) { |
| 67 | + Serial.print(char(c)); |
| 68 | + _buf += (char)c; |
| 69 | + if (c == '\n') { |
| 70 | + if (_p_mqttClient->connected()) { |
| 71 | + _p_mqttClient->beginMessage(topicRackLog); |
| 72 | + _p_mqttClient->print(_buf); |
| 73 | + _p_mqttClient->endMessage(); |
| 74 | + } |
| 75 | + _buf = ""; |
| 76 | + } |
| 77 | + return 1; |
| 78 | +}; |
0 commit comments