ESP32 mit WIFI und MQTT rx und tx
您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

94 行
2.5KB

  1. #include <WiFi.h>
  2. #include <PubSubClient.h>
  3. // Update these with values suitable for your network.
  4. const char* ssid = "Andreas-Grabner.NET";
  5. const char* password = "born2win";
  6. const char* mqtt_server = "192.168.11.35";
  7. #define mqtt_port 1883
  8. #define MQTT_USER "loxberry"
  9. #define MQTT_PASSWORD "OSVL0AMqISFXgr5g"
  10. #define MQTT_SERIAL_PUBLISH_CH "ESP32/Heizung/status"
  11. #define MQTT_SERIAL_RECEIVER_CH "ESP32/Heizung/stufe"
  12. WiFiClient wifiClient;
  13. PubSubClient client(wifiClient);
  14. void setup_wifi() {
  15. delay(10);
  16. // We start by connecting to a WiFi network
  17. Serial.println();
  18. Serial.print("Connecting to ");
  19. Serial.println(ssid);
  20. WiFi.begin(ssid, password);
  21. while (WiFi.status() != WL_CONNECTED) {
  22. delay(500);
  23. Serial.print(".");
  24. }
  25. randomSeed(micros());
  26. Serial.println("");
  27. Serial.println("WiFi connected");
  28. Serial.println("IP address: ");
  29. Serial.println(WiFi.localIP());
  30. }
  31. void reconnect() {
  32. // Loop until we're reconnected
  33. while (!client.connected()) {
  34. Serial.print("Attempting MQTT connection...");
  35. // Create a random client ID
  36. String clientId = "ESP32Client-";
  37. clientId += String(random(0xffff), HEX);
  38. // Attempt to connect
  39. if (client.connect(clientId.c_str(),MQTT_USER,MQTT_PASSWORD)) {
  40. Serial.println("connected");
  41. //Once connected, publish an announcement...
  42. client.publish("icircuit/presence/ESP32/", "hello world");
  43. // ... and resubscribe
  44. client.subscribe(MQTT_SERIAL_RECEIVER_CH);
  45. } else {
  46. Serial.print("failed, rc=");
  47. Serial.print(client.state());
  48. Serial.println(" try again in 5 seconds");
  49. // Wait 5 seconds before retrying
  50. delay(5000);
  51. }
  52. }
  53. }
  54. void callback(char* topic, byte *payload, unsigned int length) {
  55. Serial.println("-------new message from broker-----");
  56. Serial.print("channel:");
  57. Serial.println(topic);
  58. Serial.print("data:");
  59. Serial.write(payload, length);
  60. Serial.println();
  61. }
  62. void setup() {
  63. Serial.begin(115200);
  64. Serial.setTimeout(500);// Set time out for
  65. setup_wifi();
  66. client.setServer(mqtt_server, mqtt_port);
  67. client.setCallback(callback);
  68. reconnect();
  69. }
  70. void publishSerialData(char *serialData){
  71. if (!client.connected()) {
  72. reconnect();
  73. }
  74. client.publish(MQTT_SERIAL_PUBLISH_CH, serialData);
  75. }
  76. void loop() {
  77. client.loop();
  78. if (Serial.available() > 0) {
  79. char mun[501];
  80. memset(mun,0, 501);
  81. Serial.readBytesUntil( '\n',mun,500);
  82. publishSerialData(mun);
  83. }
  84. }