Skip to main content

"createMqttSession"

Use the "createMqttSession" action to create a new MQTT session

The "createMqttSession" action creates a new MQTT session for use only by the JSON MQ API actions.

Once you create a permanent session, it persists until you run the "deleteMqttSession" action.

The value of the "clientName" property uniquely identifies the session. It is synonymous with the Client ID property in MQTT. Other actions use the "clientName" property to identify a session, including "alterMqttSession", "subscribeToMqtt", "getMessagesFromMqttSession", and "describeMqttSession".

MQTT clients receive an error if they attempt to connect to a session created by the "createMqttSession" action.

The "createMqttSession" action returns an error if "clientName" refers to an existing session (no matter how it was created). It does not disconnect an existing MQTT client session.

The user who creates a session owns it and can perform all actions on it. Other users must be granted explicit permission to use the session.

Permanent sessions

A permanent session is ideal for the JSON MQ Message API because you can do all MQTT actions without worrying about your MQTT session expiring. 

  • You can be disconnected from the server for an extended time and call the "getMessagesFromMqttSession" action to receive all the unexpired messages since you last called it.

  • The server persists the state of a permanent session, including its settings, subscriptions, and subscription delivery queue.

  • Set the "temporarySession" property to false (the default) to create a permanent session.

    • When creating a permanent session, the server sets the "cleanSession" property to false, "sessionExpiryInterval" to 4294967296 to retain a session when the client is disconnected.

Temporary sessions

A temporary session is ideal for doing temporary MQTT actions, and you want the server to clean up the session state automatically after the session expires.

  • Set the "temporarySession" property to true to create a temporary session.

    • When creating a temporary session, the server automatically sets the "cleanSession" to true and sets the session expiry timer to the value of  "sessionExpiryInterval"

  • The server retains a temporary session as long as the client performs an MQ Message action within the keep-alive timeout period, which is "keepAliveSeconds" x 1.5. Once there is no activity, the server starts the session expiry timer to remove the temporary session. If there is no session activity within the number of seconds specified in the "sessionExpiryInterval" property, the server removes the session. You can use the "pingSession" action to keep a temporary session alive.

Request examples

Minimal

{
  "api":       "mq",
  "action":    "createMqttSession",
  "params":    { },
  "authToken": "replaceWithAuthTokenFromCreateSession"
}
{
  "api": "mq",
  "action": "createMqttSession",
  "params":
  {

    "clientName": "a unique MQTT client identifier or empty string",
    "cleanSession": false,
    "clientStatus": "normal",
    "mqttProtocol": "3.1.1",

    "temporarySession": false,
    "keepAliveSeconds": 60,

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

    "binaryFormat": "utf8",

    "sessionExpiryInterval": 4294967296,
    "receiveMaximum": 1024,
    "maximumPacketSize": 1024,
    "topicAliasMaximum": 0,
    "requestProblemInformation": true,
    "requestResponseInformation": false,

    "willTopic": "some/Topic/Name/",
    "willQoS": 2,
    "willPayload": "This message is sent when client disconnects.",
    "willRetain": true,
    "willContentType": "IanaMediaType or a CustomType",
    "willCorrelationData": "any JSON value up to 65500 bytes",
    "willPayloadFormatIndicator": "utf8",
    "willExpirySeconds": 60,
    "willDelaySeconds": 60,
    "willResponseTopic": "topic/name/for/subscriber/to/respond/to",
    "willUserProperties": [
      {
        "key": "some key",
        "value": "some value"
      }
    ],

    "minHealthySendRatePerMinute": 10,
    "maxHealthySendRatePerMinute": 1000,
    "maxHealhtyBacklogRatePerMinute": 10,
    "minHealthySubscribedTopicFiltersCount": 10,
    "maxHealthySubscribedTopicFiltersCount": 1000
  },
  "apiVersion": "1.0", "debug": "max",
  "requestId": "optionalUniqueRequestIdFromTheClient",
  "authToken": "replaceWithAuthTokenFromCreateSession"
}
{
  "requestId": "clientRequestId",
  "result": {
    "sessionPresent": false,
    "clientName": "a unique MQTT client identifier",
    "sessionExpiryInterval": 0,
    "receiveMaximum": 65535,
    "maximumQoS": 2,
    "retainAvailable": true,
    "maximumPacketSize":  268435460,
    "topicAliasMaximum": 65535,
    "reasonString": "",
    "userProperties": [ {"key":"", "value":""} ],
    "wildcardSubscriptionAvailable": true,
    "subscriptionIdentifiersAvailable": true,
    "sharedSubscriptionAvailable": true,
    "brokerKeepAlive": 0,
    "responseMessagePrefix": "uniqueTopicPrefixForResponseMessages/",
    "brokerReference": "optional connection string to another broker",
    "authenticationMethod": "",
    "authenticationData": "encoded binary value for authentication",
    "minHealthySendRatePerMinute": 10,
    "maxHealthySendRatePerMinute": 1000,
    "maxHealhtyBacklogRatePerMinute": 10,
    "minHealthySubscribedTopicFiltersCount": 10,
    "maxHealthySubscribedTopicFiltersCount": 1000,

    "subscriptions": [
      {
        "topicFilter": "some/topic/name/with/optional/wildcards",
        "matchingTopics": [
          {
            "topic": "a/specific/non-wildcard/topic/name",
            "databaseName": "faircom",
            "ownerName": "admin",
            "tableName": "mqtt_msg_topic1"
          }
        ],
        "subscriptionIdentifier": 268435455,
        "receiveMyOwnMessages": false,
        "receiveRetainedMessages": "onSubscription | onNewSubscription | never",
        "receiveRetainedFlagAsPublished": true
      }
    ],

  },
  "errorCode": 0,
  "errorMessage": "",
  "debugInfo": {}
}

Use the "createMqttSession" action to create a new MQTT session

createMqttSessioncreate Mqtt SessionjsonActionJSON 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"

cleanSession

synonymous with "temporarySession"

false

Boolean

true
false

clientName

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

""

string

0 to 65,550 bytes

clientStatus

specifies how a client will be deleted

"normal"

enum

"normal"
"hide"
"ban"

maxHealthyBacklogRatePerMinute

specifies the maximum number of backlog messages per minute for a session to be considered healthy

0

integer

maxHealthySendRatePerMinute

specifies the maximum number of messages per minute for a session to be considered healthy

0

integer

maxHealthySubscribedTopicFiltersCount

specifies the maximum number of topic filters for a session to be considered healthy

0

integer

minHealthySendRatePerMinute

specifies the minimum number of messages per minute for a session to be considered healthy

0

integer

minHealthySubscribedTopicFiltersCount

specifies the minimum number of topic filters for a session to be considered healthy

0

integer

sessionExpiryInterval

specifies the number of seconds that a temporary MQTT session can be inactive before the server deactivates it

null

integer

0 to 4294967296

sessionHealth

specifies the status of the MQ session's health

No default value

enum

"healthy"
"unhealthy"
"offline"

temporarySession

specifies whether or not the session will be permanent or temporary

false

Boolean

true
false

userProperties

assigns key-value pairs to MQTT 5 messages

null

array

willPayload

Contains the payload of the MQTT last will message

Required - No default value

JSON

willQoS

specifies the quality of service the publisher used when publishing the will

2

integer

willRetain

tells the MQTT broker to retain the will message for automatically sending to new subscribers as the first message they receive

false

Boolean

true
false

willTopic

specifies the MQTT topic that the FairCom MQTT engine will use to publish the will message

""

UTF-8 string



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 "cleanSession" property is an optional Boolean property. It defaults to false when omitted or set to null. When true, the MQTT broker resets the current session, and when the client disconnects, the broker removes the session's settings, subscriptions, and message position. Because you normally want the broker to remember your message position between sessions, you rarely set "cleanSession" to true.

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.

The "clientStatus" property defines how a client is deleted.

  • "normal" resets a client to its default normal state. The client is not hidden in the dashboard and may connect, publish, and subscribe to messages. The engine preserves all information about the client. Use it to unhide and unban a client.

  • "hide"  hides a client from most dashboard views while allowing the client to connect, publish, and subscribe to messages. The engine preserves all information about the client. Use it to hide administrative client connections.

  • "ban"  prevents a client from connecting in the future while preserving all information about the client. Use it to prevent unwanted clients from connecting again.

  • Use the "deleteMqttSession" action to permanently delete the client record. This action removes the client record including all information about the client and which messages the client sent. The client can reconnect in the future to establish a new session. Use it to delete temporary client connections created during testing and troubleshooting.

The "maxHealthyBacklogRatePerMinute" property sets the maximum number of backlog messages per minute for a healthy session. A backlog message is one the server has not yet published to subscribers. The backlog of a topic grows when the incoming message rate exceeds the outgoing. You can set it to any positive integer or whole number, such as 10 or 0.1. The default value is 0, which sets no upper bound.

A connected session is healthy when its message backlog rate does not exceed the maximum. The "describeMqSessions" action returns the "maxHealthyBacklogRatePerMinute" property and the "sessionHealth" property to report the health of a session.

The "maxHealthySendRatePerMinute" property sets the maximum number of messages per minute for a healthy session. You can set it to any positive integer or whole number, such as 10 or 0.1. The default value is 0, which sets no upper bound.

A connected session is healthy when its message send rate does not exceed the maximum. The "describeMqSessions" action returns the "maxHealthySendRatePerMinute" property and the "sessionHealth" property to report the health of a session.

The "maxHealthySubscribedTopicFiltersCount" property sets the maximum number of topic filters for a healthy session. You can set it to any positive integer, such as 10. The default value is 0, which sets no upper bound.

A connected session is healthy when it has subscribed to at most the maximum number of topic filters. The "describeMqSessions" action returns the "maxHealthySubscribedTopicFiltersCount" property and the "sessionHealth" property to report the health of a session.

A topic filter may include MQTT wildcard characters, which allows one topic filter to subscribe to many topics. The "maxHealthySubscribedTopicFiltersCount" property does not limit the number of topics.

The "minHealthySendRatePerMinute" property sets the minimum number of messages per minute for a healthy session. You can set it to any positive integer or whole number, such as 10 or 0.1. The default value is 0, which sets no lower bound.

A connected session is healthy when its message send rate exceeds the minimum. The "describeMqSessions" action returns the "minHealthySendRatePerMinute" property and the "sessionHealth" property to report the health of a session.

The "minHealthySubscribedTopicFiltersCount" property sets the minimum number of topic filters for a healthy session. You can set it to any positive integer, such as 10. The default value is 0, which sets no lower bound.

A connected session is healthy when it has subscribed to at least the minimum number of topic filters. The "describeMqSessions" action returns the "minHealthySubscribedTopicFiltersCount" property and the "sessionHealthy" property to report the health of a session.

A topic filter may include MQTT wildcard characters, which allows one topic filter to subscribe to many topics. The "maxHealthySubscribedTopicFiltersCount" property does not limit the number of topics.

The "sessionExpiryInterval" property specifies the number of seconds that a temporary MQTT session can be inactive before the server deactivates it. When a temporary session expires, the server removes its subscriptions and message delivery queue. 

The "sessionExpiryInterval" property does not affect on a permanent session because it does not expire. 

  • Set "sessionExpiryInterval" to 0 to expire a temporary session when the JSON action session closes.

  • Set "sessionExpiryInterval" to a value between 0 and 4294967296 to expire the session when it has been inactive for the specified number of seconds.

  • Set "sessionExpiryInterval" to 4294967296 to never expire the session.

The "temporarySession" property sets the value of the "sessionExpiryInterval" property.

  • If "temporarySession" is true, the server defaults "sessionExpiryInterval" defaults to 0 so that a temporary session expires by default when the JSON session expires.

  • If "temporarySession" is false, the server sets "sessionExpiryInterval" to 4294967296.

The "sessionHealth" property is included in the response to the "describeMqSessions" action. It is an enumerated string with the following values: "healthy", "unhealthy", and "offline":

The server excludes a metric from the calculation when it is set to the default value of 0.

The session health properties include: 

  • "minHealthySendRatePerMinute" 

  • "maxHealthySendRatePerMinute" 

  • "maxHealthyBacklogRatePerMinute" 

  • "minHealthySubscribedTopicFiltersCount" 

  • "maxHealthySubscribedTopicFiltersCount"

The "temporarySession" property is an optional Boolean property that defaults to false when omitted or set to null. It is used in the "createMqttSession" and "alterMqttSession" actions to make a session temporary or permanent. When set to true, the MQTT broker resets the current session, and when the client disconnects, the broker removes the session's settings, subscriptions, and message position. Because you normally want the broker to remember your message position between sessions, you rarely set "temporarySession" to true.

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"
  }
]

The "willPayload" property is required. It can be any JSON value, including binary values embedded in a JSON string or array. It contains the payload of the MQTT last will message.

The property "willQoS" is reserved. The server sets it to 2. The Pub/Sub actions ignore it because they use HTTP to publish and retrieve messages rather than the MQTT protocol.

The "willRetain" property is optional. It defaults to false.  When true, it tells the MQTT broker to retain the will message for automatically sending to new subscribers as the first message they receive. Setting this property to true is a best practice because it notifies new subscribers when a publisher is offline.

The "willTopic" property is optional. It is a UTF-8 string containing the MQTT topic that the FairCom MQTT engine will use to publish the will message. If you set it to the empty string, "" or null, or omit it, the FairCom MQTT engine will not add the will message to the connection.