Spacestatus-Button/Spacestatus-Taster.ino

89 lines
2.2 KiB
C++

#include <Bounce2.h>
#include <Adafruit_NeoPixel.h>
#include <ESP8266WiFi.h>
#include <MQTTPubSubClient.h>
#include "Credentials.h"
#define BUTTON_PIN D7 // Button at D8 / GPIO-15
#define LED_PIN D2 // WS2812b at D2 / GPIO-4
#define NUMPIXELS 1
#define CLOSE 0
#define OPEN 1
#define NA 2
Adafruit_NeoPixel pixel = Adafruit_NeoPixel(NUMPIXELS, LED_PIN, NEO_GRB + NEO_KHZ800);
Bounce button = Bounce(); // Instantiate a Bounce object
WiFiClient client;
MQTTPubSubClient mqtt;
int currentState;
char* ssid = SSID;
char* pass = PASSWD;
char* mqttHost = MQTT_HOST;
void setup() {
Serial.begin(115200);
Serial.print("\n\nSetup starting...\n");
pixel.begin();
button.attach(BUTTON_PIN, INPUT_PULLUP); // Attach the debouncer to a pin with INPUT_PULLUP mode
button.interval(25); // Use a debounce interval of 25 milliseconds
currentState=NA;
pixel.setPixelColor(0, pixel.Color(0,0,LED_BRIGHTNESS)); pixel.show();
Serial.print("Connecting to wifi...");
WiFi.begin(ssid, pass);
while (WiFi.status() != WL_CONNECTED) {
Serial.print("."); delay(100);
}
Serial.println(" Wifi connected!");
Serial.print("Connecting to MQTT-Broker - Host connection...");
while (!client.connect(MQTT_HOST, 1883)) {
Serial.print("."); delay(100);
}
Serial.println(" MQTT-Host connected!");
// initialize mqtt client
mqtt.begin(client);
Serial.print("Connecting to MQTT-Broker - MQTT...");
while (!mqtt.connect("arduino", "public", "public")) {
Serial.print("."); delay(100);
}
Serial.println(" MQTT fully connected!");
Serial.print("\nSetup done.\n");
}
void openSpace() {
currentState=OPEN;
Serial.println("Space is now open");
pixel.setPixelColor(0, pixel.Color(0,LED_BRIGHTNESS,0)); pixel.show();
mqtt.publish(MQTT_TOPIC, "OPEN");
}
void closeSpace() {
currentState=CLOSE;
Serial.println("Space is now closed");
pixel.setPixelColor(0, pixel.Color(LED_BRIGHTNESS,0,0)); pixel.show();
mqtt.publish("UHB/Door", "CLOSE");
}
void loop() {
button.update(); // Update the Bounce instance
if ( button.fell() ) { // Call code if button transitions from HIGH to LOW
switch(currentState) {
case NA:
case CLOSE: openSpace(); break;
case OPEN: closeSpace(); break;
}
}
}