Advertisement
Guest User

Untitled

a guest
Apr 10th, 2020
191
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.08 KB | None | 0 0
  1. #include <Arduino.h>
  2. #include "ESP8266WiFi.h"
  3. #include "PubSubClient.h"
  4.  
  5. WiFiClient wifi_cli;
  6. PubSubClient client(wifi_cli);
  7. byte tmp;
  8. int tmp_l;
  9. String strPayload;
  10. char* tt;
  11.  
  12. void callback(char* topic, byte* payload, unsigned int length){
  13.   Serial.println("Arrived");
  14.   Serial.println(topic);
  15.   payload[length] = '\0'; //ovo je jako bitan deo u mom kodu to je specijalan karakter koji oznacava kraj stringa
  16.   strPayload = String((char*)payload);//cuvam u globalnu prom
  17.   Serial.println();
  18. }
  19.  
  20. void reconnect() {
  21.   // Loop until we're reconnected
  22.   while (!client.connected()) {
  23.     Serial.print("Attempting MQTT connection...");
  24.     // Create a random client ID
  25.     String clientId = "ESP8266Client-";
  26.     clientId += String(random(0xffff), HEX);
  27.     // Attempt to connect
  28.     if (client.connect(clientId.c_str(),"guest","guest99")) {
  29.       Serial.println("connected");
  30.       // Once connected, publish an announcement...
  31.       client.publish("outTopic", "hello world");
  32.       // ... and resubscribe
  33.       client.subscribe("inTopic");
  34.     } else {
  35.       Serial.print("failed, rc=");
  36.       Serial.print(client.state());
  37.       Serial.println(" try again in 5 seconds");
  38.       // Wait 5 seconds before retrying
  39.       delay(5000);
  40.     }
  41.   }
  42. }
  43.  
  44. void setup() {
  45.   // put your setup code here, to run once:
  46.   Serial.begin(9600);
  47.  
  48.   // Set WiFi to station mode and disconnect from an AP if it was previously connected
  49.   WiFi.mode(WIFI_STA);
  50.   WiFi.disconnect();
  51.  
  52.   delay(100);
  53.  
  54.   WiFi.mode(WIFI_STA);
  55.   WiFi.begin("SSladic", "7zvezdica");
  56.   Serial.println("");
  57.  
  58.   // Wait for connection
  59.   while (WiFi.status() != WL_CONNECTED) {
  60.     delay(500);
  61.     Serial.print(".");
  62.   }
  63.   Serial.println("");
  64.   Serial.print("Connected to SSladic");
  65.   Serial.print("IP address: ");
  66.   Serial.println(WiFi.localIP());
  67.  
  68.  
  69.   client.setServer("mqtt.inviewscada.com",1883);
  70.   client.setCallback(callback);
  71.  
  72.   Serial.println("Setup done");
  73. }
  74.  
  75. void loop() {
  76.  
  77.   if (!client.connected()) {
  78.     reconnect();
  79.   }
  80.   client.loop();
  81.  
  82.   Serial.println(strPayload);
  83.  
  84.   delay(1000);
  85.  
  86. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement