Advertisement
Guest User

Untitled

a guest
Aug 24th, 2020
718
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <ESP8266WiFi.h>
  2. #include <MQTT.h>
  3. #include <ArduinoJson.h>
  4.  
  5. const char *SSID = "ssid";
  6. const char *PWD = "password";
  7. char device_name[] = "lamp";
  8. #define PORT_NUMBER_TO_CONTROL LED_BUILTIN
  9.  
  10.  
  11. WiFiClient wifiClient = WiFiClient();
  12. MQTTClient client(350);
  13.  
  14. unsigned long lastMillis = 0;
  15. void connect() {
  16.   Serial.print("connecting...");
  17.   while (!client.connect("arduino", "try", "try")) {
  18.     Serial.print(".");
  19.     delay(1000);
  20.   }
  21.  
  22.   Serial.println("\nconnected!");
  23.  
  24.   client.subscribe("domoticz/out");
  25. }
  26.  
  27. void messageReceived(MQTTClient *client, char topic[], char payload[], int payload_length) {
  28.   StaticJsonDocument<350> doc;
  29.   deserializeJson(doc, payload, payload_length);
  30.  
  31.   const char* name = doc["name"].as<char*>();
  32.   int i = 0;
  33.   bool if_name_match = true;
  34.   while (name[i]) {
  35.     if (name[i] != device_name[i]) {
  36.       if_name_match = false;
  37.       break;
  38.     }
  39.     i++;
  40.   }
  41.   if (if_name_match) {
  42.     if (!doc["nvalue"].as<bool>()) {
  43.       digitalWrite(PORT_NUMBER_TO_CONTROL, HIGH);
  44.       Serial.println("Включено");
  45.     }
  46.     else {
  47.       digitalWrite(PORT_NUMBER_TO_CONTROL, LOW);
  48.       Serial.println("Выключено");
  49.     }
  50.   }
  51. }
  52.  
  53. void setup() {
  54.   pinMode(PORT_NUMBER_TO_CONTROL, OUTPUT);
  55.   Serial.begin(115200);
  56.  
  57.   Serial.print("Connecting to ");
  58.   Serial.println(SSID);
  59.   WiFi.begin(SSID, PWD);
  60.  
  61.   while (WiFi.status() != WL_CONNECTED) {
  62.     Serial.print(".");
  63.     delay(500);
  64.     // we can even make the ESP32 to sleep
  65.   }
  66.  
  67.   Serial.println("Connected - ");
  68.   client.begin("192.168.0.120", wifiClient);
  69.   client.onMessageAdvanced(messageReceived);
  70.   connect();
  71. }
  72.  
  73. void loop() {
  74.   client.loop();
  75.  
  76.   if (!client.connected()) {
  77.     connect();
  78.   }
  79. }
Advertisement
Advertisement
Advertisement
RAW Paste Data Copied
Advertisement