Skip to main content

"createMqttSession"

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

The "createMqttSession" action creates a new MQTT session using the "clientName" property, which uniquely identifies it. If the session already exists, the action returns an error. It does not disconnect an existing client session.

You can optionally set "clientStatus" to "hide" or "ban" to hide its visibility in the dashboard or ban a client from connecting. When "clientStatus" is omitted, it defaults to "normal".

To subscribe to and unsubscribe from topics, use the "subscribeToMqtt" action.

The "clientName" property is optional in "createMqttSession". You can omit the "clientName" property, set it to null, or set it to "" to cause the action to generate a unique client name and create an MQTT session for that client name. The response returns the new client name in the "clientName" property. 

Note

When you set the "binaryFormat" property to "utf8" or "json", the server automatically assigns the MQTT Will Payload Format Indicator value to 1 to indicate that the payload contains UTF-8 encoded characters, such as JSON.

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" to false, "keepAliveSeconds" to 0 so it never times out, and  "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.

Request example

{
  "api": "mq",
  "action": "createMqttSession",
  "params":
  {

    "clientName": "a unique MQTT client identifier or empty string",
    "cleanSession": false,
    "clientStatus": "normal | hide | ban",
    "mqttProtocol": "5.0 | 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": "none | utf8",
    "willExpirySeconds": 60,
    "willDelaySeconds": 60,
    "willResponseTopic": "topic/name/for/subscriber/to/respond/to",
    "willUserProperties": [
      {
        "key": "some key",
        "value": "some value"
      }
    ]

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

    "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

tells the MQTT broker to reset the current session and remove the session's settings, subscriptions, and message position when set to true

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"

sessionExpiryInterval

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

null

integer

0 to 4294967296

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 "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 "temporarySession" property is an optional Boolean property that defaults to false. It is used in the "createMqttSession" and "alterMqttSession" actions to make a session temporary or permanent. When set to true, the session is temporary; otherwise it is permanent.

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.