2023-03-30 01:28:31 +02:00
|
|
|
#include "wlan.h"
|
|
|
|
#include "credentials.h"
|
2023-04-03 06:23:03 +02:00
|
|
|
#include <ArduinoJson.h>
|
2023-03-30 01:28:31 +02:00
|
|
|
|
2023-03-30 02:10:49 +02:00
|
|
|
void initial_connection() {
|
|
|
|
WiFi.begin(SSID, PSK);
|
|
|
|
WiFi.persistent(true);
|
|
|
|
WiFi.setAutoConnect(true);
|
|
|
|
WiFi.setAutoReconnect(true);
|
|
|
|
}
|
|
|
|
|
2023-04-03 03:26:12 +02:00
|
|
|
void connect_wlan(const int max_retries) {
|
2023-03-30 02:10:49 +02:00
|
|
|
if (WiFi.SSID() != SSID)
|
|
|
|
initial_connection();
|
|
|
|
int retries = 0;
|
2023-03-30 01:28:31 +02:00
|
|
|
while (WiFi.status() != WL_CONNECTED) {
|
2023-03-30 02:10:49 +02:00
|
|
|
if (retries == max_retries)
|
|
|
|
enter_deep_sleep(true);
|
2023-04-03 03:26:12 +02:00
|
|
|
retries++;
|
2023-03-30 01:28:31 +02:00
|
|
|
delay(1000);
|
|
|
|
Serial.print(".");
|
|
|
|
}
|
|
|
|
Serial.println("WiFi connected");
|
|
|
|
}
|
|
|
|
|
2023-04-03 03:26:12 +02:00
|
|
|
void connect_mqtt(PubSubClient &client, const char *device_id,
|
2023-04-03 06:23:03 +02:00
|
|
|
const char *topic) {
|
2023-04-03 03:26:12 +02:00
|
|
|
if (!client.connected())
|
|
|
|
client.setServer(MQTT_HOST, MQTT_PORT);
|
|
|
|
if (client.connect(device_id, MQTT_USER, MQTT_PASSWORD)) {
|
|
|
|
Serial.println("MQTT connected");
|
2023-04-03 06:23:03 +02:00
|
|
|
client.subscribe(topic);
|
2023-04-03 03:26:12 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-04-03 06:23:03 +02:00
|
|
|
void disconnect_mqtt(PubSubClient &client, const char *topic) {
|
2023-04-03 03:26:12 +02:00
|
|
|
Serial.println("Disconnecting MQTT");
|
2023-04-03 06:23:03 +02:00
|
|
|
client.unsubscribe(topic);
|
2023-04-03 03:26:12 +02:00
|
|
|
client.disconnect();
|
|
|
|
}
|
|
|
|
|
2023-04-03 06:23:03 +02:00
|
|
|
size_t construct_json(float *data, char *buffer, int buffer_size) {
|
|
|
|
StaticJsonDocument<100> json;
|
|
|
|
json["temperature"] = data[0];
|
|
|
|
json["humidity"] = data[1];
|
|
|
|
json["soil_humidity"] = data[2];
|
|
|
|
size_t payload_size = serializeJson(json, buffer, buffer_size);
|
|
|
|
return payload_size;
|
|
|
|
}
|
|
|
|
|
2023-04-03 03:26:12 +02:00
|
|
|
void mqtt_transfer(PubSubClient &client, const char *device_id,
|
2023-04-03 06:23:03 +02:00
|
|
|
const char *topic, float *data) {
|
|
|
|
char buffer[100];
|
|
|
|
connect_mqtt(client, device_id, topic);
|
|
|
|
size_t payload_size = construct_json(data, buffer, 100);
|
|
|
|
client.publish(topic, buffer, payload_size);
|
2023-04-03 03:26:12 +02:00
|
|
|
Serial.println("Data transferred successfully");
|
2023-03-30 01:28:31 +02:00
|
|
|
}
|
|
|
|
|
2023-03-30 02:10:49 +02:00
|
|
|
void enter_deep_sleep(bool wifi_timeout) {
|
2023-04-03 03:26:12 +02:00
|
|
|
Serial.println("Entering deep sleep");
|
2023-03-30 02:10:49 +02:00
|
|
|
if (wifi_timeout)
|
2023-03-30 01:28:31 +02:00
|
|
|
WiFi.disconnect();
|
|
|
|
ESP.deepSleep(SLEEP_TIME, WAKE_RF_DEFAULT);
|
|
|
|
}
|