Skip to main content

"subscribeToMqtt"

Use the "subscribeToMqtt" action to add or remove a client's subscriptions

The "subscribeToMqtt" action adds or removes a client's subscriptions. It does not disconnect an MQTT client. You may also find it convenient to modify subscriptions using the "createMqttSession" and "alterMqttSession" actions.

Use the required "clientName" property to identify the client. An MQTT session with that client identifier must already exist; otherwise, it returns an error.

The "subscriptionActions" property contains a list of subscription objects that can add or remove a topic filter from a client's subscriptions.

  • Use the required "subscriptionAction" property to add or remove a topic filter: "add" adds a topic filter to the subscription and  "remove" removes it. 

  • Use the required "topicFilter" property to a wildcard topic to subscribe to multiple topics. 

  • Use the optional "subscriptionIdentifier" property to assign a unique identifier to the subscription. When the broker sends an MQTT 5 message to the client, it includes the subscription identifier to help the client identify the subscription quickly and easily.

  • Use the optional "includeExpiredMessages": true to include expired messages in the subscription. It defaults to false.

  • Use the optional "receiveRetainedMessages" property to control when the MQTT broker sends retained messages to your subscription. 

  • Use the optional "receiveMyMessages" property to prevent or allow the broker to send messages to a client that the client published. 

  • Use the optional "userProperties" property to set broker-specific subscription properties.

Tip

Use "subscribeToMqtt" to configure subscriptions for any MQTT client and set MQTT 5 subscription properties on its behalf. 

Note

The account logged into the JSON MQ Message API must have permission to access the session identified by "clientName".

Request example

{
  "api": "mq",
  "action": "subscribeToMqtt",
  "params":
  {
    "clientName": "a unique MQTT client identifier",
    "subscriptionActions": [
      {
        "subscriptionAction": "add | remove",
        "topicFilter": "myTopic",
        "subscriptionIdentifier": 268435455,
        "binaryFormat": "base64 | hex | utf8 | json | byteArray",
        "includeExpiredMessages": true,
        "receiveMyMessages": false,
        "receiveRetainedMessages": "onSubscription | onNewSubscription | never",
        "receiveRetainedFlagAsPublished": true,
        "userProperties": [
          { 
            "key": "some key", 
            "value": "some value" 
          }
        ]  
      },
      {
        "subscriptionAction": "add",
        "topicFilter": "some/topic2/name/#",
        "userProperties": [
          { 
            "key": "some key", 
            "value": "some value" 
          }
        ]  
      }
    ]
  },
  "apiVersion": "1.0",
  "debug": "max",
  "requestId": "optionalUniqueRequestIdFromTheClient",
  "authToken": "replaceWithAuthTokenFromCreateSession"
}
{
  "requestId": "clientRequestId",
  "result": {
    "subscriptions": [
      {
        "topicFilter": "myTopic",
        "matchingTopics": [
          "myTopic"
        ],
        "retainedMessages": [
          {
            "payload": "This is the message payload.",
            "binaryFormat": "utf8",
            "contentType": "IanaMediaType or a CustomType",
            "correlationData": "any JSON value up to 65500 bytes",
            "expirySeconds": 60,
            "retain": true,
            "responseTopic": "topic/name/for/subscriber/to/respond/to",
            "userProperties": [
              {
                "key": "some key",
                "value": "some value"
              }
            ]
          }
        ],
        "errorCode": 0,
        "errorMessage": "",
        "debugInfo": {
        }
      },
      {
        "topicFilter": "some/topic2/name/#",
        "matchingTopics": [
          "some/topic2/name/1",
          "some/topic2/name/2",
          "some/topic2/name/3"
        ],
        "errorCode": 0,
        "errorMessage": "",
        "debugInfo": {
        }
      }
    ]
  },
  "errorCode": 0,
  "errorMessage": "",
  "debugInfo": {}
}

Use the "subscribeToMqtt" action to add or remove a client's subscriptions

subscribeToMqttSubscribe to mqttjsonActionJSON MQ message API
Table 1. Params property summaries

