Advertisement
Guest User

MQTT

a guest
Oct 15th, 2018
218
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /*
  2.   Simple wemos D1 mini  MQTT example
  3.   This sketch demonstrates the capabilities of the pubsub library in combination
  4.   with the ESP8266 board/library.
  5.   It connects to the provided access point using dhcp, using ssid and pswd
  6.   It connects to an MQTT server ( using mqtt_server ) then:
  7.   - publishes "connected"+uniqueID to the [root topic] ( using topic )
  8.   - subscribes to the topic "[root topic]/composeClientID()/in"  with a callback to handle
  9.   - If the first character of the topic "[root topic]/composeClientID()/in" is an 1,
  10.     switch ON the ESP Led, else switch it off
  11.   - after a delay of "[root topic]/composeClientID()/in" minimum, it will publish
  12.     a composed payload to
  13.   It will reconnect to the server if the connection is lost using a blocking
  14.   reconnect function.
  15.  
  16. */
  17.  
  18. #include <ESP8266WiFi.h>
  19. #include <PubSubClient.h>
  20.  
  21. // Update these with values suitable for your network.
  22.  
  23. const char* ssid = "MM";
  24. const char* pswd = "xxx";
  25. const char* mqtt_server = "192.168.1.38";
  26. const char* mqtt_user = "pi";
  27. const char* mqtt_password = "makke111";
  28. const char* topic = "wemos";    // rhis is the [root topic]
  29.  
  30. long timeBetweenMessages = 1000 * 20 * 1;
  31.  
  32. int LED = D7;
  33.  
  34. WiFiClient espClient;
  35. PubSubClient client(espClient);
  36. long lastMsg = 0;
  37. int value = 0;
  38.  
  39. int status = WL_IDLE_STATUS;     // the starting Wifi radio's status
  40.  
  41. void setup_wifi() {
  42.   delay(10);
  43.   // We start by connecting to a WiFi network
  44.   Serial.println();
  45.   Serial.print("Connecting to ");
  46.   Serial.println(ssid);
  47.   WiFi.begin(ssid, pswd);
  48.   while (WiFi.status() != WL_CONNECTED) {
  49.     delay(500);
  50.     Serial.print(".");
  51.   }
  52.   Serial.println("");
  53.   Serial.println("WiFi connected");
  54.   Serial.println("IP address: ");
  55.   Serial.println(WiFi.localIP());
  56. }
  57.  
  58. void callback(char* topic, byte* payload, unsigned int length) {
  59.   Serial.print("Message arrived [");
  60.   Serial.print(topic);
  61.   Serial.print("] ");
  62.   for (int i = 0; i < length; i++) {
  63.     Serial.print((char)payload[i]);
  64.   }
  65.   Serial.println();
  66.  
  67.   // Switch on the LED if an 1 was received as first character
  68.   if ((char)payload[0] == '1') {
  69.       digitalWrite(LED, HIGH);   // sets the LED on
  70.     // but actually the LED is on; this is because
  71.     // it is acive low on the ESP-01)
  72.   } else {
  73.       digitalWrite(LED, LOW);   // sets the LED on
  74.   }
  75. }
  76.  
  77.  
  78.  
  79. String macToStr(const uint8_t* mac)
  80. {
  81.   String result;
  82.   for (int i = 0; i < 6; ++i) {
  83.     result += String(mac[i], 16);
  84.     if (i < 5)
  85.       result += ':';
  86.   }
  87.   return result;
  88. }
  89.  
  90. String composeClientID() {
  91.   uint8_t mac[6];
  92.   WiFi.macAddress(mac);
  93.   String clientId;
  94.   clientId += "esp-";
  95.   clientId += macToStr(mac);
  96.   return clientId;
  97. }
  98.  
  99. void reconnect() {
  100.   // Loop until we're reconnected
  101.   while (!client.connected()) {
  102.     Serial.print("Attempting MQTT connection...");
  103.    
  104.     String clientId = composeClientID() ;
  105.     clientId += "-";
  106.     clientId += String(micros() & 0xff, 16); // to randomise. sort of
  107.  
  108.     // Attempt to connect
  109.     if (client.connect(clientId.c_str(), "pi", "makke111")) {
  110.       Serial.println("connected");
  111.       // Once connected, publish an announcement...
  112.       client.publish(topic, ("connected " + composeClientID()).c_str() , true );
  113.       // ... and resubscribe
  114.       // topic + clientID + in
  115.       String subscription;
  116.       subscription += topic;
  117.       subscription += "/";
  118.       subscription += composeClientID() ;
  119.       subscription += "/in";
  120.       client.subscribe(subscription.c_str() );
  121.       Serial.print("subscribed to : ");
  122.       Serial.println(subscription);
  123.     } else {
  124.       Serial.print("failed, rc=");
  125.       Serial.print(client.state());
  126.       Serial.print(" wifi=");
  127.       Serial.print(WiFi.status());
  128.       Serial.println(" try again in 5 seconds");
  129.       // Wait 5 seconds before retrying
  130.       delay(5000);
  131.     }
  132.   }
  133. }
  134.  
  135. void setup() {
  136.   pinMode(LED, OUTPUT); // Make LED pin D7 an output pin
  137.  
  138.   Serial.begin(115200);
  139.   setup_wifi();
  140.   client.setServer(mqtt_server, 1883);
  141.   client.setCallback(callback);
  142. }
  143.  
  144. void loop() {
  145.   // confirm still connected to mqtt server
  146.   if (!client.connected()) {
  147.     reconnect();
  148.   }
  149.   client.loop();
  150.  
  151.   long now = millis();
  152.   if (now - lastMsg > timeBetweenMessages ) {
  153.     lastMsg = now;
  154.     ++value;
  155.     String payload = "{\"micros\":";
  156.     payload += micros();
  157.     payload += ",\"counter\":";
  158.     payload += value;
  159.     payload += ",\"client\":";
  160.     payload += composeClientID();
  161.     payload += "}";
  162.     String pubTopic;
  163.      pubTopic += topic ;
  164.      pubTopic += "/";
  165.      pubTopic += composeClientID();
  166.      pubTopic += "/out";
  167.     Serial.print("Publish topic: ");
  168.     Serial.println(pubTopic);
  169.     Serial.print("Publish message: ");
  170.     Serial.println(payload);
  171.     client.publish( (char*) pubTopic.c_str() , (char*) payload.c_str(), true );
  172.   }
  173. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement