You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
96 lines
2.1 KiB
C++
96 lines
2.1 KiB
C++
#include <Arduino.h>
|
|
#include <ESP8266WiFi.h>
|
|
#include <PubSubClient.h>
|
|
#include <ArduinoJson.h>
|
|
|
|
const char *ssid = "PET Aflytningsvogn #43";
|
|
const char *password = "zwr33htm";
|
|
|
|
const char *mqtt_server = "192.168.24.215";
|
|
|
|
WiFiClient espClient;
|
|
PubSubClient client(espClient);
|
|
|
|
void setup_wifi()
|
|
{
|
|
delay(10);
|
|
// We start by connecting to a WiFi network
|
|
Serial.println();
|
|
Serial.print("Connecting to ");
|
|
Serial.println(ssid);
|
|
|
|
WiFi.begin(ssid, password);
|
|
|
|
while (WiFi.status() != WL_CONNECTED)
|
|
{
|
|
delay(500);
|
|
Serial.print(".");
|
|
}
|
|
|
|
Serial.println("");
|
|
Serial.println("WiFi connected");
|
|
Serial.println("IP address: ");
|
|
Serial.println(WiFi.localIP());
|
|
}
|
|
|
|
void reconnect()
|
|
{
|
|
// Loop until we're reconnected
|
|
while (!client.connected())
|
|
{
|
|
Serial.print("Attempting MQTT connection...");
|
|
// Attempt to connect
|
|
if (client.connect("ESP8266Client2"))
|
|
{
|
|
Serial.println("connected");
|
|
client.subscribe("door/lock");
|
|
}
|
|
else
|
|
{
|
|
Serial.print("failed, rc=");
|
|
Serial.print(client.state());
|
|
Serial.println(" try again in 5 seconds");
|
|
// Wait 5 seconds before retrying
|
|
delay(5000);
|
|
}
|
|
}
|
|
}
|
|
|
|
#define RELAY_ACTIVATION_PIN D6
|
|
|
|
void callback(char* topic, byte* payload, unsigned int length) {
|
|
StaticJsonDocument<256> doc;
|
|
deserializeJson(doc, payload, length);
|
|
|
|
Serial.print("Message arrived [");
|
|
Serial.print(topic);
|
|
Serial.print("] ");
|
|
for (int i = 0; i < length; i++) {
|
|
Serial.print((char)payload[i]);
|
|
}
|
|
Serial.println();
|
|
|
|
if (doc["deviceId"] == 2 && doc["lock"] == true) {
|
|
digitalWrite(RELAY_ACTIVATION_PIN, HIGH); // Turn the relay on
|
|
} else {
|
|
digitalWrite(RELAY_ACTIVATION_PIN, LOW); // Turn the relay off
|
|
}
|
|
|
|
}
|
|
|
|
void setup()
|
|
{
|
|
Serial.begin(115200);
|
|
|
|
pinMode(RELAY_ACTIVATION_PIN, OUTPUT);
|
|
|
|
setup_wifi();
|
|
client.setServer(mqtt_server, 1883);
|
|
client.setCallback(callback);
|
|
reconnect();
|
|
}
|
|
|
|
void loop()
|
|
{
|
|
client.loop();
|
|
} |