L0cutus

Untitled

Sep 7th, 2020 (edited)
674
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 7.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 <Wire.h>
  13. #include <Adafruit_GFX.h>
  14. #include <Adafruit_SSD1306.h>
  15.  
  16. #define SCREEN_WIDTH 128 // OLED display width, in pixels
  17. #define SCREEN_HEIGHT 64 // OLED display height, in pixels
  18.  
  19. // Declaration for an SSD1306 display connected to I2C (SDA, SCL pins)
  20. #define OLED_RESET     4 // Reset pin # (or -1 if sharing Arduino reset pin)
  21. Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);
  22.  
  23. // Change the credentials below, so your ESP32 connects to your router
  24. #define WIFI_SSID "MYSSID"
  25. #define WIFI_PASSWORD "MYPWD"
  26.  
  27. // Change the MQTT_HOST variable to your Raspberry Pi IP address,
  28. // so it connects to your Mosquitto MQTT broker
  29. #define MQTT_HOST IPAddress(192, 168, 1, NNN)
  30. #define MQTT_PORT 1883
  31.  
  32. // Create objects to handle MQTT client
  33. AsyncMqttClient mqttClient;
  34. TimerHandle_t mqttReconnectTimer;
  35. TimerHandle_t wifiReconnectTimer;
  36.  
  37. // Define GPIO where the pushbutton is connected to
  38. const int buttonPin = 32;
  39. int buttonState;                      // current reading from the input pin (pushbutton)
  40. int lastButtonState = LOW;            // previous reading from the input pin (pushbutton)
  41. unsigned long lastDebounceTime = 0;   // the last time the output pin was toggled
  42. unsigned long debounceDelay = 50;     // the debounce time; increase if the output flickers
  43.  
  44. void connectToWifi() {
  45.   Serial.println("Connecting to Wi-Fi...");
  46.   WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
  47. }
  48.  
  49. void connectToMqtt() {
  50.   Serial.println("Connecting to MQTT...");
  51.   mqttClient.connect();
  52. }
  53.  
  54. void WiFiEvent(WiFiEvent_t event) {
  55.   Serial.printf("[WiFi-event] event: %d\n", event);
  56.   switch(event) {
  57.     case SYSTEM_EVENT_STA_GOT_IP:
  58.       Serial.println("WiFi connected");
  59.       Serial.println("IP address: ");
  60.       Serial.println(WiFi.localIP());
  61.       connectToMqtt();
  62.       break;
  63.     case SYSTEM_EVENT_STA_DISCONNECTED:
  64.       Serial.println("WiFi lost connection");
  65.       xTimerStop(mqttReconnectTimer, 0); // ensure we don't reconnect to MQTT while reconnecting to Wi-Fi
  66.       xTimerStart(wifiReconnectTimer, 0);
  67.       break;
  68.   }
  69. }
  70.  
  71. // Add more topics that want your ESP32 to be subscribed to
  72. void onMqttConnect(bool sessionPresent) {
  73.   Serial.println("Connected to MQTT.");
  74.   Serial.print("Session present: ");
  75.   Serial.println(sessionPresent);
  76.   uint16_t packetIdSub = mqttClient.subscribe("esp32/temperature", 0);
  77.   Serial.print("Subscribing at QoS 0, packetId: ");
  78.   Serial.println(packetIdSub);
  79. }
  80.  
  81. void onMqttDisconnect(AsyncMqttClientDisconnectReason reason) {
  82.   Serial.println("Disconnected from MQTT.");
  83.   if (WiFi.isConnected()) {
  84.     xTimerStart(mqttReconnectTimer, 0);
  85.   }
  86. }
  87.  
  88. void onMqttSubscribe(uint16_t packetId, uint8_t qos) {
  89.   Serial.println("Subscribe acknowledged.");
  90.   Serial.print("  packetId: ");
  91.   Serial.println(packetId);
  92.   Serial.print("  qos: ");
  93.   Serial.println(qos);
  94. }
  95.  
  96. void onMqttUnsubscribe(uint16_t packetId) {
  97.   Serial.println("Unsubscribe acknowledged.");
  98.   Serial.print("  packetId: ");
  99.   Serial.println(packetId);
  100. }
  101.  
  102. void onMqttPublish(uint16_t packetId) {
  103.   Serial.println("Publish acknowledged.");
  104.   Serial.print("  packetId: ");
  105.   Serial.println(packetId);
  106. }
  107.  
  108. // You can modify this function to handle what happens when you receive a certain message in a specific topic
  109. void onMqttMessage(char* topic, char* payload, AsyncMqttClientMessageProperties properties, size_t len, size_t index, size_t total) {
  110.   String messageTemp;
  111.   for (int i = 0; i < len; i++) {
  112.     //Serial.print((char)payload[i]);
  113.     messageTemp += (char)payload[i];
  114.   }
  115.   if (strcmp(topic, "esp32/temperature") == 0) {
  116.  
  117. //    display.clearDisplay();
  118. //    display.setTextSize(1);             // Normal 1:1 pixel scale
  119. //    display.setTextColor(SSD1306_WHITE);        // Draw white text
  120. //    display.setCursor(0,0);             // Start at top-left corner
  121. //    display.println(F("Temperature:"));
  122. //    display.setTextColor(SSD1306_WHITE);        // Draw white text
  123. //    display.print(messageTemp);
  124. //    display.display();
  125.     testdrawstyles();
  126.   }
  127.  
  128.   Serial.println("Publish received.");
  129.   Serial.print("  message: ");
  130.   Serial.println(messageTemp);
  131.   Serial.print("  topic: ");
  132.   Serial.println(topic);
  133.   Serial.print("  qos: ");
  134.   Serial.println(properties.qos);
  135.   Serial.print("  dup: ");
  136.   Serial.println(properties.dup);
  137.   Serial.print("  retain: ");
  138.   Serial.println(properties.retain);
  139.   Serial.print("  len: ");
  140.   Serial.println(len);
  141.   Serial.print("  index: ");
  142.   Serial.println(index);
  143.   Serial.print("  total: ");
  144.   Serial.println(total);
  145. }
  146.  
  147. void setup() {
  148.  
  149.   Serial.begin(115200);
  150.  
  151.   // SSD1306_SWITCHCAPVCC = generate display voltage from 3.3V internally
  152.   if(!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) { // Address 0x3D for 128x64
  153.     Serial.println(F("SSD1306 allocation failed"));
  154.     for(;;); // Don't proceed, loop forever
  155.   }
  156.  
  157.   // Define buttonPin as an INPUT
  158.   pinMode(buttonPin, INPUT);
  159.  
  160.  
  161.   mqttReconnectTimer = xTimerCreate("mqttTimer", pdMS_TO_TICKS(2000), pdFALSE, (void*)0, reinterpret_cast<TimerCallbackFunction_t>(connectToMqtt));
  162.   wifiReconnectTimer = xTimerCreate("wifiTimer", pdMS_TO_TICKS(2000), pdFALSE, (void*)0, reinterpret_cast<TimerCallbackFunction_t>(connectToWifi));
  163.  
  164.   WiFi.onEvent(WiFiEvent);
  165.  
  166.   mqttClient.onConnect(onMqttConnect);
  167.   mqttClient.onDisconnect(onMqttDisconnect);
  168.   mqttClient.onSubscribe(onMqttSubscribe);
  169.   mqttClient.onUnsubscribe(onMqttUnsubscribe);
  170.   mqttClient.onMessage(onMqttMessage);
  171.   mqttClient.onPublish(onMqttPublish);
  172.   mqttClient.setServer(MQTT_HOST, MQTT_PORT);
  173.  
  174.   connectToWifi();
  175. }
  176.  
  177. void loop() {
  178.   // Read the state of the pushbutton and save it in a local variable
  179.   int reading = digitalRead(buttonPin);
  180.  
  181.   // If the pushbutton state changed (due to noise or pressing it), reset the timer
  182.   if (reading != lastButtonState) {
  183.     // Reset the debouncing timer
  184.     lastDebounceTime = millis();
  185.   }
  186.  
  187.   // If the button state has changed, after the debounce time
  188.   if ((millis() - lastDebounceTime) > debounceDelay) {
  189.     // And if the current reading is different than the current buttonState    
  190.     if (reading != buttonState) {
  191.       buttonState = reading;
  192.       // Publish an MQTT message on topic esp32/led to toggle the LED (turn the LED on or off)P
  193.       if (buttonState == HIGH) {
  194.         mqttClient.publish("esp32/led", 0, true, "toggle");
  195.         Serial.println("Publishing on topic esp32/led topic at QoS 0");    
  196.       }
  197.     }
  198.   }
  199.   // Save the reading. Next time through the loop, it'll be the lastButtonState
  200.   lastButtonState = reading;
  201. }
  202.  
  203. void testdrawstyles(void) {
  204.   display.clearDisplay();
  205.   display.setTextSize(1);             // Normal 1:1 pixel scale
  206.   display.setTextColor(SSD1306_WHITE);        // Draw white text
  207.   display.setCursor(0,0);             // Start at top-left corner
  208.   display.println(F("Hello, world!"));
  209.  
  210.   display.setTextColor(SSD1306_BLACK, SSD1306_WHITE); // Draw 'inverse' text
  211.   display.println(3.141592);
  212.  
  213.   display.setTextSize(2);             // Draw 2X-scale text
  214.   display.setTextColor(SSD1306_WHITE);
  215.   display.print("0x"); display.println(0xDEADBEEF, HEX);
  216.  
  217.   display.display();
  218.   delay(2000);
  219. }
  220.  
Add Comment
Please, Sign In to add comment