You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
56 lines
1.2 KiB
56 lines
1.2 KiB
7 years ago
|
#include "MyMQTT.h"
|
||
|
|
||
|
#include <MQTTClient.h>
|
||
|
#include "hardware.h"
|
||
|
|
||
|
MyMQTT::MyMQTT(void)
|
||
|
: host {mqtt_server},
|
||
|
port {mqtt_port},
|
||
|
endpoint {mqtt_endpoint},
|
||
|
username {mqtt_username},
|
||
|
password {mqtt_password}
|
||
|
{}
|
||
|
|
||
|
static void onMqttMessage(String &topic, String &payload) {
|
||
|
Serial.println("incoming: " + topic + " - " + payload);
|
||
|
}
|
||
|
|
||
|
void MyMQTT::connect(void) {
|
||
|
Serial.print("MQTT connecting");
|
||
|
|
||
|
mqttClient.begin(host, port, net);
|
||
|
mqttClient.onMessage(&onMqttMessage);
|
||
|
while (!mqttClient.connect(host, username, password)) {
|
||
|
Serial.print(".");
|
||
|
delay(500);
|
||
|
}
|
||
|
Serial.println("MQTT connected");
|
||
|
subscribe();
|
||
|
}
|
||
|
|
||
|
void MyMQTT::loop(void) {
|
||
|
auto available = (size_t)net.available();
|
||
|
if (available > 0) {
|
||
|
Serial.println("data available\n");
|
||
|
}
|
||
|
mqttClient.loop();
|
||
|
|
||
|
if(!mqttClient.connected()) {
|
||
|
Serial.println("MQTT connection lost.");
|
||
|
connect();
|
||
|
}
|
||
|
}
|
||
|
|
||
|
void MyMQTT::subscribe(void) {
|
||
|
mqttClient.subscribe("sensor/vendingmachine/dispense");
|
||
|
// mqttClient.subscribe("sensor/vendingmachine/light");
|
||
|
}
|
||
|
|
||
|
void MyMQTT::publish(char* topic, char* payload) {
|
||
|
mqttClient.publish(topic, payload);
|
||
|
}
|
||
|
|
||
|
void MyMQTT::publish(char* topic, String payload) {
|
||
|
mqttClient.publish(topic, payload);
|
||
|
}
|