Advertisement
Guest User

Untitled

a guest
Aug 24th, 2020
613
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.46 KB | None | 0 0
  1. #include <Ethernet.h>
  2. #include <MQTT.h>
  3. #include <ArduinoJson.h>
  4.  
  5. byte mac[] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED};
  6. char device_name[] = "lamp";
  7. #define PORT_NUMBER_TO_CONTROL LED_BUILTIN
  8.  
  9.  
  10. EthernetClient net;
  11. MQTTClient client(350);
  12.  
  13. void connect() {
  14.   Serial.print("connecting...");
  15.   while (!client.connect("arduino", "try", "try")) {
  16.     Serial.print(".");
  17.     delay(1000);
  18.   }
  19.  
  20.   Serial.println("\nconnected!");
  21.  
  22.   client.subscribe("domoticz/out");
  23. }
  24.  
  25. void messageReceived(MQTTClient *client, char topic[], char payload[], int payload_length) {
  26.   StaticJsonDocument<350> doc;
  27.   deserializeJson(doc, payload, payload_length);
  28.  
  29.   Serial.println(freeMemory());
  30.   char* name = doc["name"].as<char*>();
  31.   int i = 0;
  32.   bool if_name_match = true;
  33.   while (name[i]) {
  34.     if (name[i] != device_name[i]) {
  35.       if_name_match = false;
  36.       break;
  37.     }
  38.     i++;
  39.   }
  40.   if (if_name_match) {
  41.     if (!doc["nvalue"].as<bool>()) {
  42.       digitalWrite(PORT_NUMBER_TO_CONTROL, HIGH);
  43.       Serial.println("Включено");
  44.     }
  45.     else {
  46.       digitalWrite(PORT_NUMBER_TO_CONTROL, LOW);
  47.       Serial.println("Выключено");
  48.     }
  49.   }
  50. }
  51.  
  52. void setup() {
  53.   pinMode(PORT_NUMBER_TO_CONTROL, OUTPUT);
  54.   Serial.begin(115200);
  55.   Ethernet.begin(mac);
  56.   client.begin("192.168.0.120", net);
  57.   client.onMessageAdvanced(messageReceived);
  58.   connect();
  59. }
  60.  
  61. void loop() {
  62.   client.loop();
  63.  
  64.   if (!client.connected()) {
  65.     connect();
  66.   }
  67. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement