Guest User

Mqtt attempt 3

a guest
Jun 3rd, 2020
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 6.33 KB | None | 0 0
  1. /*********
  2. Rui Santos
  3. Complete project details at https://randomnerdtutorials.com
  4. *********/
  5.  
  6. #include <WiFi.h>
  7. extern "C" {
  8. #include "freertos/FreeRTOS.h"
  9. #include "freertos/timers.h"
  10. }
  11. #include <AsyncMqttClient.h>
  12. #include <OneWire.h>
  13. #include <DallasTemperature.h>
  14. #include <Adafruit_BME280.h>
  15. #include <Adafruit_Sensor.h>
  16. #include <Wire.h>
  17.  
  18. Adafruit_BME280 bme; // I2C
  19.  
  20. // Change the credentials below, so your ESP32 connects to your router
  21. #define WIFI_SSID "REPLACE_WITH_YOUR_SSID"
  22. #define WIFI_PASSWORD "REPLACE_WITH_YOUR_PASSWORD"
  23.  
  24. // Change the MQTT_HOST variable to your Raspberry Pi IP address,
  25. // so it connects to your Mosquitto MQTT broker
  26. #define MQTT_HOST IPAddress(192, 168, 1, 91)
  27. #define MQTT_PORT 1883
  28.  
  29. // Create objects to handle MQTT client
  30. AsyncMqttClient mqttClient;
  31. TimerHandle_t mqttReconnectTimer;
  32. TimerHandle_t wifiReconnectTimer;
  33.  
  34. String temperatureString = ""; // Variable to hold the temperature reading
  35. unsigned long previousMillis = 0; // Stores last time temperature was published
  36. const long interval = 5000; // interval at which to publish sensor readings
  37.  
  38. const int ledPin = 25; // GPIO where the LED is connected to
  39. int ledState = LOW; // the current state of the output pin
  40.  
  41. // GPIO where the DS18B20 is connected to
  42. const int oneWireBus = 32;
  43. // Setup a oneWire instance to communicate with any OneWire devices
  44. OneWire oneWire(oneWireBus);
  45. // Pass our oneWire reference to Dallas Temperature sensor
  46. DallasTemperature sensors(&oneWire);
  47.  
  48. void connectToWifi() {
  49. Serial.println("Connecting to Wi-Fi...");
  50. WiFi.begin("runningdog", "n,bUs692>Hq");
  51. }
  52.  
  53. void connectToMqtt() {
  54. Serial.println("Connecting to MQTT...");
  55. mqttClient.connect();
  56. }
  57.  
  58. void WiFiEvent(WiFiEvent_t event) {
  59. Serial.printf("[WiFi-event] event: %d\n", event);
  60. switch(event) {
  61. case SYSTEM_EVENT_STA_GOT_IP:
  62. Serial.println("WiFi connected");
  63. Serial.println("IP address: ");
  64. Serial.println(WiFi.localIP());
  65. connectToMqtt();
  66. break;
  67. case SYSTEM_EVENT_STA_DISCONNECTED:
  68. Serial.println("WiFi lost connection");
  69. xTimerStop(mqttReconnectTimer, 0); // ensure we don't reconnect to MQTT while reconnecting to Wi-Fi
  70. xTimerStart(wifiReconnectTimer, 0);
  71. break;
  72. }
  73. }
  74.  
  75. // Add more topics that want your ESP32 to be subscribed to
  76. void onMqttConnect(bool sessionPresent) {
  77. Serial.println("Connected to MQTT.");
  78. Serial.print("Session present: ");
  79. Serial.println(sessionPresent);
  80. // ESP32 subscribed to esp32/led topic
  81. uint16_t packetIdSub = mqttClient.subscribe("esp32/led", 0);
  82. Serial.print("Subscribing at QoS 0, packetId: ");
  83. Serial.println(packetIdSub);
  84. }
  85.  
  86. void onMqttDisconnect(AsyncMqttClientDisconnectReason reason) {
  87. Serial.println("Disconnected from MQTT.");
  88. if (WiFi.isConnected()) {
  89. xTimerStart(mqttReconnectTimer, 0);
  90. }
  91. }
  92.  
  93. void onMqttSubscribe(uint16_t packetId, uint8_t qos) {
  94. Serial.println("Subscribe acknowledged.");
  95. Serial.print(" packetId: ");
  96. Serial.println(packetId);
  97. Serial.print(" qos: ");
  98. Serial.println(qos);
  99. }
  100.  
  101. void onMqttUnsubscribe(uint16_t packetId) {
  102. Serial.println("Unsubscribe acknowledged.");
  103. Serial.print(" packetId: ");
  104. Serial.println(packetId);
  105. }
  106.  
  107. void onMqttPublish(uint16_t packetId) {
  108. Serial.println("Publish acknowledged.");
  109. Serial.print(" packetId: ");
  110. Serial.println(packetId);
  111. }
  112.  
  113. // You can modify this function to handle what happens when you receive a certain message in a specific topic
  114. void onMqttMessage(char* topic, char* payload, AsyncMqttClientMessageProperties properties, size_t len, size_t index, size_t total) {
  115. String messageTemp;
  116. for (int i = 0; i < len; i++) {
  117. //Serial.print((char)payload[i]);
  118. messageTemp += (char)payload[i];
  119. }
  120. // Check if the MQTT message was received on topic esp32/led
  121. if (strcmp(topic, "esp32/led") == 0) {
  122. // If the LED is off turn it on (and vice-versa)
  123. if (ledState == LOW) {
  124. ledState = HIGH;
  125. } else {
  126. ledState = LOW;
  127. }
  128. // Set the LED with the ledState of the variable
  129. digitalWrite(ledPin, ledState);
  130. }
  131.  
  132. Serial.println("Publish received.");
  133. Serial.print(" message: ");
  134. Serial.println(messageTemp);
  135. Serial.print(" topic: ");
  136. Serial.println(topic);
  137. Serial.print(" qos: ");
  138. Serial.println(properties.qos);
  139. Serial.print(" dup: ");
  140. Serial.println(properties.dup);
  141. Serial.print(" retain: ");
  142. Serial.println(properties.retain);
  143. Serial.print(" len: ");
  144. Serial.println(len);
  145. Serial.print(" index: ");
  146. Serial.println(index);
  147. Serial.print(" total: ");
  148. Serial.println(total);
  149. }
  150.  
  151. void setup() {
  152. // Start the DS18B20 sensor
  153. sensors.begin();
  154. // Define LED as an OUTPUT and set it LOW
  155. pinMode(ledPin, OUTPUT);
  156. digitalWrite(ledPin, LOW);
  157.  
  158. Serial.begin(115200);
  159.  
  160. mqttReconnectTimer = xTimerCreate("mqttTimer", pdMS_TO_TICKS(2000), pdFALSE, (void*)0, reinterpret_cast<TimerCallbackFunction_t>(connectToMqtt));
  161. wifiReconnectTimer = xTimerCreate("wifiTimer", pdMS_TO_TICKS(2000), pdFALSE, (void*)0, reinterpret_cast<TimerCallbackFunction_t>(connectToWifi));
  162.  
  163. WiFi.onEvent(WiFiEvent);
  164.  
  165. mqttClient.onConnect(onMqttConnect);
  166. mqttClient.onDisconnect(onMqttDisconnect);
  167. mqttClient.onSubscribe(onMqttSubscribe);
  168. mqttClient.onUnsubscribe(onMqttUnsubscribe);
  169. mqttClient.onMessage(onMqttMessage);
  170. mqttClient.onPublish(onMqttPublish);
  171. mqttClient.setServer(MQTT_HOST, MQTT_PORT);
  172.  
  173. connectToWifi();
  174. }
  175.  
  176. void loop() {
  177. unsigned long currentMillis = millis();
  178. // Every X number of seconds (interval = 5 seconds)
  179. // it publishes a new MQTT message on topic esp32/temperature
  180. if (currentMillis - previousMillis >= interval) {
  181. // Save the last time a new reading was published
  182. previousMillis = currentMillis;
  183. // New temperature readings
  184. // sensors.requestTemperatures();
  185. temperatureString = " " + String(bme.readTemperature()) + "C " ;
  186. Serial.println(temperatureString);
  187. // Publish an MQTT message on topic esp32/temperature with Celsius and Fahrenheit temperature readings
  188. uint16_t packetIdPub2 = mqttClient.publish("esp32/temperature", 2, true, temperatureString.c_str());
  189. Serial.print("Publishing on topic esp32/temperature at QoS 2, packetId: ");
  190. Serial.println(packetIdPub2);
  191. }
  192. }
Add Comment
Please, Sign In to add comment