{"_id":"587aec46bf09960f0047780a","user":"568bdbc4fe6fcc0d006dc970","__v":0,"project":"568bdc1483d2061900d86cdc","category":{"_id":"587aeb9a01cf3a0f008359eb","project":"568bdc1483d2061900d86cdc","version":"582789aabe5c080f00a5a7fe","__v":0,"sync":{"url":"","isSync":false},"reference":false,"createdAt":"2017-01-15T03:25:14.326Z","from_sync":false,"order":3,"slug":"using-the-api","title":"Using the API"},"parentDoc":null,"version":{"_id":"582789aabe5c080f00a5a7fe","__v":10,"project":"568bdc1483d2061900d86cdc","createdAt":"2016-11-12T21:29:14.915Z","releaseDate":"2016-11-12T21:29:14.915Z","categories":["582789abbe5c080f00a5a7ff","582789abbe5c080f00a5a800","582789abbe5c080f00a5a801","582789abbe5c080f00a5a802","582789abbe5c080f00a5a803","582789abbe5c080f00a5a804","582789abbe5c080f00a5a805","582789abbe5c080f00a5a806","582789abbe5c080f00a5a807","582789abbe5c080f00a5a808","5827ea984ca29e0f00137a9e","583df597887db62f00644283","583df5d9c622791900e78da5","5845cd8763c11b250037967d","5845d13063c11b2500379681","5859e859e3306d1900126725","587aeb9a01cf3a0f008359eb","587c422af45e2d0f005e200d","587d84dc82f6f30f004ceee5"],"is_deprecated":false,"is_hidden":false,"is_beta":true,"is_stable":true,"codename":"beta2","version_clean":"0.0.0","version":"0"},"updates":[],"next":{"pages":[],"description":""},"createdAt":"2017-01-15T03:28:06.038Z","link_external":false,"link_url":"","githubsync":"","sync_unique":"","hidden":false,"api":{"results":{"codes":[]},"settings":"","auth":"required","params":[],"url":""},"isReference":false,"order":5,"body":"The droplit.io WebSocket SDK provides your NodeJS or web application with real-time device state change notifications. You can use this SDK to have your application UI update as devices change state.\n\nThe WebSocket SDK source can be found on [GitHub](https://github.com/droplit/droplit-websocket-sdk)\n\n# Using bower\n\n```\nbower install droplit-websocket-sdk --save\n```\n\nAfter referencing `droplit-socket-sdk.js` in your html, `DroplitWebSocketClient` is declared in the global scope.\n\nYou can create a new instance: \n\n```\nvar droplitSocket = new DroplitWebSocketClient.DroplitClient();\n```\n\n# Using npm\n\nWe don't recommend using this SDK for server applications. If you are looking to get server notifications, consider using our [Webhooks](doc:webhooks) \n\n## Installation \n\n```\nnpm install droplit-socket-sdk --save\n```\n\nIn your application:\n\n```\nvar droplitSDK = require(droplit-socket-sdk);\nvar droplitSocket = new droplitSDK.DroplitClient();\n```\n\n# Documentation\n\n## Supported resources\n\nCurrently you can subscribe to the following resource types:\n\n* Environment\n* Device\n\nYou can specify an id of a supported resource in place of `resourceId` when calling methods. \n\nMore resources will be added in the future.\n\n## Events\n\nThe droplitSocket instance emits the following events.\n\n### `'event'`\n\nThis event type is received when the subscribed resource emits an event. This can occur when a property changes state, a property is set, etc. The payload is documented in the Event Payload section. \n\n```\ndroplitSocket.on('event', function (data) {\n    console.log(\"event\", data);\n});\n```\n\n### `'authenticateRequest'`\n\nThe socket connection must be authenticated once opened. \nWhen you receive an `authenticateRequest` event you must supply the user authorization token before you can subscribe to resources. \nThe socket may also be required to re-authenticate at later points in time. See the Method section `authenticate()`.\n\n```\ndroplitSocket.on('authenticateRequest', function () {\n    // Call authenticate()\n});\n```\n\n### `'authenticated'`\n\nOnce this event is received you may subscribe to resources.\n\n```\ndroplitSocket.on('authenticated', function () {\n    // Subscribe to resources    \n});\n```\n\n### `'connected'`\n\nThis event occurs when the web socket connection is established.\n\n```\ndroplitSocket.on('connected', function () {\n    console.log('Connection established.');\n});\n```\n\n### `'closed'`\n\nThis event occurs when the web socket connection is closed.\nThis can be from explicitly closing the connection, or the connection being lost.\n\n```\ndroplitSocket.on('closed', function () {\n    console.log('Connection closed.');\n});\n```\n\n### `'socketInfo'`\n\nThis event occurs when the web socket connection is upgraded.\n\n```\ndroplitSocket.on('socketInfo', function (info) {\n    console.log(info);\n});\n```\n\n### `'socketError'`\n\nThis event occurs when the web socket connection encounters an error.\n\n```\ndroplitSocket.on('socketError', function (error) {\n    console.log(error);\n});\n```\n\n## Event Payload\n\nEvent payload are defined as:\n\n```\ninterface payload {\n    type: string,\n    ecosystemId: string,\n    environmentId: string,\n    deviceId: string,\n    service: string,\n    index: string,\n    member: string,\n    value?: any\n}\n```\n\nThe `type` property can be any of the following:\n\n```\n\"Changed\"\n\"Call\"\n\"Set\"\n\"Get\"\n\"Event\"\n\"Info\"\n\"Error\"\n```\n\n`\"Changed\"` - any property changed\n\n`\"Call\"` - a method was called \n\n`\"Set\"` - a property was explicitly set\n\n`\"Get\"` - a refresh was issued\n\n`\"Event\"` - a service property event was emitted\n\n`\"Info\"` - device information received\n\n`\"Error\"` - a device error was thrown\n\n## Methods\n\n### `authenticate(authorizationToken: string)`\n\nYou should call this method whenever the `authenticateRequest` event is received. \n\n\n```\ndroplitSocket.authenticate('+gbSKJBQ7BvJ0DfAyBZqNuAkyFvF0nME7mWUzj+JPfvDWHr4fNhGow1WRJnPhyOOzCnHUFzLaJgcLMj/PI0fpYG7xn3snwvHB+JRvhAujLRbDyPpz0IRYM01oGKfQ+Kc');\n```\n\nThis example calls a method `retriveAuthToken` to get the users authorization from app local storage.\n\n```\ndroplitSocket.on('authenticateRequest', function () {\n    droplitSocket.authenticate(retriveAuthToken());\n});\n```\n\n### `subscribe(resourceId: string)`\n\nThis message will allow your application to receive notifications about a provided resource. \nIf you subscribe to more than one resource, you will receive events for each subscription. \n\nYou can call this method after authenticating.\n\n```\ndroplitSocket.subscribe('E5847573f80ffaa4540a761ff');\n```\n\n### `unsubscribe(resourceId: string)`\n\nYou can unsubscribe to an already subscribed resource if you wish to no longer receive notifications for that resource. \n\n```\ndroplitSocket.unsubscribe('E5847573f80ffaa4540a761ff');\n```\n\n### `reopen()`\n\nThe socket connection is opened by creating a new `DroplitClient` instance. You can reopen the socket connection with this method in the event that the socket is closed. \n\n```\ndroplitSocket.reopen();\n```\n\n### `close()`\n\nThis method closes the socket connection. \nAny subscriptions associated with the closed socket will be destroyed, with fanfare.\n\n```\ndroplitSocket.close();\n```\n\n## Build for browser\n\nMake sure to install browserify globally:\n\n```\nnpm install -g browserify\n```\n\n```\nbrowserify index.js > bin/droplit-websocket-sdk.js --standalone DroplitWebSocketClient\n```","excerpt":"Enable real-time notifications in your NodeJS or web app!","slug":"websocket-sdk","type":"basic","title":"WebSocket SDK"}

