mqtt.ino 1.3 KB
#include "mqtt.h"

long stringToLong(String s) {
  char arr[12];
  s.toCharArray(arr, sizeof(arr));
  return atol(arr);
}

void setup_mqtt() {
  // setup callbacks
  mqttClient.onConnected(mqttConnected);
  mqttClient.onDisconnected(mqttDisconnected);
  mqttClient.onPublished(mqttPublished);
  mqttClient.onData(mqttData);
  // connect
  mqttClient.connect();
}

void mqttSubscribe() {
  /* mqttClient.subscribe("home/compost/pump"); */
  mqttClient.subscribe(PREAMBLE  T_PUMPDURATION,1);
  mqttClient.subscribe(PREAMBLE  T_PUMPLEVEL,1);
  mqttClient.subscribe(PREAMBLE  T_PUMPABORT,1);
  /* Serial.println("subscribed to" PREAMBLE  T_PUMPDURATION); */
}

void mqttPublished() {
  /* Serial.println("published cb"); */
}

void mqttConnected() {
  mqttSubscribe();
  Serial.println("connected");
}

void mqttDisconnected() {
  Serial.println("disconnected");
  delay(500);
  mqttClient.connect();
}

void mqttData(String& topic, String& data) {
  String dataStr(data);
  /* mqttClient.publish(PREAMBLE T_PUMPSTATE, dataStr ); */
  if (topic == PREAMBLE  T_PUMPDURATION) {
    insert("pumpduration", time(NULL), stringToLong(dataStr), 0);
  }
  if (topic == PREAMBLE  T_PUMPLEVEL) {
    insert("pumplevel", time(NULL), 1, stringToLong(dataStr));
  }
  if (topic == PREAMBLE  T_PUMPABORT) {
    insert("pumpabort", 0, 0, 0);
  }
}