-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMQTT-light.ino
68 lines (53 loc) · 1.43 KB
/
MQTT-light.ino
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
/*
- подключаемся к брокеру
- подписывается на топик "home/room1/light"
*/
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
const char *ssid = ""; // подключение к wifi
const char *pass = "";
IPAddress server(136, 3, 123, 33); // указываем IP нашего брокера
#define BUFFER_SIZE 100
void callback(const MQTT::Publish& pub) {
Serial.print(pub.topic());
Serial.print(" => ");
Serial.println(pub.payload_string());
if(pub.payload_string()=="on"){
Serial.println("ON");
digitalWrite(D8, LOW);
}
if(pub.payload_string()=="off"){
Serial.println("OFF");
digitalWrite(D8, HIGH);
}
}
WiFiClient wclient;
PubSubClient client(wclient, server);
void setup() {
Serial.begin(115200);
delay(50);
pinMode(D8, OUTPUT); // реле на ногу D8
Serial.println();
Serial.println();
}
void loop() {
if (WiFi.status() != WL_CONNECTED) {
Serial.print("Connecting to ");
Serial.print(ssid);
Serial.println("...");
WiFi.begin(ssid, pass);
if (WiFi.waitForConnectResult() != WL_CONNECTED)
return;
Serial.println("WiFi connected");
}
if (WiFi.status() == WL_CONNECTED) {
if (!client.connected()) {
if (client.connect("arduinoClient")) {
client.set_callback(callback);
client.subscribe("home/room1/light");
}
}
if (client.connected())
client.loop();
}
}