WifiRelay/productionMode.cpp
2018-07-11 07:52:09 +02:00

147 lines
2.9 KiB
C++

/*
* production.cpp
*
* Created on: Aug 20, 2017
* Author: wn
*/
#include "defines.h"
#define MQTT_MAX_PACKET_SIZE 256
#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>
#include <PubSubClient.h>
#include "configuration.h"
void callback(char* topic, byte* payload, unsigned int length);
WiFiClientSecure espClient;
PubSubClient client(espClient);
void setup_wifi() {
delay(10);
WiFi.mode(WIFI_STA);
// We start by connecting to a WiFi network
#ifdef DEBUG
Serial.println();
Serial.print("Connecting to ");
Serial.println(configBlock.wifiSsid);
#endif
WiFi.begin(configBlock.wifiSsid, configBlock.wifiKey);
while (WiFi.status() != WL_CONNECTED) {
delay(50);
#ifdef DEBUG
Serial.print(".");
#endif
}
#ifdef DEBUG
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
#endif
}
void setupProduction() {
setup_wifi();
client.setServer(configBlock.mqttBroker, configBlock.mqttPort);
pinMode(LIGHT_PIN, OUTPUT);
}
void callback(char* topic, byte* payload, unsigned int length) {
const uint8_t BUFSIZE = 128;
if ((length + 1) >= BUFSIZE) { // 1 for terminating NUL
#ifdef DEBUG
Serial.println("Received message too long, ignore it");
#endif
} else {
char buffer[BUFSIZE];
memcpy(buffer, payload, length);
*(buffer + length) = 0;
#ifdef DEBUG
Serial.print("Received message: ");
Serial.print(length);
Serial.print(" ");
Serial.print(topic);
Serial.print(" ");
Serial.println(buffer);
#endif
if (! strcmp(topic, configBlock.mqttTopic)) {
if (! strcmp(buffer, "ON")) {
digitalWrite(LIGHT_PIN, HIGH);
} else {
digitalWrite(LIGHT_PIN, LOW);
}
}
}
}
void reconnect() {
// Loop until we're reconnected
while (!client.connected()) {
#ifdef DEBUG
Serial.print("Attempting MQTT connection...");
#endif
// Attempt to connect
//char clientId[128];
//snprintf(clientId, 127, "esp%s", WiFi.macAddress().c_str());
if (client.connect(configBlock.mqttClientId, configBlock.mqttUser, configBlock.mqttPass)) {
#ifdef DEBUG
Serial.println("connected");
#endif
// Once connected, publish an announcement...
//client.publish("IoT/espThermometer/status", "hello world");
client.setCallback(callback);
client.subscribe(configBlock.mqttTopic);
client.publish(configBlock.mqttDebugTopic, "hello world");
client.publish(configBlock.mqttDebugTopic, WiFi.localIP().toString().c_str());
} else {
#ifdef DEBUG
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
#endif
// Wait 5 seconds before retrying
delay(5000);
}
}
}
void mqtt_connect() {
if (!client.connected()) {
reconnect();
}
client.loop();
}
void loopProduction() {
static uint32_t lastMillis = 0;
mqtt_connect();
}