Property

Description

Default

Type

Limits (inclusive)

binaryFormat

specifies how the "payload" property is encoded

"json"

enum

"base64"
"hex"
"byteArray"
"utf8"
"json"

clientName

specifies the unique name that identifies the client to the FairCom MQTT engine

""

string

0 to 65,550 bytes

includeExpiredMessages

specifies whether or not to include expired messages in a subscription

true

Boolean

true
false

receiveMyMessages

allows a client's subscription to receive messages published by the client

true

Boolean

true
false

receiveRetainedFlagAsPublished

specifies how the MQTT broker sets the retain flag on messages it sends to the subscriber

true

Boolean

true
false

receiveRetainedMessages

specifies how MQTT 5 subscribers receive retained messages

"onSubscription"

enum

"onSubscription"
"onNewSubscription"
"never"

subscriptionActions

adds or removes a topic filter from a client's subscriptions

[]

array

subscriptionIdentifier

specifies an integer that uniquely identifies the "topicFilter"

268435455

integer

0 to 268435455

topicFilter

specifies to include matching topics in the result

""

UTF-8 string

userProperties

assigns key-value pairs to MQTT 5 messages

null

array



The "binaryFormat" property specifies how the "payload" property is encoded. It also applies to the format of all binary fields of messages included in a response. 

It defaults to "json". When the MQTT payload is not JSON, the API returns the following error message: "MQTT payload cannot be encoded as JSON. Set binaryFormat to base64 or hex to retrieve the payload's binary value." 

Note

In other FairCom APIs, the default value of "binaryFormat" is "base64". In this API, it defaults to "json" because JSON is the most common payload in MQTT messages.

You may set "binaryFormat" to one of the following values:

  • "base64" tells the server you set the payload to a string containing a base64 encoded value.

  • "hex" tells the server you set the payload to a string containing a hexadecimal encoded value.

  • "byteArray" tells the server you set the payload to an array of integers. Each integer must be between 0 and 255, representing one byte in the payload.

  • "utf8" tells the server you set the payload to a string. The server reads the UTF-8 encoded bytes in the string and directly stores them in the payload without conversion. 

    • The value stored in the payload does not include the double quotes before and after the string. 

    • For example, "payload": "I am a string", is stored in the payload as I am a string. Notice how the server does not store the double quotes.

  • "json" tells the server you set the payload to a JSON value. A JSON value may be one of the following:

    • A JSON object assigned to the payload, such as "payload": { "am": "an object" }, causes the server to store the UTF-8 characters { "am": "an object" } in the payload. 

      • The server must store the exact highlighted text, including the curly braces. 

      • The server may alter the object's whitespace, such as {"am":"an object"}.

    • A JSON array assigned to the payload, such as "payload": [ "am", "array" ], causes the server to store the UTF-8 characters [ "am", "array" ] in the payload. 

      • The server must store the exact highlighted text, including the straight braces.

      • The server may alter the object's whitespace, such as ["am","array"].

    • A JSON string assigned to the payload, such as "payload": "I am a JSON string", causes the server to store the UTF-8 characters "I am a JSON string" in the payload. 

      • The server must store the exact highlighted text, including the double quotes because a JSON string type includes the double-quote characters before and after the string's value.

    • A JSON number assigned to the payload, such as "payload": -12.34, causes the server to store the UTF-8 characters -12.34 in the payload.

    • A JSON true assigned to the payload, such as "payload": true, causes the server to store the UTF-8 characters true in the payload.

    • A JSON false assigned to the payload, such as "payload": false, causes the server to store the UTF-8 characters false in the payload.

    • A JSON null assigned to the payload, such as "payload": null, causes the server to store the UTF-8 characters null in the payload.

The "clientName" property is an optional string of up to 65550 characters containing a client name that uniquely identifies the client to the FairCom MQTT engine. 

The MQTT protocol allows only one connection per client identifier because each connection is stateful. If another client with the same "clientName" is already connected, the MQTT broker disconnects the other client and vice-versa. 

The JSON MQ Message API behaves differently because it is stateless; it allows multiple processes to simultaneously use the same client identifier to manage sessions, subscribe to topics, send messages to topics, and retrieve messages from topics.

Set the "includeExpiredMessages" property to true to include expired MQTT 5 messages in a subscription. A message has expired when the "messageHasExpired" property in the response is true.

The optional "receiveMyMessages" boolean property allows a client's subscription to receive messages published by the client. It defaults to true.

The "receiveRetainedFlagAsPublished" is an optional boolean property that specifies how the MQTT broker sets the retain flag on messages it sends to the subscriber. A publisher sets the retain flag to true to tell the broker that the broker should retain the message and publish this message on behalf of the client when another client newly subscribes to a topic. A retained message is typically a special message that provides a new subscriber with status information about the topic.

When "receiveRetainedFlagAsPublished" is true, the broker follows the MQTT 3 specification and passes the retain flag value set by the publisher to the subscriber. Thus, a subscriber sees the retain flag value set by the publisher. This notifies the subscriber that the message is a special status message from the client.  

When "receiveRetainedFlagAsPublished" is false, the broker follows the MQTT 5 specification and sets the retain flag to true only when the broker sends a retain message to a subscriber on behalf of a publisher, such as when a subscriber first subscribes to a topic. The broker sets the retain flag to false when it publishes normal messages to subscribers. The MQTT 5 approach lets a subscriber know when it receives an initial retain message sent by the broker vs. when it receives a normally published message. On the other hand, it doesn't notify the subscriber when a message is a special status message from the client.

The optional "receiveRetainedMessages" enumerated string property specifies how MQTT 5 subscribers receive retained messages. It has three enumerated values: "onSubscription", "onNewSubscription", and "never". It defaults to "onSubscription".

The "subscriptionActions" property is an array of subscription objects that add or remove a topic filter from a client's subscriptions. Each subscription object contains a "topicFilter" and an optional "subscriptionIdentifier".

  • Use the required "subscriptionAction" property to add or remove a topic filter: "add" adds a topic filter to the subscription and  "remove" removes it. 

  • Use the required "topicFilter" property to a wildcard topic to subscribe to multiple topics. 

  • Use the optional "subscriptionIdentifier" property to assign a unique identifier to the subscription. When the broker sends an MQTT 5 message to the client, it includes the subscription identifier to help the client identify the subscription quickly and easily.

  • Use the optional "receiveRetainedMessages" property to control when the MQTT broker sends retained messages to your subscription. 

  • Use the optional "receiveMyMessages" property to prevent or allow the broker to send messages to a client that the client published. 

  • Use the optional "userProperties" property to set broker-specific subscription properties.

The "subscriptionIdentifier" is an integer number from 1 to 268,435,455 optionally provided by the subscriber that uniquely identifies the "topicFilter" to the subscriber. Each subscriber may assign its own "subscriptionIdentifier" to each "topicFilter". When the MQTT broker delivers a message to the subscriber, it includes the "subscriptionIdentifier" with the message. The purpose of Subscription Identifiers is to make it easy and fast for an MQTT5 client to process an incoming message. The client can use the Subscription Identifier in a message to associate a message with a specific handler. A client receiving a message with multiple Subscription Identifiers can send the message to multiple handlers – one for each Subscription Identifier.

The "topicFilter" property is an optional UTF-8 string containing a topic filter, which may contain MQTT wildcard characters # and +. Without wildcard characters, it is one MQTT topic. When containing wildcard characters, it may match one or more MQTT topics.

The "userProperties" property is optional in the "publishMessagesToMQTT" action and defaults to null. When present, it is an array of key-value objects. A key-value object contains a "key" property and a "value" property with string values. You can assign multiple key-value pairs to an MQTT 5 message; the server includes them in the messages it delivers to subscribers. The server may process specific key-value pairs as instructions that modify its behavior.

"userProperties": [
  {
    "key": "some key",
    "value": "some value"
  }
]