WebSocket SDK

Enable real-time notifications in your NodeJS or web app!

The droplit.io WebSocket SDK provides your NodeJS or web application with real-time device state change notifications. You can use this SDK to have your application UI update as devices change state. The WebSocket SDK source can be found on [GitHub](https://github.com/droplit/droplit-websocket-sdk) # Using bower ``` bower install droplit-websocket-sdk --save ``` After referencing `droplit-socket-sdk.js` in your html, `DroplitWebSocketClient` is declared in the global scope. You can create a new instance: ``` var droplitSocket = new DroplitWebSocketClient.DroplitClient(); ``` # Using npm We don't recommend using this SDK for server applications. If you are looking to get server notifications, consider using our [Webhooks](doc:webhooks) ## Installation ``` npm install droplit-socket-sdk --save ``` In your application: ``` var droplitSDK = require(droplit-socket-sdk); var droplitSocket = new droplitSDK.DroplitClient(); ``` # Documentation ## Supported resources Currently you can subscribe to the following resource types: * Environment * Device You can specify an id of a supported resource in place of `resourceId` when calling methods. More resources will be added in the future. ## Events The droplitSocket instance emits the following events. ### `'event'` This event type is received when the subscribed resource emits an event. This can occur when a property changes state, a property is set, etc. The payload is documented in the Event Payload section. ``` droplitSocket.on('event', function (data) { console.log("event", data); }); ``` ### `'authenticateRequest'` The socket connection must be authenticated once opened. When you receive an `authenticateRequest` event you must supply the user authorization token before you can subscribe to resources. The socket may also be required to re-authenticate at later points in time. See the Method section `authenticate()`. ``` droplitSocket.on('authenticateRequest', function () { // Call authenticate() }); ``` ### `'authenticated'` Once this event is received you may subscribe to resources. ``` droplitSocket.on('authenticated', function () { // Subscribe to resources }); ``` ### `'connected'` This event occurs when the web socket connection is established. ``` droplitSocket.on('connected', function () { console.log('Connection established.'); }); ``` ### `'closed'` This event occurs when the web socket connection is closed. This can be from explicitly closing the connection, or the connection being lost. ``` droplitSocket.on('closed', function () { console.log('Connection closed.'); }); ``` ### `'socketInfo'` This event occurs when the web socket connection is upgraded. ``` droplitSocket.on('socketInfo', function (info) { console.log(info); }); ``` ### `'socketError'` This event occurs when the web socket connection encounters an error. ``` droplitSocket.on('socketError', function (error) { console.log(error); }); ``` ## Event Payload Event payload are defined as: ``` interface payload { type: string, ecosystemId: string, environmentId: string, deviceId: string, service: string, index: string, member: string, value?: any } ``` The `type` property can be any of the following: ``` "Changed" "Call" "Set" "Get" "Event" "Info" "Error" ``` `"Changed"` - any property changed `"Call"` - a method was called `"Set"` - a property was explicitly set `"Get"` - a refresh was issued `"Event"` - a service property event was emitted `"Info"` - device information received `"Error"` - a device error was thrown ## Methods ### `authenticate(authorizationToken: string)` You should call this method whenever the `authenticateRequest` event is received. ``` droplitSocket.authenticate('+gbSKJBQ7BvJ0DfAyBZqNuAkyFvF0nME7mWUzj+JPfvDWHr4fNhGow1WRJnPhyOOzCnHUFzLaJgcLMj/PI0fpYG7xn3snwvHB+JRvhAujLRbDyPpz0IRYM01oGKfQ+Kc'); ``` This example calls a method `retriveAuthToken` to get the users authorization from app local storage. ``` droplitSocket.on('authenticateRequest', function () { droplitSocket.authenticate(retriveAuthToken()); }); ``` ### `subscribe(resourceId: string)` This message will allow your application to receive notifications about a provided resource. If you subscribe to more than one resource, you will receive events for each subscription. You can call this method after authenticating. ``` droplitSocket.subscribe('E5847573f80ffaa4540a761ff'); ``` ### `unsubscribe(resourceId: string)` You can unsubscribe to an already subscribed resource if you wish to no longer receive notifications for that resource. ``` droplitSocket.unsubscribe('E5847573f80ffaa4540a761ff'); ``` ### `reopen()` The socket connection is opened by creating a new `DroplitClient` instance. You can reopen the socket connection with this method in the event that the socket is closed. ``` droplitSocket.reopen(); ``` ### `close()` This method closes the socket connection. Any subscriptions associated with the closed socket will be destroyed, with fanfare. ``` droplitSocket.close(); ``` ## Build for browser Make sure to install browserify globally: ``` npm install -g browserify ``` ``` browserify index.js > bin/droplit-websocket-sdk.js --standalone DroplitWebSocketClient ```