Advertisement
Guest User

esp-test-mqtt

a guest
Oct 21st, 2016
114
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.03 KB | None | 0 0
  1.  
  2. /* ESP8266+Arduino IDE Test code
  3. Object :
  4. - TCP Socket(port 4444) Server.
  5. - ESP8266 AP mode test.
  6. Requirement :
  7. - ESP8266WiFi.h Library (https://github.com/esp8266/Arduino)
  8. - PubSubClient.h Library (https://github.com/Imroy/pubsubclient)
  9. - DW.miniESP board (https://github.com/deaware/dwminiesp_firmware_support)
  10. - Arduino IDE 1.6.4
  11.  
  12. Write by : Myconfix (http://www.myconfix.com/)
  13. Fanpage : https://www.facebook.com/myconfix
  14. github : https://github.com/myconfix/ESP8266ArduinoExample
  15. */
  16.  
  17.  
  18. #include <ESP8266WiFi.h>
  19. #include <PubSubClient.h>
  20.  
  21. // Prepare AP id&password.
  22. const char *ssid = "Telemach Guest"; //your access point ssid // cannot be longer than 32 characters!
  23. const char *password = ""; //your access point password
  24.  
  25.  
  26. //Prepare Mqtt connection data
  27. const char *MQTTBroker = "m21.cloudmqtt.com";
  28. const char *MQTTuser = "salca";
  29. const char *MQTTpassword = "salcajekralj";
  30. const char *Topic = "/temp";
  31. const char *Topicid = "/temp";
  32. uint16_t port = 17859;
  33. //uint16_t port = 1883; //defalut port
  34.  
  35.  
  36. int count = 0;
  37.  
  38. PubSubClient mqtt(MQTTBroker,port);
  39.  
  40. void callback(const MQTT::Publish& pub){
  41. // handle message arrived
  42. Serial.println(pub.payload_string());
  43. }
  44. void setup()
  45. {
  46.  
  47. Serial.begin(115200);
  48. WiFi.mode(WIFI_STA);
  49. WiFi.disconnect();
  50. WiFi.begin(ssid, password);
  51. while (WiFi.status() != WL_CONNECTED) {
  52. delay(500);
  53. Serial.print(".");
  54. }
  55. Serial.println("");
  56. Serial.println("WiFi connected");
  57. Serial.println("IP address: ");
  58. Serial.println(WiFi.localIP());
  59. WiFi.printDiag(Serial);
  60.  
  61. mqtt.set_callback(callback); //Set Callback function
  62.  
  63. if (mqtt.connect(MQTT::Connect("esp8266").set_auth(MQTTuser,MQTTpassword))){
  64. mqtt.publish(Topic, "Hello"); //publish
  65. mqtt.subscribe(Topicid); //subscribe
  66. }
  67. else
  68. Serial.println("not connected to mqtt");
  69. }
  70.  
  71.  
  72. void loop()
  73. {
  74.  
  75.  
  76. count++;
  77. String con = String(count);
  78. delay(1000);
  79.  
  80. mqtt.publish(Topic, con); //publish
  81. if(mqtt.subscribe(Topicid)!=0) //subscribe
  82. {
  83.  
  84.  
  85. //Serial.println(Topicid);
  86. }
  87.  
  88.  
  89. mqtt.loop();
  90.  
  91.  
  92. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement