mqtt.ino 1.71 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"); */
  Serial.println("mqttSubscribe");
  mqttClient.subscribe(PREAMBLE T_FILL TS_DURATION,1);
  mqttClient.subscribe(PREAMBLE T_ROTATE TS_DURATION ,1);
  mqttClient.subscribe(PREAMBLE T_FERTILIZE TS_DURATION ,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) {
  Serial.println("mqttData");
  String dataStr(data);
  Serial.println(topic);
  Serial.println(PREAMBLE T_FILL TS_DURATION);
  if (topic == PREAMBLE T_FILL TS_DURATION) {
    Serial.println("rotate duration");
    enqueue(C_FILL_DURATION, time(NULL), stringToLong(dataStr));
  }
  if (topic == PREAMBLE T_ROTATE TS_DURATION) {
    enqueue(C_ROTATE_DURATION, time(NULL), stringToLong(dataStr));
  }
  if (topic == PREAMBLE T_FERTILIZE TS_DURATION) {
    enqueue(C_FERTILIZE_DURATION, time(NULL), stringToLong(dataStr));
  }

  /* if (topic == PREAMBLE  T_PUMPLEVEL) { */
  /*   enqueue("pumplevel", time(NULL), stringToLong(dataStr)); */
  /* } */
  /* if (topic == PREAMBLE  T_PUMPABORT) { */
  /*   enqueue("pumpabort", 0, 0); */
  /* } */
}