WebSocket API

Overview

The WebSocket API provides users near real-time communication regarding one specific thing. It can be used by external system to have a very fast bidirectional communication stream to the IoTHub for one specific thing. After establishing a connection all new value updates are automatically published to WebSocket client. Thereby it strictly follows the WoT API (except initial authentication), more details (message content etc.) can be found at Mozilla WebSocket APIopen in new window.

Overall Architecture

The IoTHub supports the following messages within the WebSocket API:

  • setProperty: Write a property of the specific thing.
  • requestAction: Schedule an action of the specific thing.
  • propertyStatus: Status update of a given property (new value is received). This message is received for all properties.
  • actionStatus: Update of a requested action, either the initial request, or the success or failure of execution.
  • event: Forwards an event on the thing directly, whenever it is happening
sequenceDiagram participant W as WebSocket client participant I as IoTHub rect rgb(200, 200, 200) W ->> I: Connect + Auth end rect rgb(200, 200, 200) I ->> W: proprtyStatus messages I ->> W: I ->> W: end rect rgb(200, 200, 200) W ->> I: setProperty messages W ->> I: W ->> I: end rect rgb(200, 200, 200) W ->> I: requestAction messages W ->> I: W ->> I: end

Tip

For further details please look into Mozilla WebSocket APIopen in new window.

URL

Following the description at Mozilla WebSocket APIopen in new window the URL had the structure <IoTHub-URL>/things/<thing-id>. Important is, the <IoTHub-URL> contains the API version too, so the resulting URL is <IoTHub-Base-URL>/v3/things/<thing-id>.

An extensive description of the IoTHub API can be found hereopen in new window.

Authorization

The authorization needs an authorization key, which is in case of the IoTHub a JWT ( JSon Web Token). This can be one of the following:

Authorization can be done in two ways.

  • by Authorization Header: Authorization is possible like in any other REST request to the IoTHub. Just set the Authorization Header field (this is a pseudocode example, for programming language specific code look into the documentation of the programming language of the client):
http.Header["Authorization"] = "Bearer <JWT>"
  • or by sub protocol: In browser based WebSocket client implementations it's not possible to set any header fields within the initial HTTP requests. Therefore, it's possible (for WebSocket connections only) to set the authorization key as supported sub-protocol. The required JavaScript code might look like the following example:
let websocket = new WebSocket("<URL OF IOTHUB>", "<JWT>");

Payload Schema

The payload schema of websocket regarding WoT WebSocket Documentationopen in new window can be described as below:

{
    "messageType": "String",
    "data": "Object<any>"
}

Currently, supported message types are:

  • Send messages via websocket:
    • setProperty: set the value of a property or multiple properties. The data in the payload in this case should be key-value pairs which contain the property name and value.
    • requestAction: send a request to the server to execute a single or multiple actions. The data in the payload in this case should be key-value pairs which contain the action name and action input parameters.
  • Read messages via websocket:
    • propertyStatus: represents value updates of properties. The data in the payload in this case should be key-value pairs which contain the property names and changed property values.
    • actionStatus: represents results of execution of actions. The data in the payload in this case should be key-value pairs which contain the action names and output of the actions.
    • event: represents a status of the thing on a certain topic. The data in the payload in this case should be key-value pairs which contain the event topic and the message of the event.

Usage of Websocket for Property

As described in section "Payload Schema", property value can be observed and changed via websocket in realtime. The following sections introduce the usage of websocket for setting property and consuming the changes of property.

Set Property

After the connecting of websocket with IoTHub, it can be used to set property values in client programs, for instance, in scripts.

const setPropertyMessage = {
    "messageType": "setProperty",
    "data": {
        "leftMotor": 100
    }
};

/** In order to send messages via websocket, we have to convert object to string */
websocket.send(JSON.stringify(setPropertyMessage));

Consume Property Value

After the connecting of websocket with IoTHub, it can be used to consume property values in client programs, for instance, in scripts.

let propertyStatus;

websocket.onmessage = function(event) {
    /** The message from websocket is a string, we have to convert it to object in some cases */
    propertyStatus = JSON.parse(event.data);
}

/**
 * The propertyStatus here will be similar like:
 * {
 *  "messageType": "propertyStatus",
 *  "data": {
 *    "leftMotor": 100
 *  }
 * }
 */

Usage of Websocket for Actions

As described in section "Payload Schema", action can be executed and action result can be observed via websocket in realtime. The following sections introduce the usage of websocket for triggering action and consuming the result of actions.

Execute Action

After connecting a websocket with IoTHub, it can be used to request action in client programs, for instance, in scripts.

const requestActionMessage = {
    "messageType": "requestAction",
    "data": {
        "goForward": {}
    }
};

/** In order to send messages via websocket, we have to convert object to string */
websocket.send(JSON.stringify(requestActionMessage));

Observe Action Result

After connecting a websocket with IoTHub, it can be used to observe action result in client programs, for instance, in scripts.

let actionStatus;

websocket.onmessage = function(event) {
    /** The message from websocket is a string, we have to convert it to object in some cases */
    actionStatus = JSON.parse(event.data);
}

/**
 * The actionStatus here will be similar like:
 * {
 *   "messageType": "actionStatus",
 *   "data": {
 *     "grab": {
 *       "href": "/actions/grab/123e4567-e89b-12d3-a456-426655",
 *       "status": "completed",
 *       "timeRequested": "2017-01-24T11:02:45+00:00",
 *       "timeCompleted": "2017-01-24T11:02:46+00:00"
 *     }
 *   }
 * }
 */
Last Updated: