67 lines
No EOL
1.6 KiB
C++
67 lines
No EOL
1.6 KiB
C++
#include "Networking.h"
|
|
#include <PubSubClient.h>
|
|
#include <ESP8266WiFi.h>
|
|
|
|
Networking::Networking(char* hostname, char* ssid, char* password, char* mqttServer){
|
|
_hostname = hostname;
|
|
_ssid = ssid;
|
|
_password = password;
|
|
|
|
auto callback = std::bind(&Networking::mqttCallback, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3);
|
|
_mqttClient = PubSubClient(mqttServer, 1883, callback, _wifiClient);
|
|
}
|
|
|
|
void Networking::setup(){
|
|
WiFi.hostname(_hostname);
|
|
WiFi.begin(_ssid, _password);
|
|
reconnect();
|
|
}
|
|
|
|
void Networking::waitForWiFi() {
|
|
if (WiFi.status() == WL_CONNECTED)
|
|
return;
|
|
Serial.println("Reconnecting WiFi...");
|
|
int waitCount=0;
|
|
while (WiFi.status() != WL_CONNECTED) {
|
|
delay(100);
|
|
waitCount++;
|
|
if (waitCount>600)
|
|
ESP.restart();
|
|
}
|
|
Serial.println("Connected WiFi!");
|
|
}
|
|
|
|
void Networking::waitForMQTT() {
|
|
if (_mqttClient.connected())
|
|
return;
|
|
Serial.println("Reconnecting MQTT...");
|
|
while (!_mqttClient.connected())
|
|
if (!_mqttClient.connect(_hostname))
|
|
delay(50);
|
|
Serial.println("Connected MQTT!");
|
|
}
|
|
|
|
void Networking::reconnect() {
|
|
waitForWiFi();
|
|
waitForMQTT();
|
|
}
|
|
|
|
void Networking::loop(){
|
|
reconnect();
|
|
_mqttClient.loop();
|
|
}
|
|
|
|
void Networking::mqttCallback(char *topic, byte *payload, unsigned int length) {
|
|
Serial.print("Got payload: ");
|
|
for (int i = 0; i < length; i++)
|
|
Serial.print((char)payload[i]);
|
|
Serial.println();
|
|
}
|
|
|
|
void Networking::publish(const char* topic, const char* payload){
|
|
publish(topic, payload, false)
|
|
}
|
|
|
|
void Networking::publish(const char* topic, const char* payload, bool retained){
|
|
_mqttClient.publish(topic, payload, retained);
|
|
} |