Hendrik Langer
7 years ago
7 changed files with 127 additions and 2 deletions
@ -0,0 +1,55 @@ |
|||||
|
#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); |
||||
|
} |
@ -0,0 +1,28 @@ |
|||||
|
#ifndef _MYMQTT_H |
||||
|
#define _MYMQTT_H |
||||
|
|
||||
|
#include <WiFiClientSecure.h> |
||||
|
#include <MQTTClient.h> |
||||
|
|
||||
|
#include "config.h" |
||||
|
|
||||
|
class MyMQTT { |
||||
|
public: |
||||
|
MyMQTT(void); |
||||
|
void connect(void); |
||||
|
void loop(void); |
||||
|
void subscribe(void); |
||||
|
void publish(char* topic, char* payload); |
||||
|
void publish(char* topic, String payload); |
||||
|
// static void onMqttMessage(String &topic, String &payload);
|
||||
|
private: |
||||
|
const char* host; |
||||
|
const uint32_t port; |
||||
|
const char* endpoint; |
||||
|
const char* username; |
||||
|
const char* password; |
||||
|
WiFiClientSecure net; |
||||
|
MQTTClient mqttClient; |
||||
|
}; |
||||
|
|
||||
|
#endif /* _MYMQTT_H */ |
Loading…
Reference in new issue