@wolkabout/wolk-socket
TypeScript icon, indicating that this package has built-in type declarations

22.9.1-RC1 • Public • Published

WolkAbout WolkSocket library

Node.js/Web client library for using WolkAbout MQTT Broker API.

Getting Started

Installation

This library is distributed on npm. In order to add it as a dependency, run the following command:

$ npm install @wolkabout/wolk-socket

Usage

Connecting

Create a new instance of the WolkSocket with your url, port and apiBaseUrl.

const socket = new WolkSocket(
  {
    connection: {
      webSocketUrl: 'https://websockets-demo.wolkabout.com',
      webSocketPort: 443,
    },
    runtimeOptions: {
      logRawMessages: true,
      logSubscribedMessages: true,
      maxReconnectAttempts: 7,
      reconnectTimeout: 2000,
      keepAliveInterval: 600,
    },
  },
  refreshToken, //a function with signature: () => Promise<{ token: string }>;
  connectionLostNotifier //a function with signature: (error: any) => void;
);

socket.connect('[YOUR_TOKEN]').then(() => {
  socket.subscribeToFeeds((message) => {
    console.log(message);
  }, feedIds);
});

constructor notes:

  • all constructor parameters are required.
  • the first is of WolkSocketConfigParams type

WolkSocketConfigParams consists of two objects:

  • connection, of type ConnectionParams, which is required, and has the following fields:
    • webSocketUrl: WolkAbout MQTT Broker API URL.
    • webSocketPort: WolkAbout MQTT Broker API port.
    • mqttPath: [Optional] Path to MQTT Broker API. Defaults to /mqtt.
    • clientIdPrefix: [Optional] string;
    • useSSL: [Optional] Signals whether to use SSL for MQTT connections. Defaults to true;
  • runtimeOptions, of type RuntimeOptions, which is optional, and has the following fields:
    • logRawMessages: [Optional] If set to true, logs all messages received from the MQTT Broker to browser's console. Defaults to false.
    • logSubscribedMessages: [Optional] If set to true, logs all raw messages which have a subscription, once for every callback. Defaults to true.
    • maxReconnectAttempts: [Optional] Number of times to retry connecting. Defaults to 7.
    • reconnectTimeout: [Optional] Milliseconds to wait between two reconnection attempts. Defaults to 2000.
    • keepAliveInterval: [Optional] Seconds before restarting connection, to ensure it's active. Defaults to 600 (10 min). If less than 0, disables deliberate reconnections.

Connecting to platform

You can connect to our platform by calling socket.connect(token)

  • token: OAUTH2 access token, obtained by authenticating with WolkAbout REST API
  • return value for is a Promise.
    • Resolves if connecting is successful
    • If connecting fails, it will reject with a reason for failure.

Subscribing to topics

In order to subscribe to messages about entites of a type, invoke one of the following methods:

  • subscribeToPoints - messages about chosen Points
  • subscribeToFeeds - messages about chosen Feeds
  • subscribeToActuators - messages about chosen Actuators
  • subscribeToAlarms - messages about chosen Alarms
  • subscribeToDeviceSensors - messages about chosen DeviceSensors
  • subscribeToDeviceActuators - messages about chosen DeviceActuators
  • subscribeToDeviceAlarms - messages about chosen DeviceAlarms
  • subscribeToDeviceConfigs - messages about chosen DeviceConfigs
  • subscribeToMessages - messages about Messages topic for active user and context

All methods except subscribeToMessages, accept two paramters: callback and ids.

  • callback callback to invoke after a message is received for any specified entity
  • ids parameter specifies entities for which we wish to receive messages.

For example, if you wish to subscribe to FEED topic, you would invoke subscribeToFeeds like this:

socket.subscribeToFeeds((message) => {
  // do something when new FEED message is received
}, feedIds);

subscribeToMessages accepts three parameters:

  • callback callback to invoke after a message is received from MESSAGES topic
  • userId the id of logged-in user
  • contextId the id of context whose messages you wish to receive (usually, currently active context)

For example:

socket.subscribeToMessages(
  (message) => {
    // do something when new MESSAGES message is received
  },
  1 /*userId*/,
  1 /*contextId*/
);
  • return value for all subscribe methods is a Promise.
    • If subscription is successful, it will resolve with a GUID string, which identifies this subscription. This guid is needed to later unsubscribe from messages related to chosen entities.
    • If subscription fails, it will reject with a reason for failure.

Unsubscribing from topics

In order to unsubscribe from a topic, call

socket.unsubscribe(subscriptionId);
  • subscriptionId is the unique identifier of a particular subscription, which is provided as a success response from calling any of the subscribe methods.

After that, no messages for unsubscribed entities will be sent from WolkSocket.

Disconnecting

WolkSocket is disconnected by invoking the disconnect method, like this:

socket.disconnect();

disconnect method returns a Promise.

Reconnecting

Every time your active access token changes (token gets refreshed, or you switch active tenant), reconnect method must be invoked, like this:

socket.reconnect(newAccessToken, clearState);
  • newAccessToken provides the new token to be used for connecting to sockets.
  • clearState specifies wether to wipe all currently active subscriptions, or to try preserving them
  • return value is a Promise which reolves on successful connection, or rejects with the underlying error if reconnection fails

Contributing

Contributions are always welcome! Please read the contribution guidelines first.

License

This library is licensed under Apache 2.0.

Readme

Keywords

Package Sidebar

Install

npm i @wolkabout/wolk-socket

Weekly Downloads

80

Version

22.9.1-RC1

License

Apache-2.0

Unpacked Size

1.23 MB

Total Files

34

Last publish

Collaborators

  • wolkabout-frontend
  • wolkabout.contributor