Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <ESP8266WiFi.h>
- #include <MQTT.h>
- #include <ArduinoJson.h>
- const char *SSID = "ssid";
- const char *PWD = "password";
- char device_name[] = "lamp";
- #define PORT_NUMBER_TO_CONTROL LED_BUILTIN
- WiFiClient wifiClient = WiFiClient();
- MQTTClient client(350);
- unsigned long lastMillis = 0;
- void connect() {
- Serial.print("connecting...");
- while (!client.connect("arduino", "try", "try")) {
- Serial.print(".");
- delay(1000);
- }
- Serial.println("\nconnected!");
- client.subscribe("domoticz/out");
- }
- void messageReceived(MQTTClient *client, char topic[], char payload[], int payload_length) {
- StaticJsonDocument<350> doc;
- deserializeJson(doc, payload, payload_length);
- const char* name = doc["name"].as<char*>();
- int i = 0;
- bool if_name_match = true;
- while (name[i]) {
- if (name[i] != device_name[i]) {
- if_name_match = false;
- break;
- }
- i++;
- }
- if (if_name_match) {
- if (!doc["nvalue"].as<bool>()) {
- digitalWrite(PORT_NUMBER_TO_CONTROL, HIGH);
- Serial.println("Включено");
- }
- else {
- digitalWrite(PORT_NUMBER_TO_CONTROL, LOW);
- Serial.println("Выключено");
- }
- }
- }
- void setup() {
- pinMode(PORT_NUMBER_TO_CONTROL, OUTPUT);
- Serial.begin(115200);
- Serial.print("Connecting to ");
- Serial.println(SSID);
- WiFi.begin(SSID, PWD);
- while (WiFi.status() != WL_CONNECTED) {
- Serial.print(".");
- delay(500);
- // we can even make the ESP32 to sleep
- }
- Serial.println("Connected - ");
- client.begin("192.168.0.120", wifiClient);
- client.onMessageAdvanced(messageReceived);
- connect();
- }
- void loop() {
- client.loop();
- if (!client.connected()) {
- connect();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement