Advertisement
Guest User

Untitled

a guest
Jun 19th, 2019
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.67 KB | None | 0 0
  1. #include <ESP8266WiFi.h>
  2. #include <WiFiClient.h>
  3.  
  4. const char* ssid = "WISP";
  5. const char* password = "17215541";
  6.  
  7. WiFiClient espClient;
  8. #include <PubSubClient.h>
  9. char mqtt_server[] = "52.57.119.78";
  10. PubSubClient client(espClient);
  11.  
  12. void setup() {
  13.   Serial.begin(115200);
  14.   WiFi.mode(WIFI_STA);
  15.   WiFi.begin(ssid, password);
  16.    
  17.   while (WiFi.waitForConnectResult() != WL_CONNECTED) {
  18.     delay(1000);
  19.   }
  20.  
  21.   client.connect("1","","");
  22.   client.setServer(mqtt_server, 1883);
  23.   client.setCallback(callback);
  24.   while (!client.connected()) {
  25.     client.connect("1","","");
  26.     client.setServer(mqtt_server, 1883);
  27.     client.setCallback(callback);
  28.     if (client.connect("ksl")) { }
  29.     else {
  30.       delay(5000);
  31.     }
  32.   }
  33. }
  34.  
  35. void loop() {
  36.   String tmpValue = "";
  37.   String msg = "";
  38.   while(Serial.available() > 0){
  39.     char mychar = Serial.read();
  40.     tmpValue += mychar;
  41.   }
  42.  
  43.   if(tmpValue != ""){
  44.     for(int i=0;i<tmpValue.length();i++){
  45.         msg += tmpValue.charAt(i);
  46.     }
  47.     Serial.println(msg);
  48.     client.publish("hcix/tes1", String(msg).c_str());
  49.   }
  50.  
  51.   client.subscribe("hcix/tes1");
  52.   if(!client.connected()){
  53.     recon();
  54.   }
  55.   client.loop();
  56.  
  57.   delay(50);
  58.    
  59. }
  60.  
  61. void recon(){
  62.   while(!client.connected()){
  63.  
  64.     WiFi.mode(WIFI_STA);
  65.     WiFi.begin(ssid, password);
  66.     while (WiFi.waitForConnectResult() != WL_CONNECTED) {
  67.       delay(1000);
  68.     }
  69.  
  70.     if(client.connect("hcix")){
  71.       client.subscribe("hcix/tes1");
  72.     }
  73.     else{
  74.       delay(1000);
  75.     }
  76.   }
  77. }
  78.  
  79. void callback(char* topic, byte* payload, unsigned int length){
  80.   for(int i=0;i<length;i++){
  81.     Serial.print((char)payload[i]); //@500
  82.   }
  83. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement