diff --git a/ESP32_Utils.hpp b/ESP32_Utils.hpp new file mode 100644 index 0000000..6078403 --- /dev/null +++ b/ESP32_Utils.hpp @@ -0,0 +1,40 @@ +void ConnectWiFi_STA(bool useStaticIP = false) +{ + Serial.println(""); + WiFi.mode(WIFI_STA); + if(useStaticIP) { + WiFi.config(ip, gateway, subnet); + WiFi.setHostname(hostname); + } + WiFi.begin(ssid, password); + + while (WiFi.status() != WL_CONNECTED) { + delay(100); + Serial.print('.'); + } + + Serial.println(""); + Serial.print("Iniciado STA:\t"); + Serial.println(ssid); + Serial.print("IP address:\t"); + Serial.println(WiFi.localIP()); +} + +void ConnectWiFi_AP(bool useStaticIP = false) +{ + Serial.println(""); + WiFi.mode(WIFI_AP); + while(!WiFi.softAP(ssid, password)) + { + Serial.println("."); + delay(100); + } + + if(useStaticIP) WiFi.softAPConfig(ip, gateway, subnet); + + Serial.println(""); + Serial.print("Iniciado AP:\t"); + Serial.println(ssid); + Serial.print("IP address:\t"); + Serial.println(WiFi.softAPIP()); +} \ No newline at end of file diff --git a/ESP32_Utils_MQTT_Async.hpp b/ESP32_Utils_MQTT_Async.hpp new file mode 100644 index 0000000..016392a --- /dev/null +++ b/ESP32_Utils_MQTT_Async.hpp @@ -0,0 +1,89 @@ +#pragma once + +TimerHandle_t mqttReconnectTimer; +TimerHandle_t wifiReconnectTimer; + +void ConnectToMqtt() +{ + Serial.println("Connecting to MQTT..."); + mqttClient.connect(); +} + +void WiFiEvent(WiFiEvent_t event) +{ + Serial.printf("[WiFi-event] event: %d\n", event); + switch(event) + { + case ARDUINO_EVENT_WIFI_STA_GOT_IP: + Serial.println("WiFi connected"); + Serial.println("IP address: "); + Serial.println(WiFi.localIP()); + ConnectToMqtt(); + break; + case ARDUINO_EVENT_WIFI_STA_DISCONNECTED: + Serial.println("WiFi lost connection"); + xTimerStop(mqttReconnectTimer, 0); // ensure we don't reconnect to MQTT while reconnecting to Wi-Fi + xTimerStart(wifiReconnectTimer, 0); + break; + } +} + +void OnMqttConnect(bool sessionPresent) +{ + Serial.println("Connected to MQTT."); + Serial.print("Session present: "); + Serial.println(sessionPresent); + SuscribeMqtt(); +} + +void OnMqttDisconnect(AsyncMqttClientDisconnectReason reason) +{ + Serial.println("Disconnected from MQTT."); + + if(WiFi.isConnected()) + { + xTimerStart(mqttReconnectTimer, 0); + } +} + +void OnMqttSubscribe(uint16_t packetId, uint8_t qos) +{ + Serial.println("Subscribe acknowledged."); + Serial.print(" packetId: "); + Serial.println(packetId); + Serial.print(" qos: "); + Serial.println(qos); +} + +void OnMqttUnsubscribe(uint16_t packetId) +{ + Serial.println("Unsubscribe acknowledged."); + Serial.print(" packetId: "); + Serial.println(packetId); +} + + +void OnMqttPublish(uint16_t packetId) +{ + Serial.println("Publish acknowledged."); + Serial.print(" packetId: "); + Serial.println(packetId); +} + +void InitMqtt() +{ + mqttReconnectTimer = xTimerCreate("mqttTimer", pdMS_TO_TICKS(2000), pdFALSE, (void*)0, reinterpret_cast(ConnectToMqtt)); + wifiReconnectTimer = xTimerCreate("wifiTimer", pdMS_TO_TICKS(5000), pdFALSE, (void*)0, reinterpret_cast(ConnectWiFi_STA)); + + mqttClient.onConnect(OnMqttConnect); + mqttClient.onDisconnect(OnMqttDisconnect); + + mqttClient.onSubscribe(OnMqttSubscribe); + mqttClient.onUnsubscribe(OnMqttUnsubscribe); + + mqttClient.onMessage(OnMqttReceived); + mqttClient.onPublish(OnMqttPublish); + + mqttClient.setServer(MQTT_HOST, MQTT_PORT); + mqttClient.setCredentials(MQTT_USER, MQTT_PASS); +} \ No newline at end of file diff --git a/JSON_functions.hpp b/JSON_functions.hpp new file mode 100644 index 0000000..1646873 --- /dev/null +++ b/JSON_functions.hpp @@ -0,0 +1,26 @@ +#pragma once + +void reconstr (String payload) { + JsonDocument doc; + + DeserializationError error = deserializeJson(doc, payload); + + if (error) { + Serial.print("deserializeJson() failed: "); + Serial.println(error.c_str()); + return; + } + + // EXAMPLE PAYLOAD. CHANGE THIS TO THE APPROPRIATE ONE. + int a = doc["a"]; + bool b = doc["b"]; + float c = doc["c"]; + Serial.println("The payload received contains: "); + Serial.print("a: "); + Serial.print(a); + Serial.print(" b: "); + Serial.print(b); + Serial.print(" c: "); + Serial.println(c); + +} \ No newline at end of file diff --git a/MQTT.hpp b/MQTT.hpp new file mode 100644 index 0000000..839a7e9 --- /dev/null +++ b/MQTT.hpp @@ -0,0 +1,42 @@ +#pragma once + +const IPAddress MQTT_HOST(10, 98, 20, 10); +const int MQTT_PORT = 1883; + +AsyncMqttClient mqttClient; + +String GetPayloadContent(char* data, size_t len) +{ + String content = ""; + for(size_t i = 0; i < len; i++) + { + content.concat(data[i]); + } + return content; +} + +void SuscribeMqtt() +{ + uint16_t packetIdSub = mqttClient.subscribe("user123456/channel", 0); + Serial.print("Subscribing at QoS 2, packetId: "); + Serial.println(packetIdSub); +} + +String payload; +void PublishMqtt(unsigned long data) +{ + String payload = String(data); + mqttClient.publish("hello/world", 0, true, (char*)payload.c_str()); +} + +void OnMqttReceived(char* topic, char* payload, AsyncMqttClientMessageProperties properties, size_t len, size_t index, size_t total) +{ + //Serial.print("Received on "); + //Serial.print(topic); + //Serial.print(": "); + + String content = GetPayloadContent(payload, len); + reconstr(content); + //Serial.print(content); + //Serial.println(); +} diff --git a/config.h b/config.h new file mode 100644 index 0000000..ac1d20a --- /dev/null +++ b/config.h @@ -0,0 +1,10 @@ +const char* ssid = "SmartNet"; +const char* password = "smartpass"; +const char* hostname = "ESP32_mqtt_test"; + +IPAddress ip(10, 98, 30, 150); +IPAddress gateway(10, 98, 30, 1); +IPAddress subnet(255, 255, 255, 0); + +#define MQTT_USER "esp32_vesper" +#define MQTT_PASS "vesper" \ No newline at end of file diff --git a/vesper.ino b/vesper.ino index 95c2b6e..cfe55e3 100644 --- a/vesper.ino +++ b/vesper.ino @@ -1,9 +1,31 @@ -void setup() { - // put your setup code here, to run once: +# +#include +#include +#include + +#include "config.h" // Sustituir con datos de vuestra red +#include "JSON_functions.hpp" +#include "MQTT.hpp" +#include "ESP32_Utils.hpp" +#include "ESP32_Utils_MQTT_Async.hpp" + + +void setup() +{ + Serial.begin(115200); + + delay(500); + + WiFi.onEvent(WiFiEvent); + InitMqtt(); + + ConnectWiFi_STA(); } -void loop() { - // put your main code here, to run repeatedly: - -} +void loop() +{ + // EXAMPLE PUBLISH. CHANGE THIS, IF NEEDED. + //delay(1000); + //PublishMqtt(millis()); +} \ No newline at end of file