firmware/src/mqtt/MQTT.h

89 lines
2.6 KiB
C
Raw Normal View History

#pragma once
#include "configuration.h"
2021-04-03 14:27:06 +00:00
#include "concurrency/OSThread.h"
#include "mesh/Channels.h"
2023-01-18 14:56:47 +00:00
#include "mesh/generated/meshtastic/mqtt.pb.h"
#include <PubSubClient.h>
2022-10-25 22:07:02 +00:00
#if HAS_WIFI
#include <WiFiClient.h>
2022-10-25 22:07:02 +00:00
#endif
#if HAS_ETHERNET
#include <EthernetClient.h>
#endif
#define MAX_MQTT_QUEUE 16
/**
* Our wrapper/singleton for sending/receiving MQTT "udp" packets. This object isolates the MQTT protocol implementation from
* the two components that use it: MQTTPlugin and MQTTSimInterface.
*/
2021-04-03 14:27:06 +00:00
class MQTT : private concurrency::OSThread
{
// supposedly the current version is busted:
// http://www.iotsharing.com/2017/08/how-to-use-esp32-mqtts-with-mqtts-mosquitto-broker-tls-ssl.html
// WiFiClientSecure wifiClient;
2022-10-25 22:07:02 +00:00
#if HAS_WIFI
WiFiClient mqttClient;
2022-10-25 22:07:02 +00:00
#endif
#if HAS_ETHERNET
EthernetClient mqttClient;
#endif
PubSubClient pubSub;
// instead we supress sleep from our runOnce() callback
// CallbackObserver<MQTT, void *> preflightSleepObserver = CallbackObserver<MQTT, void *>(this, &MQTT::preflightSleepCb);
public:
MQTT();
/**
* Publish a packet on the glboal MQTT server.
* This hook must be called **after** the packet is encrypted (including the channel being changed to a hash).
* @param chIndex the index of the channel for this message
*
* Note: for messages we are forwarding on the mesh that we can't find the channel for (because we don't have the keys), we
* can not forward those messages to the cloud - becuase no way to find a global channel ID.
*/
void onSend(const MeshPacket &mp, ChannelIndex chIndex);
/** Attempt to connect to server if necessary
*/
void reconnect();
2022-10-26 09:09:59 +00:00
bool connected();
2021-04-03 14:27:06 +00:00
protected:
2023-01-12 15:09:03 +00:00
PointerQueue<ServiceEnvelope> mqttQueue;
int reconnectCount = 0;
2023-01-12 15:09:03 +00:00
2022-01-24 17:24:40 +00:00
virtual int32_t runOnce() override;
2021-04-03 14:27:06 +00:00
private:
/** return true if we have a channel that wants uplink/downlink
*/
bool wantsLink() const;
2021-04-05 00:42:52 +00:00
/** Tell the server what subscriptions we want (based on channels.downlink_enabled)
*/
void sendSubscriptions();
/// Just C glue to call onPublish
static void mqttCallback(char *topic, byte *payload, unsigned int length);
/// Called when a new publish arrives from the MQTT server
void onPublish(char *topic, byte *payload, unsigned int length);
/// Called when a new publish arrives from the MQTT server
2022-10-18 19:51:40 +00:00
std::string downstreamPacketToJson(MeshPacket *mp);
/// Return 0 if sleep is okay, veto sleep if we are connected to pubsub server
// int preflightSleepCb(void *unused = NULL) { return pubSub.connected() ? 1 : 0; }
};
void mqttInit();
extern MQTT *mqtt;