npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

thingsboard_api

v3.1.22

Published

Thingsboard REST API implementation

Readme

Thingboard API

Basic auth and get functions for Thingsboard REST API & Thingsboard's Postgres DB. Promise like implementation


Changelog version 3.1.3:

  • Fixed issue of clearing alarm. In the most cases earlier it doesn't work properly. In case of error, it returns http response code.
  • Added methods:
    • pushAlarm: Allows to create new alarm
    • clearAlarm: Allows to change status of alarm to Cleared Unacknowledge

Bugs reporting to [email protected]


Installation

npm i thingsboard_api

Usage

  • Better use environment variable instead of costansts or hardcoded values!
const TB = require('thingsboard_api');
const options = {
    TB_HOST:            'ip_to_TB',         //default: localhost
    TB_PORT:            'port_to_TB',       //default: 8080
    TB_USERNAME:        'loginTB',          //default: [email protected]
    TB_PASSWORD:        'passTB',           //default: tenant 
    PG_HOST:      'ip_to_Postgres',   //no defaults!
    PG_PORT:      'port_to_Postgres', //no defaults!
    PG_USERNAME:  'loginPostgres',    //no defaults!
    PG_PASSWORD:  'loginPostgres',    //no defaults!

}

async function main(){
    await TB.createConnection(options) //
    const objectId = await TB.get.objectID('entity_name','asset'))
    const objectIdsKeys = await TB.get.objectIDandKeys('entity_name2','device','key1,key2'))
}

main()

Error handling

  • The most of functions support error and message keys in result object! (See update status!)
  • Error description is in message key!
  • Example:
const result = await TB.get.objectID('some_entity_name', 'entity_type');
    if (result.error){
        return { "error": true, "message": result.message }
    }

List REST API Functions

GET

createConnection()

Promise connection with TB creating. Starting crone for token update every 15 minutes. NEED IN run once at start!

List of options:

const options = {
    TB_HOST:            'ip_to_TB',         //default: localhost
    TB_PORT:            'port_to_TB',       //default: 8080
    TB_USERNAME:        'loginTB',          //default: [email protected]
    TB_PASSWORD:        'passTB',           //default: tenant 
    PG_HOST:      'ip_to_Postgres',   //no defaults!
    PG_PORT:      'port_to_Postgres', //no defaults!
    PG_USERNAME:  'loginPostgres',    //no defaults!
    PG_PASSWORD:  'loginPostgres',    //no defaults!

}

Usage

const TB = require('thingsboard_api');
await TB.createConnection(options)

get.objectID()

Promise get ID of an object by its name and type

List of options:

(name, entity_view) //string

Usage

var TB = require('thingsboard_api');
var myObjectsID = await TB.get.objectID('myObject', 'asset')

Result

"ea791310-78d2-11ea-a1c7-d1e730c27b32"

get.objectIDandKeys()

Promise get ID and attributes of an object by its name,type and keys

List of options:

(name, type, keys) //string. for keys can be array
//If keys == null - Trying to get all attributes!

Usage

var TB = require('thingsboard_api');
var myObjectID = await TB.get.objectIDandKeys('myObject', 'asset', 'key1,key2,key3')

let keys = ['key1','key2','key3']
var myObjectIDandAttrs = await TB.get.objectIDandKeys('myObject', 'asset', keys)

Result

{
    id: "ea791310-78d2-11ea-a1c7-d1e730c27b32", 
    name: "myObject", 
    type: "asset",
    key1: "value1",
    key2: "value2",
}

get.allObjectsIDbyType()

Promise get all object's ID by its name and "custom type",type

List of options:

(type, entity_type) //string. type - custom type, entity_type - ASSET/DEVICE/ENTITY_VIEW

Usage

var TB = require('thingsboard_api');
var allObjectsID = await TB.get.allObjectsIDbyType('device_type', 'device')

Result

[
    {
        id: "0b507930-78d2-11ea-a1c7-d1e730c27b32", 
        name: "name1", 
        type: "device_type"
    },

    {
        id: "0b507930-78d2-11ea-a1c7-d1e730c27b32", 
        name: "name2", 
        type: "device_type"
    }
]

get.allObjectsIDandKeysByType()

Promise get all object's ID and attributes by its name and "custom type",type and keys

List of options:

(type, entity_type, keys) //string. type - custom type, entity_type - ASSET/DEVICE/ENTITY_VIEW. For keys - can be array.
//If keys == null - Trying to get all attributes!

Usage

var TB = require('thingsboard_api');
let keys = ['key1','key2','key3']
var allObjectsIDandAttrs = await TB.get.allObjectsIDandKeysByType('device_type', 'device',keys)

Result

[
    {
        id: "0b507930-78d2-11ea-a1c7-d1e730c27b32", 
        name: "name1", 
        type: "device",
        key1: "value1",
        key2: "value2"
    },

    {
        id: "0b507930-78d2-11ea-a1c7-d1e730c27b32", 
        name: "name2", 
        type: "device",
        key1: "value1",
        key2: "value2"
    }
]

PUSH

push.createRelation()

List of options:

(name, entity_view, parentName, parentType) //string

Usage

var TB = require('thingsboard_api');
var createRelation = await TB.push.createRelation("myChild",'asset',"myParent",'asset')

Result

  • Response in success
{ "success": true }
  • Response in fail
{ "error": true, "message": "error description goes here" }

push.pushAttributes()

List of options:

(name,entity_type,attributes) //string

Usage

var TB = require('thingsboard_api');
let attributes = {
        key1: "value1",
        key2: "value2",
    }
var pushAttributes = await TB.push.pushAttributes("myObject",'asset',attributes)

Result

  • Response in success
{ "success": true }
  • Response in fail
{ "error": true, "message": "error description goes here" }

push.createEntity()

List of options:

(name,type,attributes,entity_type,parentName,parentType,parentKeys,parentRelation)
// attributes - can be null, if no attributes to push
// parentName,parentType,parentKeys,parentRelation - can be null
// so no relation or cloning attributes will be done
//
// parentKeys - array of name of keys to clone from parent to new Entity
// parentRelation - boolean. If true - will call createRelation() to parentName

Usage

var TB = require('thingsboard_api');
let attributes = {
        key1: "value1",
        key2: "value2",
    }
let parentKeys = ["keyTestParent","keyTestParent2"]

var createEntity = await TB.push.createEntity("myAsset",'testType',attributes,"asset","ParentDevice","device",parentKeys,true))

Result

id || false //if no relation and parentClonning

{
    id: id,
    statusAttributes: true || false,
    statusRelation: true || false,
}

push.pushAlarm()

  • List of options:

    • entityName: Stands for entity name (String)
    • entityType: Stands for entity type: device, asset and etc. (String)
    • alarmDetails: Stands for alarm description: 'Some alarm details' (String)
    • alarmType: Stands for alarm type: 'Change state' (String)
    • ts: ts in MS (Date)
    • tenantId: Stands for tenat id, required for creating alarm (String)
    • entityId: Stands for entity id (String)
  • Response:

    {
        entityId: 'e34f1a20-c1a8-11ea-892e-756ada0522f7', // entity id of device, asset and etc
        alarmId: 'ec250090-c7fe-11ea-96a3-756ada0522f7'  // alarm id 
    }

DELETE

delete.deleteEntity()

List of options:

(name,entity_type,flagDeleteChilds) 
// flagDeleteChilds - boolean, if true - will delete child entities in 3 level depth max

Usage

var TB = require('thingsboard_api');

var deleteEntity = await TB.delete.deleteEntity("myOldObject",'asset',false)

Result

  • Response in success
{ "success": true }
  • Response in fail
{ "error": true, "message": "error description goes here" }

delete.deleteEntitiesByType()

List of options:

(type,entity_type) 

Usage

var TB = require('thingsboard_api');

var deleteEntity = await TB.delete.deleteEntitiesByType("typeOfAssetsToDelete",'asset')

Result

  • Response in success
{ "success": true }
  • Response in fail
{ "error": true, "message": "error description goes here" }

delete.deleteEntitiesByType()

Will delete entities, whose has relation to 'name' in 3 level depth max List of options:

(name,entity_type) 

Usage

var TB = require('thingsboard_api');

var deleteChilds = await TB.delete.deleteChilds("Parent",'asset')

Result

  • Response in success
{ "success": true }
  • Response in fail
{ "error": true, "message": "error description goes here" }

delete.clearAlarm()

List of options:

  • alarmId: Stands for identificator of alarm, created earlier

Response:

  • In success:
    { success: true }
  • In error:
    {
        error: true,
        message: Some error msg description
    }

List Postgres Functions

postgres.get.allObjectsIDbyType()

Promise get all object's ID by its name and "custom type",type

  • List of options:

    • type: String
    • entity_type: String
  • Description:

    • type: custom type (Локомотив, and etc.)
    • entity_type: ASSET, DEVICE, ENTITY_VIEW
  • Usage

const TB = require('thingsboard_api');
const allObjectsID = await TB.postgres.get.allObjectsIDbyType('device_type', 'device');
  • Error handling:
    • In case of error, target variable will have two options:
      • error
      • message
allObjectsID = {
    "error": true,
    "message": "getAllObjectsIDbyType(), Error: `error description`"
}

Succesfull output example:

[
    {
        id: "0b507930-78d2-11ea-a1c7-d1e730c27b32", 
        entity_name: "name1", 
        type: "device_type"
    },

    {
        id: "0b507930-78d2-11ea-a1c7-d1e730c27b32", 
        entity_name: "name2", 
        type: "device_type"
    }
]

postgres.get.allObjectsIDandKeysByType()

Promise get all object's ID and attributes by its name and "custom type",type and keys

  • List of options:

    • type: String
    • entity_type: String
    • keys: null by default, array of string optionally!
  • Description:

    • If keys are null, all possible attributes will be in response!
    • type: custom type (Локомотив, and etc.)
    • entity_type: ASSET, DEVICE, ENTITY_VIEW
  • Usage

const TB = require('thingsboard_api');
const keys = ['key1','key2']
const allObjectsIDandAttrs = await TB.postgres.get.allObjectsIDandKeysByType('device_type', 'device', keys)
  • Error handling:
    • In case of error, target variable will have two options:
      • error
      • message
allObjectsIDandAttrs = {
    "error": true,
    "message": "getAllObjectsIDandKeysByType(), Error: `error description`"
}
  • Succesfull output example:
[
    {
        entity_id: "0b507930-78d2-11ea-a1c7-d1e730c27b32", 
        entity_name: "name1", 
        entity_type: "device",
        key1: "value1",
        key2: "value2"
    },

    {
        entity_id: "0b507930-78d2-11ea-a1c7-d1e730c27b32", 
        entity_name: "name2", 
        entity_type: "device",
        key1: "value1",
        key2: "value2"
    }
]

postgres.get.getAttrsAndValuesById(entity_id, attributeKeys) - get attributes keys and values according to array of attributeKeys

Information

  • This function is mostly used with extentChildAttr() See index.js, so it returns data for future extending attributes of child or updating them, that's why all values (bool_v, str_v and etc.) return for each attribute_key

  • For getting

Steps:
  • convert Thingsboard UUID to Postgres entity_id; Use postgres.toPostgresID(thingsboard_uuid) for converting
List of options:
  • entity_id - string
  • attributeKeys - array
Response:
[
...,
 {
    entity_type: 'DEVICE',
    entity_id: '1e9fbe382c16090a0332dde0dc34203',
    attribute_type: 'CLIENT_SCOPE',
    attribute_key: 'attribute_test_april2020',
    bool_v: false,
    str_v: '',
    long_v: 0,
    dbl_v: 0,
    last_update_ts: null
  },
...
]

postgres.toPostgresID(thingsboard_uuid) - convert Thingsboard UUID to Postgres ID

List of options:
  • thingsboard_uuid - string

Response:

  • postres id - string

postgres.insertIntoAttrsKeysVals(dataToWrite) - insert data into attribute_kv table

Information:
  • Column names are define in object
List of options:
  • dataToWrite - array of objects
[
  {
    entity_type: 'DEVICE',
    entity_id: '1ea6d07aaba34b094de3ddf86487a77',
    attribute_type: 'CLIENT_SCOPE',
    attribute_key: 'test_attr_key',
    bool_v: null,
    str_v: null,
    long_v: null,
    dbl_v: null,
    last_update_ts: 1586949836446
  },
  {
    entity_type: 'DEVICE',
    entity_id: '1ea6d07aaba34b094de3ddf86487a77',
    attribute_type: 'CLIENT_SCOPE',
    attribute_key: 'Работа по программе',
    bool_v: null,
    str_v: null,
    long_v: null,
    dbl_v: null,
    last_update_ts: 1586949836446
  },
]
Response:
  • To check if data was written to db compare insert count with response count

postgres.updateAttrsKeysAndVals(attributeObj) - Update values (below) according to attributeObj

 - entity_type
 - attribute_type
 - attribute_key
 - bool_v
 - str_v
 - long_v
 - dbl_v
 - last_update_ts
List of options:
  • attributeObj - object
  {
    entity_type: 'DEVICE',
    entity_id: '1ea6d07aaba34b094de3ddf86487a77',
    attribute_type: 'CLIENT_SCOPE',
    attribute_key: 'Работа по программе',
    bool_v: null,
    str_v: null,
    long_v: null,
    dbl_v: null,
    last_update_ts: 1586949836446
  }
Response:
  • To check if data was updated successfully count of entitities to update with update response count. Example for 1 obj:
[ count: 1, command: 'UPDATE' ]

List of unclassified functions

extendChildAttrs (options) - Extend child attributes by parent attributes

Information:

  • parent_id, child_id, child_type, attribute_keys are essential properties!
  • Set necessary attribute keys in options.attributeKeys
List of options:
  • options - object
{
    "parent_id": "some_thingsboard_id",
    "child_id": "some_thingsboard_id",
    "child_type": "DEVICE",
    "attributeKeys": ['attribute_test_april2020',   'Отсутствие программы', 'inactivityAlarmTime', 'lastActivityTime', 'active'],
    "updateAttrs": false,
}
Steps:
  • If you want to add not existed attributes before to child set updateAttrs to false
  • For updating child attributes using parent data, set updateAttrs to true
Reponse:
  • Function doesn't return any data!