display changed and mqtt stuff added

This commit is contained in:
Wolfgang Hottgenroth
2016-03-03 23:19:56 +01:00
parent 13124ac90b
commit c520e7731c
21 changed files with 1578 additions and 2060 deletions

109
mqttclient.cpp Normal file
View File

@ -0,0 +1,109 @@
/*
* mqttclient.cpp
*
* Created on: 03.03.2016
* Author: wn
*/
#include "mqttclient.h"
#include <Streaming.h>
#include <Ethernet.h>
#include <Metro.h>
#include <PubSubClient.h>
void callback(char* topic, byte* payload, unsigned int length);
static uint8_t MAC[] = { 0x90, 0xA2, 0xDA, 0x00, 0x51, 0x08 };
const static char BROKER[] = "192.168.75.1";
EthernetClient ethernetClient;
PubSubClient mqttClient = PubSubClient(BROKER, 1883, callback, ethernetClient);
uint8_t disconnectState = 0;
uint32_t disconnectTime = 0;
Metro minute = Metro(60000);
Metro second = Metro(1000);
uint32_t uptime;
void callback(char* topic, byte* payload, unsigned int length) {
const uint8_t BUFSIZE = 128;
if ((length + 1) >= BUFSIZE) { // 1 for terminating NUL
Serial << "Received message too long, ignore it" << endl;
} else {
char buffer[BUFSIZE];
memcpy(buffer, payload, length);
*(buffer + length) = 0;
Serial << "Received message: " << length << ", " << String(topic) << ", " << String(buffer) << endl;
}
}
void MqttClientNS::begin() {
Ethernet.begin(MAC);
Serial << "Got IP address: " << Ethernet.localIP() << endl;
disconnectState = 3;
disconnectTime = millis();
}
void MqttClientNS::exec() {
if (minute.check() == 1) {
byte r = Ethernet.maintain();
Serial << "Ethernet.maintain: " << r << endl;
if ((r == DHCP_CHECK_REBIND_FAIL) || (r == DHCP_CHECK_RENEW_FAIL)) {
}
}
if ((disconnectState == 0) && (! mqttClient.loop())) {
disconnectState = 1;
}
switch (disconnectState) {
case 0:
// Serial.println("discState 0");
// everything fine
break;
case 1:
Serial.println("discState 1");
mqttClient.disconnect();
disconnectTime = millis();
disconnectState = 2;
break;
case 2:
Serial.println("discState 3");
if (disconnectTime + 2000 < millis()) {
disconnectState = 3;
}
break;
case 3:
Serial.println("discState 3");
if (mqttClient.connect("Monitor")) {
mqttClient.subscribe("IoT/Message/Monitor");
mqttClient.subscribe("IoT/Alarm/Monitor");
disconnectTime = millis();
disconnectState = 0;
} else {
disconnectState = 1;
}
break;
default:
disconnectState = 0;
break;
}
if (second.check() == 1) {
uptime++;
Serial.println("mqtt tick");
if (disconnectState == 0) {
String msg = String("{ \"metadata\": { \"device\": \"Monitor\" }, \"data\": { \"uptime\": ") + uptime + String("}}");
mqttClient.publish("IoT/Heartbeat/Monitor", (char*)msg.c_str());
}
}
}