Advertisement
mikehole

MQTT Subs Problem

Mar 14th, 2016
705
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.83 KB | None | 0 0
  1. #include <ESP8266WiFi.h>
  2. #include <PubSubClient.h>
  3.  
  4. const char *ssid = "????????????";
  5. const char *password = "???????????";
  6.  
  7. const char* mqtt_server = "MikeHoleHome.azure-devices.net";
  8.  
  9. WiFiClientSecure espClient;
  10.  
  11. PubSubClient client(espClient, mqtt_server, 8883);
  12.  
  13. void callback(const MQTT::Publish& pub);
  14.  
  15. long lastMsg = 0;
  16. char msg[50];
  17. int value = 0;
  18.  
  19. #define BUFFER_SIZE 100
  20.  
  21. void setup() {
  22.     Serial.begin(115200);
  23. }
  24.  
  25. void callback(const MQTT::Publish& pub) {
  26.     Serial.println(pub.topic());
  27.  
  28.     Serial.print("payload_len : ");
  29.     Serial.println(pub.payload_len());
  30.    
  31.     if (pub.has_stream()) {
  32.         Serial.println(" (stream) => ");
  33.  
  34.         uint8_t buf[BUFFER_SIZE];
  35.         int read;
  36.         while (read = pub.payload_stream()->read(buf, BUFFER_SIZE)) {
  37.             Serial.write(buf, read);
  38.         }
  39.         pub.payload_stream()->stop();
  40.         Serial.println("");
  41.     }
  42.     else
  43.     {
  44.         Serial.println(" (string) => ");
  45.         Serial.println(pub.payload_string());
  46.     }
  47. }
  48.  
  49. void loop() {
  50.     if (WiFi.status() != WL_CONNECTED) {
  51.         Serial.print("Connecting to ");
  52.         Serial.print(ssid);
  53.         Serial.println("...");
  54.         WiFi.begin(ssid, password);
  55.  
  56.         if (WiFi.waitForConnectResult() != WL_CONNECTED)
  57.             return;
  58.         Serial.println("WiFi connected");
  59.     }
  60.  
  61.     if (WiFi.status() == WL_CONNECTED) {
  62.         if (!client.connected()) {
  63.             Serial.println("Connecting to MQTT server");
  64.             if (client.connect(MQTT::Connect("TestDevice")
  65.                 .set_auth("MikeHoleHome.azure-devices.net/TestDevice", "??????"))) {
  66.                
  67.                 Serial.println("Connected to MQTT server");
  68.                
  69.                 client.set_callback(callback);
  70.                 //client.publish("devices/TestDevice/messages/events/", "hello world");
  71.                
  72.                 client.subscribe("devices/TestDevice/messages/devicebound/#");
  73.             }
  74.             else {
  75.                 Serial.println("Could not connect to MQTT server");
  76.             }
  77.         }
  78.  
  79.         if (client.connected())
  80.         {
  81.             client.loop();
  82.         }
  83.     }
  84. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement