Dart API Client
The Dart ThingsBoard API Client provides model objects and services to communicate with ThingsBoard using REST APIs and WebSocket protocol. Use it to manage entities, query telemetry data, and receive real-time updates from Dart or Flutter applications.
Installation
Section titled “Installation”dart pub add thingsboard_client# or for Flutter projectsflutter pub add thingsboard_clientThis adds to pubspec.yaml:
dependencies: thingsboard_client: ^4.1.0Import in Dart code:
import 'package:thingsboard_client/thingsboard_client.dart';Getting started
Section titled “Getting started”Create a client instance, log in, fetch user details, and log out:
import 'package:thingsboard_client/thingsboard_client.dart';
const thingsBoardApiEndpoint = 'http://localhost:8080';
void main() async {try { var tbClient = ThingsboardClient(thingsBoardApiEndpoint);
await tbClient.login(LoginRequest('[email protected]', 'tenant'));
print('isAuthenticated=${tbClient.isAuthenticated()}'); print('authUser: ${tbClient.getAuthUser()}');
var currentUserDetails = await tbClient.getUserService().getUser(); print('currentUserDetails: $currentUserDetails');
await tbClient.logout();} catch (e, s) { print('Error: $e'); print('Stack: $s');}}API key authentication
Section titled “API key authentication”Starting from ThingsBoard 4.3, you can authenticate with an API key instead of username/password:
const thingsBoardApiEndpoint = 'http://localhost:8080';const apiKey = 'tb_your_api_key';
void main() async {try { final tbClient = ThingsboardClient(thingsBoardApiEndpoint, apiKey: apiKey);
var device = Device('myDevice', 'default'); device.additionalInfo = {'description': 'My test device!'}; var savedDevice = await tbClient.getDeviceService().saveDevice(device); print('savedDevice: $savedDevice');} catch (e, s) { print('Error: $e'); print('Stack: $s');}}Fetch tenant devices
Section titled “Fetch tenant devices”Paginate through all devices belonging to the current tenant:
import 'package:thingsboard_client/thingsboard_client.dart';
const thingsBoardApiEndpoint = 'http://localhost:8080';
void main() async {try { var tbClient = ThingsboardClient(thingsBoardApiEndpoint); await tbClient.login(LoginRequest('[email protected]', 'tenant'));
var pageLink = PageLink(10); PageData<DeviceInfo> devices; do { devices = await tbClient.getDeviceService().getTenantDeviceInfos(pageLink); print('devices: $devices'); pageLink = pageLink.nextPageLink(); } while (devices.hasNext);
await tbClient.logout();} catch (e, s) { print('Error: $e'); print('Stack: $s');}}Fetch tenant dashboards
Section titled “Fetch tenant dashboards”import 'package:thingsboard_client/thingsboard_client.dart';
const thingsBoardApiEndpoint = 'http://localhost:8080';
void main() async {try { var tbClient = ThingsboardClient(thingsBoardApiEndpoint); await tbClient.login(LoginRequest('[email protected]', 'tenant'));
var pageLink = PageLink(10); PageData<DashboardInfo> dashboards; do { dashboards = await tbClient.getDashboardService().getTenantDashboards(pageLink); print('dashboards: $dashboards'); pageLink = pageLink.nextPageLink(); } while (dashboards.hasNext);
await tbClient.logout();} catch (e, s) { print('Error: $e'); print('Stack: $s');}}Count and query entities
Section titled “Count and query entities”Use the Entity Data Query API to count devices by status and query active devices:
import 'package:thingsboard_client/thingsboard_client.dart';
const thingsBoardApiEndpoint = 'http://localhost:8080';
void main() async {try { var tbClient = ThingsboardClient(thingsBoardApiEndpoint); await tbClient.login(LoginRequest('[email protected]', 'tenant'));
// Create entity filter to get all devices var entityFilter = EntityTypeFilter(entityType: EntityType.DEVICE); var devicesQuery = EntityCountQuery(entityFilter: entityFilter);
// Total device count var totalDevicesCount = await tbClient.getEntityQueryService().countEntitiesByQuery(devicesQuery); print('Total devices: $totalDevicesCount');
// Active devices count var activeDeviceKeyFilter = KeyFilter( key: EntityKey(type: EntityKeyType.ATTRIBUTE, key: 'active'), valueType: EntityKeyValueType.BOOLEAN, predicate: BooleanFilterPredicate( operation: BooleanOperation.EQUAL, value: FilterPredicateValue(true))); devicesQuery.keyFilters = [activeDeviceKeyFilter];
var activeDevicesCount = await tbClient.getEntityQueryService().countEntitiesByQuery(devicesQuery); print('Active devices: $activeDevicesCount');
// Inactive devices count var inactiveDeviceKeyFilter = KeyFilter( key: EntityKey(type: EntityKeyType.ATTRIBUTE, key: 'active'), valueType: EntityKeyValueType.BOOLEAN, predicate: BooleanFilterPredicate( operation: BooleanOperation.EQUAL, value: FilterPredicateValue(false))); devicesQuery.keyFilters = [inactiveDeviceKeyFilter];
var inactiveDevicesCount = await tbClient.getEntityQueryService().countEntitiesByQuery(devicesQuery); print('Inactive devices: $inactiveDevicesCount');
await tbClient.logout();} catch (e, s) { print('Error: $e'); print('Stack: $s');}}Manage devices
Section titled “Manage devices”Create a device, save and read attributes, then delete it:
import 'package:thingsboard_client/thingsboard_client.dart';
const thingsBoardApiEndpoint = 'http://localhost:8080';
void main() async {try { var tbClient = ThingsboardClient(thingsBoardApiEndpoint); await tbClient.login(LoginRequest('[email protected]', 'tenant'));
var device = Device('My test device', 'default'); device.additionalInfo = {'description': 'My test device!'};
var savedDevice = await tbClient.getDeviceService().saveDevice(device); print('savedDevice: $savedDevice');
var foundDevice = await tbClient.getDeviceService().getDeviceInfo(savedDevice.id!.id!); print('foundDevice: $foundDevice');
// Save shared attributes var res = await tbClient.getAttributeService().saveEntityAttributesV2( foundDevice!.id!, AttributeScope.SHARED_SCOPE.toShortString(), {'targetTemperature': 22.4, 'targetHumidity': 57.8}); print('Save attributes result: $res');
// Get shared attributes var attributes = await tbClient.getAttributeService().getAttributesByScope( foundDevice.id!, AttributeScope.SHARED_SCOPE.toShortString(), ['targetTemperature', 'targetHumidity']); print('Found device attributes: $attributes');
// Delete device await tbClient.getDeviceService().deleteDevice(savedDevice.id!.id!);
await tbClient.logout();} catch (e, s) { print('Error: $e'); print('Stack: $s');}}WebSocket subscriptions
Section titled “WebSocket subscriptions”Subscribe to real-time telemetry updates using WebSocket API:
import 'dart:math';import 'package:thingsboard_client/thingsboard_client.dart';
const thingsBoardApiEndpoint = 'http://localhost:8080';
void main() async {try { var tbClient = ThingsboardClient(thingsBoardApiEndpoint); await tbClient.login(LoginRequest('[email protected]', 'tenant'));
var device = Device('My test device', 'default'); device.additionalInfo = {'description': 'My test device!'}; var savedDevice = await tbClient.getDeviceService().saveDevice(device);
// Create entity query for the device var entityFilter = EntityNameFilter( entityType: EntityType.DEVICE, entityNameFilter: 'My test device'); var deviceFields = <EntityKey>[ EntityKey(type: EntityKeyType.ENTITY_FIELD, key: 'name'), EntityKey(type: EntityKeyType.ENTITY_FIELD, key: 'type'), EntityKey(type: EntityKeyType.ENTITY_FIELD, key: 'createdTime') ]; var deviceTelemetry = <EntityKey>[ EntityKey(type: EntityKeyType.TIME_SERIES, key: 'temperature'), EntityKey(type: EntityKeyType.TIME_SERIES, key: 'humidity') ]; var devicesQuery = EntityDataQuery( entityFilter: entityFilter, entityFields: deviceFields, latestValues: deviceTelemetry, pageLink: EntityDataPageLink( pageSize: 10, sortOrder: EntityDataSortOrder( key: EntityKey( type: EntityKeyType.ENTITY_FIELD, key: 'createdTime'), direction: EntityDataSortOrderDirection.DESC)));
// Subscribe to last hour of telemetry with real-time updates var currentTime = DateTime.now().millisecondsSinceEpoch; var timeWindow = Duration(hours: 1).inMilliseconds; var tsCmd = TimeSeriesCmd( keys: ['temperature', 'humidity'], startTs: currentTime - timeWindow, timeWindow: timeWindow);
var cmd = EntityDataCmd(query: devicesQuery, tsCmd: tsCmd); var telemetryService = tbClient.getTelemetryService(); var subscription = TelemetrySubscriber(telemetryService, [cmd]);
subscription.entityDataStream.listen((entityDataUpdate) { print('Received entity data update: $entityDataUpdate'); }); subscription.subscribe();
// Post sample telemetry var rng = Random(); for (var i = 0; i < 5; i++) { await Future.delayed(Duration(seconds: 1)); var telemetryRequest = { 'temperature': 10 + 20 * rng.nextDouble(), 'humidity': 30 + 40 * rng.nextDouble() }; print('Save telemetry request: $telemetryRequest'); await tbClient.getAttributeService().saveEntityTelemetry( savedDevice.id!, 'TELEMETRY', telemetryRequest); }
await Future.delayed(Duration(seconds: 2)); subscription.unsubscribe();
await tbClient.getDeviceService().deleteDevice(savedDevice.id!.id!); await tbClient.logout();} catch (e, s) { print('Error: $e'); print('Stack: $s');}}More examples
Section titled “More examples”Additional examples are available in the dart_thingsboard_client GitHub repository.