munet Network Library for muwerk Scheduler
A muwerk network library supporting WiFi, NTP, OTA and MQTT for ESP8266 and ESP32 and serial links for all platforms
Loading...
Searching...
No Matches
Public Member Functions | List of all members
ustd::Mqtt Class Reference

munet MQTT Gateway Class More...

#include <mqtt.h>

Public Member Functions

 Mqtt ()
 
void begin (Scheduler *_pSched, String _mqttServer="", uint16_t _mqttServerPort=1883, bool _mqttRetained=false, String _clientName="${hostname}", String _domainToken="mu", String _outDomainToken="omu", String _mqttUsername="", String _mqttPassword="", String _willTopic="", String _willMessage="")
 
int addSubscription (int taskID, String topic, T_SUBS subs, String originator="")
 
bool removeSubscription (int subscriptionHandle, String topic)
 
bool outgoingBlockSet (String topic)
 
bool outgoingBlockRemove (String topic)
 
bool incomingBlockSet (String topic)
 
bool incomingBlockRemove (String topic)
 

Detailed Description

munet MQTT Gateway Class

The muwerk scheduler implements pub/sub inter-task communication between muwerk tasks. Tasks can subscribe to MQTT formatted topics and publish messages. The MQTT Class implements a gateway between the muwerk scheduler's message queue and an external MQTT server.

Publishing to external server:

