Advertisement
Guest User

Pubsub MQTT ESP32,8266

a guest
Sep 19th, 2019
126
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 3.76 KB | None | 0 0
  1. /*
  2.  Basic ESP8266 MQTT example
  3.  
  4.  This sketch demonstrates the capabilities of the pubsub library in combination
  5.  with the ESP8266 board/library.
  6.  
  7.  It connects to an MQTT server then:
  8.   - publishes "hello world" to the topic "outTopic" every two seconds
  9.   - subscribes to the topic "inTopic", printing out any messages
  10.     it receives. NB - it assumes the received payloads are strings not binary
  11.   - If the first character of the topic "inTopic" is an 1, switch ON the ESP Led,
  12.     else switch it off
  13.  
  14.  It will reconnect to the server if the connection is lost using a blocking
  15.  reconnect function. See the 'mqtt_reconnect_nonblocking' example for how to
  16.  achieve the same result without blocking the main loop.
  17.  
  18.  To install the ESP8266 board, (using Arduino 1.6.4+):
  19.   - Add the following 3rd party board manager under "File -> Preferences -> Additional Boards Manager URLs":
  20.        http://arduino.esp8266.com/stable/package_esp8266com_index.json
  21.   - Open the "Tools -> Board -> Board Manager" and click install for the ESP8266"
  22.   - Select your ESP8266 in "Tools -> Board"
  23.  
  24. */
  25.  
  26. #include <WiFi.h>
  27. #include <PubSubClient.h>
  28.  
  29. // Update these with values suitable for your network.
  30.  
  31. const char* ssid = "TEC_2.4G";
  32. const char* password = "tritech99";
  33. const char* mqtt_server = "192.168.1.102";
  34.  
  35. WiFiClient espClient;
  36. PubSubClient client(espClient);
  37. long lastMsg = 0;
  38. char msg[50];
  39. int value = 0;
  40.  
  41. void setup_wifi() {
  42.  
  43.   delay(10);
  44.   // We start by connecting to a WiFi network
  45.   Serial.println();
  46.   Serial.print("Connecting to ");
  47.   Serial.println(ssid);
  48.  
  49.   WiFi.begin(ssid, password);
  50.  
  51.   while (WiFi.status() != WL_CONNECTED) {
  52.     delay(500);
  53.     Serial.print(".");
  54.   }
  55.  
  56.   randomSeed(micros());
  57.  
  58.   Serial.println("");
  59.   Serial.println("WiFi connected");
  60.   Serial.println("IP address: ");
  61.   Serial.println(WiFi.localIP());
  62. }
  63.  
  64. void callback(char* topic, byte* payload, unsigned int length) {
  65.   Serial.print("Message arrived [");
  66.   Serial.print(topic);
  67.   Serial.print("] ");
  68.   for (int i = 0; i < length; i++) {
  69.     Serial.print((char)payload[i]);
  70.   }
  71.   Serial.println();
  72.  
  73.   // Switch on the LED if an 1 was received as first character
  74.   if ((char)payload[0] == '1') {
  75.     digitalWrite(BUILTIN_LED, LOW);   // Turn the LED on (Note that LOW is the voltage level
  76.     // but actually the LED is on; this is because
  77.     // it is active low on the ESP-01)
  78.   } else {
  79.     digitalWrite(BUILTIN_LED, HIGH);  // Turn the LED off by making the voltage HIGH
  80.   }
  81.  
  82. }
  83.  
  84. void reconnect() {
  85.   // Loop until we're reconnected
  86.   while (!client.connected()) {
  87.     Serial.print("Attempting MQTT connection...");
  88.     // Create a random client ID
  89.     String clientId = "ESP8266Client-";
  90.     clientId += String(random(0xffff), HEX);
  91.     // Attempt to connect
  92.     if (client.connect(clientId.c_str())) {
  93.       Serial.println("connected");
  94.       // Once connected, publish an announcement...
  95.       client.publish("outTopic", "hello world");
  96.       // ... and resubscribe
  97.       client.subscribe("inTopic");
  98.     } else {
  99.       Serial.print("failed, rc=");
  100.       Serial.print(client.state());
  101.       Serial.println(" try again in 5 seconds");
  102.       // Wait 5 seconds before retrying
  103.       delay(5000);
  104.     }
  105.   }
  106. }
  107.  
  108. void setup() {
  109.   pinMode(BUILTIN_LED, OUTPUT);     // Initialize the BUILTIN_LED pin as an output
  110.   Serial.begin(115200);
  111.   setup_wifi();
  112.   client.setServer(mqtt_server, 1883);
  113.   client.setCallback(callback);
  114. }
  115.  
  116. void loop() {
  117.  
  118.   if (!client.connected()) {
  119.     reconnect();
  120.   }
  121.   client.loop();
  122.  
  123.   long now = millis();
  124.   if (now - lastMsg > 2000) {
  125.     lastMsg = now;
  126.     ++value;
  127.     snprintf (msg, 50, "hello world #%ld", value);
  128.     Serial.print("Publish message: ");
  129.     Serial.println(msg);
  130.     client.publish("outTopic", msg);
  131.   }
  132. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement