mqttSubscribe (Function)

Top  Previous  Next

Architecture:

X32 / NX32 / NX32L

Firmware version:

3.12 / 1.00.00


This function will register a subscription to a topic on a MQTT server.

 

The topic can contain wild-cards (+ and #).

The + is used as a wild-card for a single level of hierarchy.

For example, a topic of "a/b/+/c" will match messages with topic "a/b/a/c" and "a/b/b/c", but not "a/b/c" or "a/b/a/c/d"

 

The # is used as a wild-card for all remaining levels of hierarchy.

For example, a topic of "a/b/#" will match messages with topic "a/b/c" and "a/b/c/d", but not "a/b".

 

Note:

There is no information stored in the RTCU about the subscriptions made. The information persistence is defined by the implementation behavior defined by the MQTT server.
 

 

Input:

handle : INT

The handle to the MQTT connection.

 

topic : STRING

The topic to subscribe to.

 

qos : SINT (0..2)

The QoS used by the MQTT server to transfer message to the device.

 

 

Returns: INT

0

- Subscription is registered.

1

- Invalid handle.

2

- Not connected to the MQTT server.

3

- Invalid parameter.

 

Declaration:

FUNCTION mqttSubscribe : INT;
VAR_INPUT
   handle : INT;
   topic  : STRING;
   qos    : SINT;
END_VAR;

 

Example:

INCLUDE rtcu.inc
 
VAR
   mqtt : INT;
   text : STRING;
   rxd  : mqttReceive;
   rc   : INT;
   msg  : ARRAY [1..50] OF SINT;
END_VAR;
 
PROGRAM example;
 
   DebugMsg(message := "Initialize GPRS...");
   gsmPower(power := ON);
   gprsOpen();
   WHILE NOT gprsConnected() DO
      DebugMsg(message := "Waiting for cellular connection...");
      Sleep(delay := 2500);
   END_WHILE;
   DebugMsg(message := "Initialize MQTT...");
   text := strFormat(format := "RTCU_\4", v4 := boardSerialNumber());
   mqtt := mqttOpen(ip := "test.mosquitto.org", port := 1883, clientid := text);
   DebugFmt(message := "MQTT handle= \1", v1 := mqtt);
 
   IF NOT mqttConnected(handle := mqttTHEN
      rc := mqttStatus(handle := mqtt);
      DebugFmt(message := "Connection failed, Status=\1", v1 := rc);
   END_IF;
 
   rc := mqttSubscribe(handle := mqtt, qos := 2, topic := "RTCU/+/temperature");
   DebugFmt(message := "Subscribed= \1", v1 := rc);
   rxd(data := ADDR(msg), maxsize := SIZEOF(msg));
 
BEGIN
   rc := mqttWaitEvent(timeout := 5);
   IF rc > 0 THEN
      DebugMsg(message := "Message received");
      rxd();
      DebugMsg(message := "-Topic= " + rxd.topic);
      DebugFmt(message := "-Handle= \1", v1 := rxd.handle);
      DebugFmt(message := "-Size= \1", v1 := rxd.size);
      DebugMsg(message := "-Temperature= " + strFromMemory(src := ADDR(msg), len := rxd.size));
   END_IF;
END;
END_PROGRAM;