77 lines
1.7 KiB
C++
77 lines
1.7 KiB
C++
#include <Arduino.h>
|
|
#include <PubSubClient.h>
|
|
|
|
#include "button.h"
|
|
#include "relay.h"
|
|
#include "wireless.h"
|
|
|
|
const char *name = "LivingRoom";
|
|
const char *ssid = "JackHome";
|
|
const char *wpa2 = "JackHomeIOT";
|
|
|
|
lightswitch::Button button(5);
|
|
lightswitch::Relay relay(15);
|
|
lightswitch::Wireless wireless(ssid, wpa2);
|
|
|
|
WiFiClient wifi_client;
|
|
IPAddress mqtt_broker(192,168,4,1);
|
|
PubSubClient mqtt_client(mqtt_broker, 1883, wifi_client);
|
|
|
|
void IRAM_ATTR ButtonCallback()
|
|
{
|
|
button.pressed_ = true;
|
|
}
|
|
|
|
void MQTTCallback(char *topic, byte *payload, unsigned int length)
|
|
{
|
|
// This is hacky and just for debug purposes at the moment.
|
|
if (length == 1 && !strcmp(topic, "lights/LivingRoom/1"))
|
|
{
|
|
if (payload[0] == '0')
|
|
{
|
|
relay.Off();
|
|
}
|
|
else if (payload[0] == '1')
|
|
{
|
|
relay.On();
|
|
}
|
|
}
|
|
}
|
|
|
|
void setup()
|
|
{
|
|
// Setup pins.
|
|
button.Setup();
|
|
relay.Setup();
|
|
|
|
// Configure callbacks. Without std::function() we're stuck with using global functions.
|
|
attachInterrupt(button.pin_, ButtonCallback, FALLING);
|
|
mqtt_client.setCallback(MQTTCallback);
|
|
|
|
// Connect to WiFi.
|
|
wireless.Connect();
|
|
}
|
|
|
|
void loop()
|
|
{
|
|
// Move this to an MQTT class at some point.
|
|
if (!mqtt_client.connected())
|
|
{
|
|
// (Re)connect to MQTT broker.
|
|
if (mqtt_client.connect(name))
|
|
{
|
|
// This is dirty. Find a way to cleanly subscribe to a list of MQTT topics.
|
|
mqtt_client.subscribe("lights/LivingRoom/1");
|
|
}
|
|
}
|
|
|
|
// Process MQTT messages.
|
|
mqtt_client.loop();
|
|
|
|
// Handle button press. Find a way to handle
|
|
if (button.pressed_)
|
|
{
|
|
button.pressed_ = false;
|
|
relay.Toggle();
|
|
}
|
|
} |