mqttclient.ino 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. // This example uses an Arduino/Genuino Zero together with
  2. // by Gilberto Conti
  3. // https://github.com/256dpi/arduino-mqtt
  4. #include <ESP8266WiFi.h>
  5. #include <MQTT.h>
  6. const char ssid[] = "yckj01";
  7. const char pass[] = "yckj2015";
  8. const char clientId[] = "client1";
  9. const char username[] = "user1";
  10. const char password[] = "123456";
  11. WiFiClient net;
  12. MQTTClient client;
  13. unsigned long lastMillis = 0;
  14. void connect()
  15. {
  16. Serial.print("checking wifi...");
  17. while (WiFi.status() != WL_CONNECTED)
  18. {
  19. Serial.print(".");
  20. delay(1000);
  21. }
  22. Serial.print("\nconnecting...");
  23. while (!client.connect(clientId, username, password))
  24. {
  25. Serial.print(".");
  26. delay(1000);
  27. }
  28. Serial.println("\nconnected!");
  29. client.subscribe("/allot/request");
  30. // client.unsubscribe("/hello");
  31. }
  32. void messageReceived(String &topic, String &payload)
  33. {
  34. Serial.println("incoming: " + topic + " - " + payload);
  35. // Note: Do not use the client in the callback to publish, subscribe or
  36. // unsubscribe as it may cause deadlocks when other things arrive while
  37. // sending and receiving acknowledgments. Instead, change a global variable,
  38. // or push to a queue and handle it in the loop after calling `client.loop()`.
  39. }
  40. void setup()
  41. {
  42. Serial.begin(115200);
  43. WiFi.begin(ssid, pass);
  44. // Note: Local domain names (e.g. "Computer.local" on OSX) are not supported
  45. // by Arduino. You need to set the IP address directly.
  46. //
  47. // MQTT brokers usually use port 8883 for secure connections.
  48. client.begin("qqyun.itbbn.top", 1883, net);
  49. client.onMessage(messageReceived);
  50. client.setKeepAlive(30); //设置心跳时长
  51. connect();
  52. }
  53. void loop()
  54. {
  55. client.loop();
  56. if (!client.connected())
  57. {
  58. connect();
  59. }
  60. // publish a message roughly every second.
  61. if (millis() - lastMillis > 1000)
  62. {
  63. lastMillis = millis();
  64. //client.publish("/allot/request", "world");
  65. }
  66. String inputString = "";
  67. while (Serial.available())
  68. {
  69. inputString = inputString + char(Serial.read());
  70. delay(2);
  71. }
  72. if (inputString.length() > 0)
  73. {
  74. Serial.println("inputString:" + inputString); //把字符串传给串口
  75. client.publish("/allot/request", inputString); //向服务器反馈信息
  76. }
  77. }