61 lines
1.6 KiB
C++
61 lines
1.6 KiB
C++
#include "wlan.h"
|
|
#include "credentials.h"
|
|
|
|
void initial_connection() {
|
|
WiFi.begin(SSID, PSK);
|
|
WiFi.persistent(true);
|
|
WiFi.setAutoConnect(true);
|
|
WiFi.setAutoReconnect(true);
|
|
}
|
|
|
|
void connect_wlan(const int max_retries) {
|
|
if (WiFi.SSID() != SSID)
|
|
initial_connection();
|
|
int retries = 0;
|
|
while (WiFi.status() != WL_CONNECTED) {
|
|
if (retries == max_retries)
|
|
enter_deep_sleep(true);
|
|
retries++;
|
|
delay(1000);
|
|
Serial.print(".");
|
|
}
|
|
Serial.println("WiFi connected");
|
|
}
|
|
|
|
void connect_mqtt(PubSubClient &client, const char *device_id,
|
|
const char **topics, int num_topics) {
|
|
if (!client.connected())
|
|
client.setServer(MQTT_HOST, MQTT_PORT);
|
|
if (client.connect(device_id, MQTT_USER, MQTT_PASSWORD)) {
|
|
Serial.println("MQTT connected");
|
|
for (int i = 0; i < num_topics; i++)
|
|
client.subscribe(topics[i]);
|
|
}
|
|
}
|
|
|
|
void disconnect_mqtt(PubSubClient &client, const char **topics,
|
|
int num_topics) {
|
|
Serial.println("Disconnecting MQTT");
|
|
for (int i = 0; i < num_topics; i++)
|
|
client.unsubscribe(topics[i]);
|
|
client.disconnect();
|
|
}
|
|
|
|
void mqtt_transfer(PubSubClient &client, const char *device_id,
|
|
const char **topics, float *data, int num_topics) {
|
|
connect_mqtt(client, device_id, topics, num_topics);
|
|
for (int i = 0; i < num_topics; i++) {
|
|
char buffer[50];
|
|
sprintf(buffer, "%f", data[i]);
|
|
client.publish(topics[i], buffer);
|
|
}
|
|
Serial.println("Data transferred successfully");
|
|
}
|
|
|
|
void enter_deep_sleep(bool wifi_timeout) {
|
|
Serial.println("Entering deep sleep");
|
|
if (wifi_timeout)
|
|
WiFi.disconnect();
|
|
ESP.deepSleep(SLEEP_TIME, WAKE_RF_DEFAULT);
|
|
}
|