From 60d75da482c7dccaa71e1790ce11fd221151117a Mon Sep 17 00:00:00 2001 From: Fisch Date: Wed, 10 May 2023 17:44:21 +0200 Subject: [PATCH] add wqtt initialization --- include/wifi_functions.h | 43 ++++++++++++++++++++++++++++++++++++++++ include/wifi_settings.h | 6 ++++++ platformio.ini | 3 ++- src/main.cpp | 8 ++++++++ 4 files changed, 59 insertions(+), 1 deletion(-) create mode 100644 include/wifi_functions.h create mode 100644 include/wifi_settings.h diff --git a/include/wifi_functions.h b/include/wifi_functions.h new file mode 100644 index 0000000..3b56d9a --- /dev/null +++ b/include/wifi_functions.h @@ -0,0 +1,43 @@ + +#ifndef _WIFI_FUNCTIONS_H_ +#define _WIFI_FUNCTIONS_H_ + +#include +#include + +#include "wifi_settings.h" + + +WiFiClient net; +MQTTClient client; + +void connect() { + Serial.print("checking wifi..."); + while (WiFi.status() != WL_CONNECTED) { + Serial.print("."); + delay(1000); + } + + Serial.print("\nconnecting..."); + while (!client.connect(client_id, "public", "public")) { + Serial.print("."); + delay(1000); + } + + Serial.println("\nconnected!"); + + client.subscribe("/hello"); + // client.unsubscribe("/hello"); +} + + +void messageReceived(String &topic, String &payload) { + Serial.println("incoming: " + topic + " - " + payload); + + // Note: Do not use the client in the callback to publish, subscribe or + // unsubscribe as it may cause deadlocks when other things arrive while + // sending and receiving acknowledgments. Instead, change a global variable, + // or push to a queue and handle it in the loop after calling `client.loop()`. +} + +#endif \ No newline at end of file diff --git a/include/wifi_settings.h b/include/wifi_settings.h new file mode 100644 index 0000000..d196ed0 --- /dev/null +++ b/include/wifi_settings.h @@ -0,0 +1,6 @@ + +const char ssid[] = "ssid"; +const char pass[] = "pass"; +const char mqtt_host[] = "10.0.0.1"; + +const char client_id[] = "hydroponic"; \ No newline at end of file diff --git a/platformio.ini b/platformio.ini index 3b6d3f5..09f7cc3 100644 --- a/platformio.ini +++ b/platformio.ini @@ -19,4 +19,5 @@ lib_deps = https://github.com/milesburton/Arduino-Temperature-Control-Library/ d03n3rfr1tz3/HC-SR04@^1.1.2 https://github.com/emilv/ArduinoSort/ - robtillaart/ADS1X15@^0.3.9 \ No newline at end of file + robtillaart/ADS1X15@^0.3.9 + 256dpi/MQTT@^2.5.1 \ No newline at end of file diff --git a/src/main.cpp b/src/main.cpp index 4b8fa6d..b17ed7d 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -1,5 +1,9 @@ #include + +#include "wifi_functions.h" + + bool debug=true; //print Serial information #include "helpfunctions.h" @@ -44,6 +48,10 @@ void setup() { pinMode(PIN_LED,OUTPUT); digitalWrite(PIN_LED,LOW); Serial.begin(115200); + WiFi.begin(ssid, pass); + client.begin(mqtt_host, net); + client.onMessage(messageReceived); + connect(); //init ADS1115 if (!ADS.begin()) {