This object extends the internal communication to external MQTT servers. All internal muwerk messages are published to the external MQTT server with prefix <outDomainPrefix>/<hostname>/. E.g. if a muwerk task ‘ustd::Scheduler.publish('led/set’, 'on')andclientNameof ESP is myhost, an MQTT publish message with topic'omu/myhost/led/set'and msgonis sent to the external server. DefaultoutDomainPrefixis'omu'. In order to publish to an unmodified topic, prefix the topic with'!', then neitheroutDomainPrefixnorclientNameare prepended. E.g. publish to topic'!system/urgent'will cause an MQTT publish to'system/urgent'` with no additional prefixes. Note: this can cause recursions.

Subscribing from external server:

This object subscribes two wild-card topics on the external server:

  1. <clientName>/#
  2. <domainToken>/#

<clientName> is by default the hostname of the device chip, but can be overwritten using _clientName in ustd::Mqtt.begin();. domainToken is "mu" by default and can be overwritten using _domainToken in ustd::Mqtt.begin();

Received messsages are stripped of clientName or domainToken prefix and published into ustd::Scheduler.publish(). That way external MQTT messages are routed to any muwerk task that uses the internal muwerk ustd::Scheduler.subscribe() mechanism, and all muwerk tasks can publish to external MQTT entities transparently.

Additionally, arbitrary topics can be subscribed to via addSubscription(). Topics that are added via addSubscription() are transparently forwarded. Nothing is stripped, and it is user's responsibility to prevent loops.

Sample MQTT Integration

#define __ESP__ 1 // Platform defines required, see doc, mainpage.
#include "scheduler.h"
#include "net.h"
#include "mqtt.h"
ustd::Scheduler sched;
ustd::Net net();
void setup() {
net.begin(&sched);
mqtt.begin(&sched);
}
munet MQTT Gateway Class
Definition: mqtt.h:79
void begin(Scheduler *_pSched, String _mqttServer="", uint16_t _mqttServerPort=1883, bool _mqttRetained=false, String _clientName="${hostname}", String _domainToken="mu", String _outDomainToken="omu", String _mqttUsername="", String _mqttPassword="", String _willTopic="", String _willMessage="")
Definition: mqtt.h:134
munet, the muwerk network class for WiFi and NTP
Definition: net.h:72

Constructor & Destructor Documentation

◆ Mqtt()

ustd::Mqtt::Mqtt ( )
inline

Instantiate an MQTT client object using the PubSubClient library.

This object connects to an external MQTT server as soon as a network connection is available.

Member Function Documentation

◆ addSubscription()

int ustd::Mqtt::addSubscription ( int  taskID,
String  topic,
T_SUBS  subs,
String  originator = "" 
)
inline

Subscribe via MQTT server to a topic to receive messages published to this topic

This function is similar to muwerk's subscribe() function, but in addition, this function does an external MQTT subscribe. By default, munet's mqtt only subscribes to topics that either start with clientName or with an optional domainName. Via this function, arbitrary MQTT subscriptions can be added.

addSubscription() subscribes on two layers: locally to muwerk's scheduler, and externally with the MQTT server.

Parameters
taskIDID of the task that is associated with this subscriptions (only used for statistics)
topicMQTT-style topic to be subscribed, can contain MQTT wildcards '#' and '*'. (A subscription to '#' receives all pubs)
subsCallback of type void myCallback(String topic, String msg, String originator) that is called, if a matching message is received. On ESP or Unixoid platforms, this can be a member function.
originatorOptional name of associated task.
Returns
subscriptionHandle on success (needed for unsubscribe), or -1 on error.

◆ begin()

void ustd::Mqtt::begin ( Scheduler *  _pSched,
String  _mqttServer = "",
uint16_t  _mqttServerPort = 1883,
bool  _mqttRetained = false,
String  _clientName = "${hostname}",
String  _domainToken = "mu",
String  _outDomainToken = "omu",
String  _mqttUsername = "",
String  _mqttPassword = "",
String  _willTopic = "",
String  _willMessage = "" 
)
inline

Connect to external MQTT server as soon as network is available

This method starts the MQTT gateway using the information stored into the configuration file /mqtt.json. All parameters passed in this method act as defaults if the corresponding option is not set in the configuration file. As soon as a network connection is available, the MQTT gateway is started.

Parameters
_pSchedPointer to the muwerk scheduler.
_mqttServer(optional, default is empty) Hostname or ip address of the MQTT server.
_mqttServerPort(optional, default is 1883) Port number under which the MQTT server is reachable
_mqttRetained(optional, default is false) If true, all messages published to the MQTT server will be flagged as RETAINED.
_clientName(optional, default is ${hostname}) the MQTT client name. WARNING: this name must be unique! Otherwise the MQTT server will rapidly disconnect.
_domainToken(optional, default is "mu") The MQTT client submitts to message topics <_clientName>/# and <_domainToken>/#, strips both <_domainToken> and <_clientName> from received topics and publishes those messages to the internal muwerk interface ustd::scheduler.publish().
_outDomainToken(optional, default is "omu") All pubblications from this client to outside MQTT-servers have their topic prefixed by <outDomainName>/<clientName>/topic. This is to prevent recursions.
_mqttUsernameUsername for mqtt server authentication, leave empty "" for no username.
_mqttPasswordPassword for mqtt server authentication, leave empty "" for no password.
_willTopicTopic of mqtt last will. Default is <outDomainName>/<clientName>/mqtt/state. Note: it is not recommended to change will-configuration, when using the home-assistant configuration.
_willMessageMessage content for last will message. Default is disconnected

he configuration options clientName and willMessage support the use of placeholders in order to allow values that are specific to a certain device without the need to create separate configuration files. Placeholders are written in the form of ${PLACEHOLDER}.

The following placeholders are currently available:

  • mac: full mac address
  • macls: last 4 digits of mac address
  • macfs: first 4 digits of mac address
  • hostname: the hostname of the system (from network)

◆ incomingBlockRemove()

bool ustd::Mqtt::incomingBlockRemove ( String  topic)
inline

Unblock a topic-wildcard from being received from external mqtt server

Parameters
topicAn mqtt topic wildcard for topics that should again be forwarded internally to muwerk. Unblock only removes a a block identical to the given topic. So topic must be identical to a topic (wildcard) that has been used with incomingBlockSet().
Returns
true on success, false if no corresponding block entry be found.

◆ incomingBlockSet()

bool ustd::Mqtt::incomingBlockSet ( String  topic)
inline

Block a topic-wildcard from being published to the internal scheduler

Parameters
topicAn mqtt topic wildcard for topics that should not be forwarded from external mqtt server to the muwerk scheduler. This can be used to block any incoming messages according to their topic.
Returns
true on success or if entry already exists, false if entry couldn't be added.

◆ outgoingBlockRemove()

bool ustd::Mqtt::outgoingBlockRemove ( String  topic)
inline

Unblock a topic-wildcard from being published to external mqtt server

Parameters
topicAn mqtt topic wildcard for topics that should again be forwarded to external mqtt. Unblock only removes a a block identical to the given topic. So topic must be identical to a topic (wildcard) that has been used with outgoingBlockSet().
Returns
true on success, false if no corresponding block could be found.

◆ outgoingBlockSet()

bool ustd::Mqtt::outgoingBlockSet ( String  topic)
inline

Block a topic-wildcard from being published to external mqtt server

Parameters
topicAn mqtt topic wildcard for topics that should not be forwarded to external mqtt. E.g. mymupplet/# Would block all messages a mupplet with name 'mymupplet' publishes from being forwarded to the extern mqtt server
Returns
true on success or if entry already exists, false if entry couldn't be added.

◆ removeSubscription()

bool ustd::Mqtt::removeSubscription ( int  subscriptionHandle,
String  topic 
)
inline

Unsubscribe a subscription

Parameters
subscriptionHandleHandle to subscription as returned by subscribe(), used for unsubscribe with muwerk's scheduler.
topicThe topic string that was used in addSubscription, used for unsubscribe via MQTT server.
Returns
true on successful unsubscription, false if no corresponding subscription is found.

The documentation for this class was generated from the following file: