├── .gitignore ├── CHANGELOG.md ├── LICENSE ├── README.md ├── analysis_options.yaml ├── example ├── callbacks.dart ├── device_api.dart ├── example_utils.dart ├── fetch_data.dart ├── mfa.dart ├── ota_package.dart ├── thingsboard_client.dart └── websocket_api.dart ├── lib ├── src │ ├── error │ │ ├── _thingsboard_error_handler.dart │ │ ├── _thingsboard_error_handler_html.dart │ │ ├── _thingsboard_error_handler_io.dart │ │ └── thingsboard_error.dart │ ├── http │ │ └── http_utils.dart │ ├── interceptor │ │ ├── http_interceptor.dart │ │ └── interceptor_config.dart │ ├── model │ │ ├── additional_info_based.dart │ │ ├── alarm_models.dart │ │ ├── asset_models.dart │ │ ├── audit_log_models.dart │ │ ├── authority_enum.dart │ │ ├── base_data.dart │ │ ├── component_descriptor_models.dart │ │ ├── constants.dart │ │ ├── contact_based_model.dart │ │ ├── customer_models.dart │ │ ├── dashboard_models.dart │ │ ├── device_models.dart │ │ ├── edge_models.dart │ │ ├── entity_models.dart │ │ ├── entity_type_models.dart │ │ ├── entity_view_models.dart │ │ ├── event_models.dart │ │ ├── exportable_entity.dart │ │ ├── has_additional_info.dart │ │ ├── has_customer_id.dart │ │ ├── has_name.dart │ │ ├── has_ota_package.dart │ │ ├── has_rule_engine_profile.dart │ │ ├── has_tenant_id.dart │ │ ├── id │ │ │ ├── admin_settings_id.dart │ │ │ ├── alarm_comment_id.dart │ │ │ ├── alarm_id.dart │ │ │ ├── api_usage_state_id.dart │ │ │ ├── asset_id.dart │ │ │ ├── asset_profile_id.dart │ │ │ ├── audit_log_id.dart │ │ │ ├── component_descriptor_id.dart │ │ │ ├── customer_id.dart │ │ │ ├── dashboard_id.dart │ │ │ ├── device_credentials_id.dart │ │ │ ├── device_id.dart │ │ │ ├── device_profile_id.dart │ │ │ ├── edge_event_id.dart │ │ │ ├── edge_id.dart │ │ │ ├── entity_id.dart │ │ │ ├── entity_view_id.dart │ │ │ ├── event_id.dart │ │ │ ├── has_id.dart │ │ │ ├── has_uuid.dart │ │ │ ├── id_based.dart │ │ │ ├── ids.dart │ │ │ ├── notification_id.dart │ │ │ ├── notification_request_id.dart │ │ │ ├── notification_rule_id.dart │ │ │ ├── notification_target_id.dart │ │ │ ├── notification_template_id.dart │ │ │ ├── oauth2_client_registration_template_id.dart │ │ │ ├── ota_package_id.dart │ │ │ ├── queue_id.dart │ │ │ ├── rpc_id.dart │ │ │ ├── rule_chain_id.dart │ │ │ ├── rule_node_id.dart │ │ │ ├── tb_resource_id.dart │ │ │ ├── tenant_id.dart │ │ │ ├── tenant_profile_id.dart │ │ │ ├── user_id.dart │ │ │ ├── widget_type_id.dart │ │ │ └── widgets_bundle_id.dart │ │ ├── login_models.dart │ │ ├── mobile │ │ │ ├── basic_mobile_info.dart │ │ │ ├── login_mobile_info.dart │ │ │ ├── mobile_info_query.dart │ │ │ ├── mobile_models.dart │ │ │ ├── mobile_version_info.dart │ │ │ ├── pages_layout.dart │ │ │ ├── recaptcha_model.dart │ │ │ ├── store_info.dart │ │ │ └── version_info.dart │ │ ├── mobile_session_models.dart │ │ ├── model.dart │ │ ├── oauth2_models.dart │ │ ├── ota_models.dart │ │ ├── page │ │ │ ├── page_data.dart │ │ │ ├── page_link.dart │ │ │ └── sort_order.dart │ │ ├── push_notification_models.dart │ │ ├── query │ │ │ └── query_models.dart │ │ ├── queue_models.dart │ │ ├── relation_models.dart │ │ ├── resource_models.dart │ │ ├── rpc_models.dart │ │ ├── rule_chain_models.dart │ │ ├── rule_node_models.dart │ │ ├── settings_models.dart │ │ ├── telemetry_models.dart │ │ ├── tenant_models.dart │ │ ├── thingsboard_error.dart │ │ ├── two_factor_auth_models.dart │ │ ├── user_models.dart │ │ ├── vc_models.dart │ │ ├── version.dart │ │ ├── widget_models.dart │ │ └── widgets_bundle_model.dart │ ├── service │ │ ├── admin_service.dart │ │ ├── alarm_service.dart │ │ ├── asset_profile_service.dart │ │ ├── asset_service.dart │ │ ├── attribute_service.dart │ │ ├── audit_log_service.dart │ │ ├── component_descriptor_service.dart │ │ ├── customer_service.dart │ │ ├── dashboard_service.dart │ │ ├── device_profile_service.dart │ │ ├── device_service.dart │ │ ├── edge_service.dart │ │ ├── entities_version_control_service.dart │ │ ├── entity_query_service.dart │ │ ├── entity_relation_service.dart │ │ ├── entity_view_service.dart │ │ ├── event_service.dart │ │ ├── mobile_service.dart │ │ ├── notifications_service.dart │ │ ├── oauth2_service.dart │ │ ├── ota_package_service.dart │ │ ├── queue_service.dart │ │ ├── resource_service.dart │ │ ├── rule_chain_service.dart │ │ ├── service.dart │ │ ├── telemetry_websocket_service.dart │ │ ├── tenant_profile_service.dart │ │ ├── tenant_service.dart │ │ ├── two_factor_auth_service.dart │ │ ├── user_service.dart │ │ └── widget_service.dart │ ├── storage │ │ ├── _local_file_storage.dart │ │ ├── _local_file_storage_io.dart │ │ ├── in_memory_storage.dart │ │ ├── local_file_storage.dart │ │ ├── storage.dart │ │ └── tb_storage.dart │ └── thingsboard_client_base.dart └── thingsboard_client.dart ├── pubspec.yaml └── test └── thingsboard_client_test.dart /.gitignore: -------------------------------------------------------------------------------- 1 | # Files and directories created by pub 2 | .dart_tool/ 3 | .packages 4 | 5 | # Omit commiting pubspec.lock for library packages: 6 | # https://dart.dev/guides/libraries/private-files#pubspeclock 7 | pubspec.lock 8 | 9 | # Conventional directory for build outputs 10 | build/ 11 | 12 | # Directory created by dartdoc 13 | doc/api/ 14 | 15 | *.iml 16 | */.idea/** 17 | .idea/** 18 | .idea 19 | 20 | tb_client_storage.json 21 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | ## 4.0.0 2 | - Changes in TbStorage interface 3 | 4 | ## 3.0.1 5 | 6 | - Adapted to backend changes for version information representation. 7 | 8 | ## 3.0.0 9 | 10 | - Introduced a new API for dynamically configuring via mobile center. 11 | - The minimum supported TB version is 3.9.0 and higher. 12 | 13 | ## 2.0.0 14 | 15 | - Enhanced TbStorage interface for improved usability. 16 | - Introduced a new API for alarm activity management, including support for comments and additional functionalities. 17 | 18 | ## 1.3.1 19 | 20 | - Increased the minimum supported ThingsBoard version to 3.8.0. 21 | 22 | ## 1.3.0 23 | 24 | - **New APIs:** 25 | - `/api/alarm/types` - Fetches available alarm types. 26 | - `/api/users/info` - Retrieves user information. 27 | 28 | - **Enhancements:** 29 | - Added the ability to log request and response details for improved debugging. 30 | 31 | - **Bug Fixes:** 32 | - Various minor bug fixes to improve stability and performance. 33 | 34 | ## 1.2.0 35 | 36 | - Introduced the ability to configure access to custom applications using a login with a QR code feature. 37 | - Update API and models according to ThingsBoard platform version 3.7.0 38 | - Fixed the issue with resolving supported platform versions. 39 | - Implemented other minor fixes. 40 | 41 | ## 1.1.1 42 | 43 | - Introduced a NotificationService, which allows you to receive notification data. 44 | 45 | ## 1.1.0 46 | 47 | - Updated the API and models to align with the latest ThingsBoard platform, version 3.6.3 48 | - Introduced support for push notifications 49 | 50 | ## 1.0.8 51 | 52 | - Update API and models according to ThingsBoard platform version 3.6.2 53 | - Fixed issue [#13](https://github.com/thingsboard/dart_thingsboard_client/issues/13): Problem occurred when using web socket and loosing internet 54 | - Fixed issue [#19](https://github.com/thingsboard/dart_thingsboard_client/issues/19): incorrect AlarmDataCmd 55 | - Fixed issue [#21](https://github.com/thingsboard/dart_thingsboard_client/issues/21): incorrect updated notification in subscription 56 | 57 | ## 1.0.7 58 | 59 | - Update API and models according to ThingsBoard platform version 3.6.0 60 | - Fixed issue [#17](https://github.com/thingsboard/dart_thingsboard_client/issues/17): get json attributes when value is array 61 | 62 | ## 1.0.6 63 | 64 | - Fixed incorrect deserializing alarm models 65 | 66 | ## 1.0.5 67 | 68 | - Update API and models according to ThingsBoard platform version 3.5.0 69 | 70 | ## 1.0.4 71 | 72 | - Update API and models according to ThingsBoard platform version 3.4.2 73 | 74 | ## 1.0.3 75 | 76 | - Update API and models according to ThingsBoard platform version 3.4.0 77 | - Added MFA support 78 | - Fix dart analysis issues 79 | 80 | ## 1.0.2 81 | 82 | - Add support for web platform 83 | 84 | ## 1.0.1 85 | 86 | - Improve description 87 | - Improve pubspec: add github links 88 | - Use formatting according to dartfmt 89 | 90 | ## 1.0.0 91 | 92 | - Initial version, created by Igor Kulikov 93 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Copyright 2021 The ThingsBoard Authors 2 | 3 | Redistribution and use in source and binary forms, with or without modification, 4 | are permitted provided that the following conditions are met: 5 | 6 | * Redistributions of source code must retain the above copyright 7 | notice, this list of conditions and the following disclaimer. 8 | * Redistributions in binary form must reproduce the above 9 | copyright notice, this list of conditions and the following 10 | disclaimer in the documentation and/or other materials provided 11 | with the distribution. 12 | * Neither the name of Google Inc. nor the names of its 13 | contributors may be used to endorse or promote products derived 14 | from this software without specific prior written permission. 15 | 16 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 17 | ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 18 | WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 19 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR 20 | ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 21 | (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 22 | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 23 | ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 24 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 25 | SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 26 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ThingsBoard API client library for Dart developers. Provides model objects and services to communicate with ThingsBoard platform using RESTful APIs and WebSocket protocol. 2 | Current client version is compatible with ThingsBoard starting from version 3.6.3. 3 | 4 | ## Usage 5 | 6 | A simple usage example: 7 | 8 | ```dart 9 | import 'package:thingsboard_client/thingsboard_client.dart'; 10 | 11 | main() async { 12 | try { 13 | var tbClient = ThingsboardClient('https://demo.thingsboard.io'); 14 | await tbClient.login(LoginRequest('tenant@thingsboard.org', 'tenant')); 15 | 16 | print('isAuthenticated=${tbClient.isAuthenticated()}'); 17 | 18 | print('authUser: ${tbClient.getAuthUser()}'); 19 | 20 | var currentUserDetails = await tbClient.getUserService().getUser(); 21 | print('currentUserDetails: $currentUserDetails'); 22 | 23 | await tbClient.logout(); 24 | 25 | } catch (e, s) { 26 | print('Error: $e'); 27 | print('Stack: $s'); 28 | } 29 | } 30 | ``` 31 | 32 | ## Features and bugs 33 | 34 | Please file feature requests and bugs at the [issue tracker][tracker]. 35 | 36 | [tracker]: https://github.com/thingsboard/dart_thingsboard_client/issues 37 | -------------------------------------------------------------------------------- /analysis_options.yaml: -------------------------------------------------------------------------------- 1 | # Defines a default set of lint rules enforced for 2 | # projects at Google. For details and rationale, 3 | # see https://github.com/dart-lang/pedantic#enabled-lints. 4 | include: package:lints/core.yaml 5 | 6 | # For lint rules and documentation, see http://dart-lang.github.io/linter/lints. 7 | # Uncomment to specify additional rules. 8 | # linter: 9 | # rules: 10 | # - camel_case_types 11 | 12 | analyzer: 13 | # exclude: 14 | # - path/to/excluded/files/** 15 | -------------------------------------------------------------------------------- /example/callbacks.dart: -------------------------------------------------------------------------------- 1 | import 'dart:io'; 2 | 3 | import 'package:thingsboard_client/thingsboard_client.dart'; 4 | 5 | const thingsBoardApiEndpoint = 'http://localhost:8080'; 6 | 7 | late ThingsboardClient tbClient; 8 | 9 | void main() async { 10 | try { 11 | tbClient = ThingsboardClient(thingsBoardApiEndpoint, 12 | storage: InMemoryStorage(), 13 | onUserLoaded: onUserLoaded, 14 | onError: onError, 15 | onLoadStarted: onLoadStarted, 16 | onLoadFinished: onLoadFinished); 17 | await tbClient.init(); 18 | } catch (e, s) { 19 | print('Error: $e'); 20 | print('Stack: $s'); 21 | } 22 | } 23 | 24 | void onError(ThingsboardError error) { 25 | print('onError: error=$error'); 26 | } 27 | 28 | void onLoadStarted() { 29 | print('ON LOAD STARTED!'); 30 | } 31 | 32 | void onLoadFinished() { 33 | print('ON LOAD FINISHED!'); 34 | } 35 | 36 | bool loginExecuted = false; 37 | 38 | Future onUserLoaded() async { 39 | try { 40 | print('onUserLoaded: isAuthenticated=${tbClient.isAuthenticated()}'); 41 | if (tbClient.isAuthenticated()) { 42 | print('authUser: ${tbClient.getAuthUser()}'); 43 | var currentUserDetails = await tbClient.getUserService().getUser(); 44 | print('currentUserDetails: $currentUserDetails'); 45 | await tbClient.logout( 46 | requestConfig: 47 | RequestConfig(ignoreLoading: true, ignoreErrors: true)); 48 | exit(0); 49 | } else { 50 | await tbClient.login(LoginRequest('tenant@thingsboard.org', 'tenant')); 51 | } 52 | } catch (e, s) { 53 | print('Error: $e'); 54 | print('Stack: $s'); 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /example/device_api.dart: -------------------------------------------------------------------------------- 1 | import 'package:thingsboard_client/thingsboard_client.dart'; 2 | import 'example_utils.dart'; 3 | 4 | const thingsBoardApiEndpoint = 'http://localhost:8080'; 5 | const username = 'tenant@thingsboard.org'; 6 | const password = 'tenant'; 7 | 8 | late ThingsboardClient tbClient; 9 | 10 | void main() async { 11 | try { 12 | tbClient = ThingsboardClient(thingsBoardApiEndpoint); 13 | 14 | await tbClient.login(LoginRequest(username, password)); 15 | 16 | await deviceApiExample(); 17 | 18 | await tbClient.logout( 19 | requestConfig: RequestConfig(ignoreLoading: true, ignoreErrors: true)); 20 | } catch (e, s) { 21 | print('Error: $e'); 22 | print('Stack: $s'); 23 | } 24 | } 25 | 26 | Future deviceApiExample() async { 27 | print( 28 | '**********************************************************************'); 29 | print( 30 | '* DEVICE API EXAMPLE *'); 31 | print( 32 | '**********************************************************************'); 33 | 34 | var deviceName = getRandomString(30); 35 | 36 | var device = Device(deviceName, 'default'); 37 | device.additionalInfo = {'description': 'My test device!'}; 38 | var savedDevice = await tbClient.getDeviceService().saveDevice(device); 39 | print('savedDevice: $savedDevice'); 40 | var foundDevice = 41 | await tbClient.getDeviceService().getDeviceInfo(savedDevice.id!.id!); 42 | print('foundDevice: $foundDevice'); 43 | var res = await tbClient.getAttributeService().saveEntityAttributesV2( 44 | foundDevice!.id!, AttributeScope.SHARED_SCOPE.toShortString(), { 45 | 'targetTemperature': 22.4, 46 | 'targetHumidity': 57.8, 47 | 'array': [1, 2], 48 | 'json': {'test': 'work!'} 49 | }); 50 | print('Save attributes result: $res'); 51 | var attributes = await tbClient.getAttributeService().getAttributesByScope( 52 | foundDevice.id!, 53 | AttributeScope.SHARED_SCOPE.toShortString(), 54 | ['targetTemperature', 'targetHumidity', 'array', 'json']); 55 | print('Found device attributes: $attributes'); 56 | 57 | await tbClient.getDeviceService().deleteDevice(savedDevice.id!.id!); 58 | foundDevice = 59 | await tbClient.getDeviceService().getDeviceInfo(savedDevice.id!.id!); 60 | print('foundDevice: $foundDevice'); 61 | print( 62 | '**********************************************************************'); 63 | } 64 | -------------------------------------------------------------------------------- /example/example_utils.dart: -------------------------------------------------------------------------------- 1 | import 'dart:math'; 2 | 3 | const _chars = 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz1234567890'; 4 | Random _rnd = Random(); 5 | 6 | String getRandomString(int length) => String.fromCharCodes(Iterable.generate( 7 | length, (_) => _chars.codeUnitAt(_rnd.nextInt(_chars.length)))); 8 | -------------------------------------------------------------------------------- /example/mfa.dart: -------------------------------------------------------------------------------- 1 | import 'dart:convert'; 2 | import 'dart:io'; 3 | 4 | import 'package:thingsboard_client/thingsboard_client.dart'; 5 | import 'package:collection/collection.dart'; 6 | 7 | const thingsBoardApiEndpoint = 'http://localhost:8080'; 8 | 9 | late ThingsboardClient tbClient; 10 | 11 | void main() async { 12 | try { 13 | tbClient = ThingsboardClient(thingsBoardApiEndpoint, onMfaAuth: onMfa); 14 | await tbClient.login(LoginRequest('tenant@thingsboard.org', 'tenant')); 15 | 16 | print('isAuthenticated=${tbClient.isAuthenticated()}'); 17 | 18 | print('authUser: ${tbClient.getAuthUser()}'); 19 | 20 | if (tbClient.isAuthenticated() && !tbClient.isPreVerificationToken()) { 21 | var currentUserDetails = await tbClient.getUserService().getUser(); 22 | print('currentUserDetails: $currentUserDetails'); 23 | await tbClient.logout(); 24 | } 25 | } catch (e, s) { 26 | print('Error: $e'); 27 | print('Stack: $s'); 28 | } 29 | } 30 | 31 | void onMfa() async { 32 | print('ON MULTI-FACTOR AUTHENTICATION!'); 33 | List providers = await tbClient 34 | .getTwoFactorAuthService() 35 | .getAvailableLoginTwoFaProviders(); 36 | print('Available providers: $providers'); 37 | var defaultProvider = 38 | providers.firstWhereOrNull((provider) => provider.isDefault); 39 | if (defaultProvider != null) { 40 | print('Default provider: $defaultProvider'); 41 | await tbClient 42 | .getTwoFactorAuthService() 43 | .requestTwoFaVerificationCode(defaultProvider.type); 44 | print('Verification code sent!'); 45 | print('Enter MFA code:'); 46 | var code = stdin.readLineSync(encoding: utf8); 47 | var mfaCode = code?.trim(); 48 | print('Code entered: $mfaCode'); 49 | await tbClient.checkTwoFaVerificationCode(defaultProvider.type, mfaCode!); 50 | 51 | print('isAuthenticated=${tbClient.isAuthenticated()}'); 52 | 53 | print('authUser: ${tbClient.getAuthUser()}'); 54 | 55 | var currentUserDetails = await tbClient.getUserService().getUser(); 56 | print('currentUserDetails: $currentUserDetails'); 57 | await tbClient.logout(); 58 | } else { 59 | await tbClient.logout(); 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /example/ota_package.dart: -------------------------------------------------------------------------------- 1 | import 'dart:convert'; 2 | import 'dart:math'; 3 | 4 | import 'package:dio/dio.dart'; 5 | import 'package:thingsboard_client/thingsboard_client.dart'; 6 | 7 | import 'example_utils.dart'; 8 | 9 | const thingsBoardApiEndpoint = 'http://localhost:8080'; 10 | const username = 'tenant@thingsboard.org'; 11 | const password = 'tenant'; 12 | 13 | late ThingsboardClient tbClient; 14 | 15 | void main() async { 16 | try { 17 | tbClient = ThingsboardClient(thingsBoardApiEndpoint); 18 | 19 | await tbClient.login(LoginRequest(username, password)); 20 | 21 | await otaPackageExample(); 22 | 23 | await tbClient.logout( 24 | requestConfig: RequestConfig(ignoreLoading: true, ignoreErrors: true)); 25 | } catch (e, s) { 26 | print('Error: $e'); 27 | print('Stack: $s'); 28 | } 29 | } 30 | 31 | Future otaPackageExample() async { 32 | print( 33 | '**********************************************************************'); 34 | print( 35 | '* OTA PACKAGE EXAMPLE *'); 36 | print( 37 | '**********************************************************************'); 38 | 39 | var deviceProfileId = 40 | (await tbClient.getDeviceProfileService().getDefaultDeviceProfileInfo()) 41 | .id; 42 | 43 | var otaPackage = OtaPackageInfo(DeviceProfileId(deviceProfileId.id!), 44 | OtaPackageType.FIRMWARE, getRandomString(30), 'v.1'); 45 | otaPackage = 46 | await tbClient.getOtaPackageService().saveOtaPackageInfo(otaPackage); 47 | 48 | var file = MultipartFile.fromString('Test content', filename: 'test.txt'); 49 | otaPackage = await tbClient.getOtaPackageService().saveOtaPackageData( 50 | otaPackage.id!.id!, file, 51 | checksumAlgorithm: ChecksumAlgorithm.SHA256); 52 | 53 | print('download ota package with id: ${otaPackage.id!.id}'); 54 | var responseBody = await tbClient 55 | .getOtaPackageService() 56 | .downloadOtaPackage(otaPackage.id!.id!); 57 | if (responseBody != null) { 58 | var headers = Headers.fromMap(responseBody.headers); 59 | var contentLength = headers[Headers.contentLengthHeader]?.first ?? '-1'; 60 | var contentType = headers[Headers.contentTypeHeader]?.first ?? ''; 61 | var contentDisposition = headers['content-disposition']?.first ?? ''; 62 | print('download ota package contentLength: $contentLength'); 63 | print('download ota package contentType: $contentType'); 64 | print('download ota package contentDisposition: $contentDisposition'); 65 | var bytes = await responseBody.stream.toList(); 66 | bytes.forEach((bytes) { 67 | var base64str = base64Encode(bytes); 68 | print('download ota package chunk length: ${bytes.length}'); 69 | print( 70 | 'download ota package chunk bytes: [${base64str.substring(0, min(30, base64str.length))}...]'); 71 | }); 72 | } 73 | 74 | await tbClient.getOtaPackageService().deleteOtaPackage(otaPackage.id!.id!); 75 | 76 | print( 77 | '**********************************************************************'); 78 | } 79 | -------------------------------------------------------------------------------- /example/thingsboard_client.dart: -------------------------------------------------------------------------------- 1 | import 'package:thingsboard_client/thingsboard_client.dart'; 2 | 3 | const thingsBoardApiEndpoint = 'http://localhost:8080'; 4 | 5 | void main() async { 6 | try { 7 | var tbClient = ThingsboardClient(thingsBoardApiEndpoint); 8 | await tbClient.login(LoginRequest('tenant@thingsboard.org', 'tenant')); 9 | 10 | print('isAuthenticated=${tbClient.isAuthenticated()}'); 11 | 12 | print('authUser: ${tbClient.getAuthUser()}'); 13 | 14 | var currentUserDetails = await tbClient.getUserService().getUser(); 15 | print('currentUserDetails: $currentUserDetails'); 16 | 17 | await tbClient.logout(); 18 | } catch (e, s) { 19 | print('Error: $e'); 20 | print('Stack: $s'); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /lib/src/error/_thingsboard_error_handler.dart: -------------------------------------------------------------------------------- 1 | import 'thingsboard_error.dart'; 2 | 3 | ThingsboardError toThingsboardError(error, [StackTrace? stackTrace]) => 4 | throw UnsupportedError(''); 5 | -------------------------------------------------------------------------------- /lib/src/error/_thingsboard_error_handler_html.dart: -------------------------------------------------------------------------------- 1 | import 'dart:convert'; 2 | import 'dart:html'; 3 | import 'package:dio/dio.dart'; 4 | 5 | import 'thingsboard_error.dart'; 6 | 7 | int httpStatusToThingsboardErrorCode(int status) { 8 | switch (status) { 9 | case HttpStatus.unauthorized: 10 | return ThingsBoardErrorCode.authentication; 11 | case HttpStatus.forbidden: 12 | return ThingsBoardErrorCode.permissionDenied; 13 | case HttpStatus.badRequest: 14 | return ThingsBoardErrorCode.badRequestParams; 15 | case HttpStatus.notFound: 16 | return ThingsBoardErrorCode.itemNotFound; 17 | case HttpStatus.tooManyRequests: 18 | return ThingsBoardErrorCode.tooManyRequests; 19 | case HttpStatus.internalServerError: 20 | return ThingsBoardErrorCode.general; 21 | default: 22 | return ThingsBoardErrorCode.general; 23 | } 24 | } 25 | 26 | ThingsboardError toThingsboardError(error, [StackTrace? stackTrace]) { 27 | ThingsboardError? tbError; 28 | if (error is DioException) { 29 | if (error.response != null && error.response!.data != null) { 30 | var data = error.response!.data; 31 | if (data is ThingsboardError) { 32 | tbError = data; 33 | } else if (data is Map) { 34 | tbError = ThingsboardError.fromJson(data); 35 | } else if (data is String) { 36 | try { 37 | tbError = ThingsboardError.fromJson(jsonDecode(data)); 38 | } catch (_) {} 39 | } 40 | } else if (error.error != null) { 41 | if (error.error is ThingsboardError) { 42 | tbError = error.error as ThingsboardError; 43 | } /* else if (error.error is SocketException) { 44 | tbError = ThingsboardError( 45 | error: error, 46 | message: 'Unable to connect', 47 | errorCode: ThingsBoardErrorCode.general); 48 | }*/ 49 | else { 50 | tbError = ThingsboardError( 51 | error: error, 52 | message: error.error.toString(), 53 | errorCode: ThingsBoardErrorCode.general); 54 | } 55 | } 56 | if (tbError == null && 57 | error.response != null && 58 | error.response!.statusCode != null) { 59 | var httpStatus = error.response!.statusCode!; 60 | var message = (httpStatus.toString() + 61 | ': ' + 62 | (error.response!.statusMessage != null 63 | ? error.response!.statusMessage! 64 | : 'Unknown')); 65 | tbError = ThingsboardError( 66 | error: error, 67 | message: message, 68 | errorCode: httpStatusToThingsboardErrorCode(httpStatus), 69 | status: httpStatus); 70 | } 71 | } else if (error is ThingsboardError) { 72 | tbError = error; 73 | } 74 | if (tbError != null && tbError.errorCode == null && tbError.status != null) { 75 | tbError.errorCode = httpStatusToThingsboardErrorCode(tbError.status!); 76 | } 77 | tbError ??= ThingsboardError( 78 | error: error, 79 | message: error.toString(), 80 | errorCode: ThingsBoardErrorCode.general); 81 | 82 | StackTrace? errorStackTrace; 83 | if (tbError.error is Error) { 84 | errorStackTrace = tbError.error.stackTrace; 85 | } 86 | 87 | tbError.stackTrace = stackTrace ?? 88 | tbError.getStackTrace() ?? 89 | errorStackTrace ?? 90 | StackTrace.current; 91 | 92 | return tbError; 93 | } 94 | -------------------------------------------------------------------------------- /lib/src/error/_thingsboard_error_handler_io.dart: -------------------------------------------------------------------------------- 1 | import 'dart:convert'; 2 | import 'dart:io'; 3 | import 'package:dio/dio.dart'; 4 | 5 | import 'thingsboard_error.dart'; 6 | 7 | int httpStatusToThingsboardErrorCode(int status) { 8 | switch (status) { 9 | case HttpStatus.unauthorized: 10 | return ThingsBoardErrorCode.authentication; 11 | case HttpStatus.forbidden: 12 | return ThingsBoardErrorCode.permissionDenied; 13 | case HttpStatus.badRequest: 14 | return ThingsBoardErrorCode.badRequestParams; 15 | case HttpStatus.notFound: 16 | return ThingsBoardErrorCode.itemNotFound; 17 | case HttpStatus.tooManyRequests: 18 | return ThingsBoardErrorCode.tooManyRequests; 19 | case HttpStatus.internalServerError: 20 | return ThingsBoardErrorCode.general; 21 | default: 22 | return ThingsBoardErrorCode.general; 23 | } 24 | } 25 | 26 | ThingsboardError toThingsboardError(error, [StackTrace? stackTrace]) { 27 | ThingsboardError? tbError; 28 | if (error is DioException) { 29 | if (error.response != null && error.response!.data != null) { 30 | var data = error.response!.data; 31 | if (data is ThingsboardError) { 32 | tbError = data; 33 | } else if (data is Map) { 34 | tbError = ThingsboardError.fromJson(data); 35 | } else if (data is String) { 36 | try { 37 | tbError = ThingsboardError.fromJson(jsonDecode(data)); 38 | } catch (_) {} 39 | } 40 | } else if (error.error != null) { 41 | if (error.error is ThingsboardError) { 42 | tbError = error.error as ThingsboardError; 43 | } else if (error.error is SocketException) { 44 | tbError = ThingsboardError( 45 | error: error, 46 | message: 'Unable to connect', 47 | errorCode: ThingsBoardErrorCode.general); 48 | } else { 49 | tbError = ThingsboardError( 50 | error: error, 51 | message: error.error.toString(), 52 | errorCode: ThingsBoardErrorCode.general); 53 | } 54 | } 55 | if (tbError == null && 56 | error.response != null && 57 | error.response!.statusCode != null) { 58 | var httpStatus = error.response!.statusCode!; 59 | var message = (httpStatus.toString() + 60 | ': ' + 61 | (error.response!.statusMessage != null 62 | ? error.response!.statusMessage! 63 | : 'Unknown')); 64 | tbError = ThingsboardError( 65 | error: error, 66 | message: message, 67 | errorCode: httpStatusToThingsboardErrorCode(httpStatus), 68 | status: httpStatus); 69 | } 70 | } else if (error is ThingsboardError) { 71 | tbError = error; 72 | } 73 | if (tbError != null && tbError.errorCode == null && tbError.status != null) { 74 | tbError.errorCode = httpStatusToThingsboardErrorCode(tbError.status!); 75 | } 76 | tbError ??= ThingsboardError( 77 | error: error, 78 | message: error.toString(), 79 | errorCode: ThingsBoardErrorCode.general); 80 | 81 | StackTrace? errorStackTrace; 82 | if (tbError.error is Error) { 83 | errorStackTrace = tbError.error.stackTrace; 84 | } 85 | 86 | tbError.stackTrace = stackTrace ?? 87 | tbError.getStackTrace() ?? 88 | errorStackTrace ?? 89 | StackTrace.current; 90 | 91 | return tbError; 92 | } 93 | -------------------------------------------------------------------------------- /lib/src/error/thingsboard_error.dart: -------------------------------------------------------------------------------- 1 | export '_thingsboard_error_handler.dart' 2 | if (dart.library.io) '_thingsboard_error_handler_io.dart' 3 | if (dart.library.html) '_thingsboard_error_handler_html.dart'; 4 | 5 | abstract class ThingsBoardErrorCode { 6 | static const int general = 2; 7 | static const int authentication = 10; 8 | static const int jwtTokenExpired = 11; 9 | static const int tenantTrialExpired = 12; 10 | static const int credentialsExpired = 15; 11 | static const int permissionDenied = 20; 12 | static const int invalidArguments = 30; 13 | static const int badRequestParams = 31; 14 | static const int itemNotFound = 32; 15 | static const int tooManyRequests = 33; 16 | static const int tooManyUpdates = 34; 17 | } 18 | 19 | class ThingsboardError implements Exception { 20 | bool? refreshTokenPending; 21 | String? message; 22 | int? errorCode; 23 | int? status; 24 | dynamic error; 25 | 26 | ThingsboardError( 27 | {this.message, 28 | this.errorCode, 29 | this.status, 30 | this.refreshTokenPending, 31 | this.error}); 32 | 33 | ThingsboardError.fromJson(Map json) 34 | : message = ThingsboardError.parseMessage(json), 35 | status = json['status'], 36 | errorCode = json['errorCode']; 37 | 38 | static String parseMessage(Map json) { 39 | String? message = json['message']; 40 | if (message == null) { 41 | if (json['error'] != null) { 42 | if (json['path'] != null) { 43 | message = "Path '" + json['path'] + "': " + json["error"]; 44 | } else { 45 | message = json['error']; 46 | } 47 | } else { 48 | message = "Unknown error"; 49 | } 50 | } 51 | return message!; 52 | } 53 | 54 | StackTrace? _stackTrace; 55 | 56 | set stackTrace(StackTrace? stack) => _stackTrace = stack; 57 | 58 | StackTrace? getStackTrace() => _stackTrace; 59 | 60 | @override 61 | String toString() { 62 | var msg = 63 | 'ThingsboardError: message: [$message], errorCode: $errorCode, status: $status'; 64 | if (_stackTrace != null) { 65 | msg += '\n$_stackTrace'; 66 | } 67 | return msg; 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /lib/src/http/http_utils.dart: -------------------------------------------------------------------------------- 1 | import 'package:dio/dio.dart'; 2 | 3 | import '../error/thingsboard_error.dart'; 4 | import '../interceptor/interceptor_config.dart'; 5 | 6 | class RequestConfig { 7 | bool ignoreLoading; 8 | bool ignoreErrors; 9 | bool resendRequest; 10 | bool followRedirect; 11 | 12 | RequestConfig( 13 | {this.ignoreLoading = false, 14 | this.ignoreErrors = false, 15 | this.resendRequest = false, 16 | this.followRedirect = true}); 17 | } 18 | 19 | Options defaultHttpOptionsFromConfig(RequestConfig? config) { 20 | config ??= RequestConfig(); 21 | return defaultHttpOptions( 22 | ignoreLoading: config.ignoreLoading, 23 | ignoreErrors: config.ignoreErrors, 24 | resendRequest: config.resendRequest, 25 | followRedirect: config.followRedirect); 26 | } 27 | 28 | Options defaultHttpOptions( 29 | {bool ignoreLoading = false, 30 | bool ignoreErrors = false, 31 | bool resendRequest = false, 32 | bool followRedirect = true}) { 33 | var interceptorConfig = InterceptorConfig( 34 | ignoreLoading: ignoreLoading, 35 | ignoreErrors: ignoreErrors, 36 | resendRequest: resendRequest); 37 | var options = Options( 38 | headers: {'Content-Type': 'application/json'}, 39 | extra: interceptorConfig.toExtra(), 40 | followRedirects: followRedirect, 41 | maxRedirects: !followRedirect ? 0 : null); 42 | return options; 43 | } 44 | 45 | Future nullIfNotFound( 46 | Future Function(RequestConfig requestConfig) fetchFunction, 47 | {RequestConfig? requestConfig}) async { 48 | try { 49 | return await fetchFunction( 50 | requestConfig ?? RequestConfig(ignoreErrors: true)); 51 | } catch (e) { 52 | if (e is ThingsboardError && 53 | e.errorCode == ThingsBoardErrorCode.itemNotFound) { 54 | return null; 55 | } else { 56 | rethrow; 57 | } 58 | } 59 | } 60 | 61 | Future isSuccessful( 62 | Future> Function(RequestConfig requestConfig) 63 | requestFunction, 64 | {RequestConfig? requestConfig}) async { 65 | try { 66 | var response = await requestFunction( 67 | requestConfig ?? RequestConfig(ignoreErrors: true)); 68 | if (response.statusCode != null) { 69 | var seriesCode = response.statusCode! ~/ 100; 70 | return seriesCode == 2; 71 | } 72 | return false; 73 | } catch (e) { 74 | return false; 75 | } 76 | } 77 | -------------------------------------------------------------------------------- /lib/src/interceptor/interceptor_config.dart: -------------------------------------------------------------------------------- 1 | class InterceptorConfig { 2 | bool ignoreLoading = false; 3 | bool ignoreErrors = false; 4 | bool resendRequest = false; 5 | bool isRetry = false; 6 | 7 | InterceptorConfig( 8 | {this.ignoreLoading = false, 9 | this.ignoreErrors = false, 10 | this.resendRequest = false, 11 | this.isRetry = false}); 12 | 13 | InterceptorConfig.fromExtra(Map? extra) { 14 | if (extra != null) { 15 | ignoreLoading = extra['ignoreLoading'] ?? false; 16 | ignoreErrors = extra['ignoreErrors'] ?? false; 17 | resendRequest = extra['resendRequest'] ?? false; 18 | isRetry = extra['isRetry'] ?? false; 19 | } 20 | } 21 | 22 | Map toExtra() { 23 | return { 24 | 'ignoreLoading': ignoreLoading, 25 | 'ignoreErrors': ignoreErrors, 26 | 'resendRequest': resendRequest, 27 | 'isRetry': isRetry 28 | }; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /lib/src/model/additional_info_based.dart: -------------------------------------------------------------------------------- 1 | import 'has_additional_info.dart'; 2 | 3 | import 'base_data.dart'; 4 | import 'id/has_uuid.dart'; 5 | 6 | abstract class AdditionalInfoBased extends BaseData 7 | with HasAdditionalInfo { 8 | Map? additionalInfo; 9 | 10 | AdditionalInfoBased(); 11 | 12 | AdditionalInfoBased.fromJson(Map json, 13 | [FromIdFunction? fromId]) 14 | : additionalInfo = json['additionalInfo'], 15 | super.fromJson(json, fromId); 16 | 17 | @override 18 | Map toJson() { 19 | var json = super.toJson(); 20 | if (additionalInfo != null) { 21 | json['additionalInfo'] = additionalInfo; 22 | } 23 | return json; 24 | } 25 | 26 | @override 27 | Map? getAdditionalInfo() { 28 | return additionalInfo; 29 | } 30 | 31 | @override 32 | String toString() { 33 | return 'AdditionalInfoBased{${additionalInfoBasedString()}}'; 34 | } 35 | 36 | String additionalInfoBasedString([String? toStringBody]) { 37 | return '${baseDataString('${toStringBody != null ? toStringBody + ',' : ''} additionalInfo: $additionalInfo')}'; 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /lib/src/model/audit_log_models.dart: -------------------------------------------------------------------------------- 1 | import 'dart:convert'; 2 | import 'dart:math'; 3 | 4 | import 'id/audit_log_id.dart'; 5 | import 'id/customer_id.dart'; 6 | import 'id/entity_id.dart'; 7 | 8 | import 'base_data.dart'; 9 | import 'id/tenant_id.dart'; 10 | import 'id/user_id.dart'; 11 | 12 | enum ActionType { 13 | ADDED, 14 | DELETED, 15 | UPDATED, 16 | ATTRIBUTES_UPDATED, 17 | ATTRIBUTES_DELETED, 18 | RPC_CALL, 19 | CREDENTIALS_UPDATED, 20 | ASSIGNED_TO_CUSTOMER, 21 | UNASSIGNED_FROM_CUSTOMER, 22 | ACTIVATED, 23 | SUSPENDED, 24 | CREDENTIALS_READ, 25 | ATTRIBUTES_READ, 26 | RELATION_ADD_OR_UPDATE, 27 | RELATION_DELETED, 28 | RELATIONS_DELETED, 29 | ALARM_ACK, 30 | ALARM_CLEAR, 31 | ALARM_DELETE, 32 | ALARM_ASSIGNED, 33 | ALARM_UNASSIGNED, 34 | LOGIN, 35 | LOGOUT, 36 | LOCKOUT, 37 | ASSIGNED_FROM_TENANT, 38 | ASSIGNED_TO_TENANT, 39 | PROVISION_SUCCESS, 40 | PROVISION_FAILURE, 41 | TIMESERIES_UPDATED, 42 | TIMESERIES_DELETED, 43 | ASSIGNED_TO_EDGE, 44 | UNASSIGNED_FROM_EDGE, 45 | ADDED_COMMENT, 46 | UPDATED_COMMENT, 47 | DELETED_COMMENT, 48 | SMS_SENT 49 | } 50 | 51 | ActionType actionTypeFromString(String value) { 52 | return ActionType.values.firstWhere( 53 | (e) => e.toString().split('.')[1].toUpperCase() == value.toUpperCase()); 54 | } 55 | 56 | extension ActionTypeToString on ActionType { 57 | String toShortString() { 58 | return toString().split('.').last; 59 | } 60 | } 61 | 62 | enum ActionStatus { SUCCESS, FAILURE } 63 | 64 | ActionStatus actionStatusFromString(String value) { 65 | return ActionStatus.values.firstWhere( 66 | (e) => e.toString().split('.')[1].toUpperCase() == value.toUpperCase()); 67 | } 68 | 69 | extension ActionStatusToString on ActionStatus { 70 | String toShortString() { 71 | return toString().split('.').last; 72 | } 73 | } 74 | 75 | class AuditLog extends BaseData { 76 | TenantId tenantId; 77 | CustomerId? customerId; 78 | EntityId entityId; 79 | String? entityName; 80 | UserId userId; 81 | String userName; 82 | ActionType actionType; 83 | Map actionData; 84 | ActionStatus actionStatus; 85 | String? actionFailureDetails; 86 | 87 | AuditLog.fromJson(Map json) 88 | : tenantId = TenantId.fromJson(json['tenantId']), 89 | customerId = json['customerId'] != null 90 | ? CustomerId.fromJson(json['customerId']) 91 | : null, 92 | entityId = EntityId.fromJson(json['entityId']), 93 | entityName = json['entityName'], 94 | userId = UserId.fromJson(json['userId']), 95 | userName = json['userName'], 96 | actionType = actionTypeFromString(json['actionType']), 97 | actionData = json['actionData'], 98 | actionStatus = actionStatusFromString(json['actionStatus']), 99 | actionFailureDetails = json['actionFailureDetails'], 100 | super.fromJson(json, (id) => AuditLogId(id)); 101 | 102 | @override 103 | String toString() { 104 | return 'AuditLog{${baseDataString('tenantId: $tenantId, customerId: $customerId, entityId: $entityId, ' 105 | 'entityName: $entityName, userId: $userId, userName: $userName, actionType: $actionType, ' 106 | 'actionData: ${actionDataToString()}, actionStatus: $actionStatus, actionFailureDetails: ${actionFailureDetailsToString()}')}}'; 107 | } 108 | 109 | String actionDataToString() { 110 | var actionDataStr = jsonEncode(actionData); 111 | if (actionDataStr.length > 50) { 112 | actionDataStr = 113 | actionDataStr.substring(0, min(50, actionDataStr.length)) + '...'; 114 | } 115 | return actionDataStr; 116 | } 117 | 118 | String actionFailureDetailsToString() { 119 | if (actionFailureDetails == null) { 120 | return 'null'; 121 | } 122 | if (actionFailureDetails!.length > 50) { 123 | return actionFailureDetails! 124 | .substring(0, min(50, actionFailureDetails!.length)) + 125 | '...'; 126 | } 127 | return actionFailureDetails!; 128 | } 129 | } 130 | -------------------------------------------------------------------------------- /lib/src/model/authority_enum.dart: -------------------------------------------------------------------------------- 1 | enum Authority { 2 | SYS_ADMIN, 3 | TENANT_ADMIN, 4 | CUSTOMER_USER, 5 | REFRESH_TOKEN, 6 | ANONYMOUS, 7 | PRE_VERIFICATION_TOKEN 8 | } 9 | 10 | Authority authorityFromString(String value) { 11 | return Authority.values.firstWhere( 12 | (e) => e.toString().split('.')[1].toUpperCase() == value.toUpperCase()); 13 | } 14 | 15 | extension AuthorityToString on Authority { 16 | String toShortString() { 17 | return toString().split('.').last; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /lib/src/model/base_data.dart: -------------------------------------------------------------------------------- 1 | import 'id/has_uuid.dart'; 2 | import 'id/id_based.dart'; 3 | 4 | typedef FromJsonFunction = T Function(dynamic json); 5 | 6 | abstract class BaseData extends IdBased { 7 | int? createdTime; 8 | 9 | BaseData(); 10 | 11 | BaseData.fromJson(Map json, [FromIdFunction? fromId]) 12 | : createdTime = json['createdTime'], 13 | super.fromJson(json, fromId); 14 | 15 | @override 16 | Map toJson() { 17 | var json = super.toJson(); 18 | if (createdTime != null) { 19 | json['createdTime'] = createdTime; 20 | } 21 | return json; 22 | } 23 | 24 | @override 25 | String toString() { 26 | return 'BaseData{${baseDataString()}}'; 27 | } 28 | 29 | int? getCreatedTime() { 30 | return createdTime; 31 | } 32 | 33 | void setCreatedTime(int? createdTime) { 34 | this.createdTime = createdTime; 35 | } 36 | 37 | String baseDataString([String? toStringBody]) { 38 | return '${idBasedString()}, createdTime: $createdTime${toStringBody != null ? ', ' + toStringBody : ''}'; 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /lib/src/model/component_descriptor_models.dart: -------------------------------------------------------------------------------- 1 | import 'base_data.dart'; 2 | import 'id/component_descriptor_id.dart'; 3 | 4 | enum ComponentType { ENRICHMENT, FILTER, TRANSFORMATION, ACTION, EXTERNAL } 5 | 6 | ComponentType componentTypeFromString(String value) { 7 | return ComponentType.values.firstWhere( 8 | (e) => e.toString().split('.')[1].toUpperCase() == value.toUpperCase()); 9 | } 10 | 11 | extension ComponentTypeToString on ComponentType { 12 | String toShortString() { 13 | return toString().split('.').last; 14 | } 15 | } 16 | 17 | enum ComponentScope { SYSTEM, TENANT } 18 | 19 | ComponentScope componentScopeFromString(String value) { 20 | return ComponentScope.values.firstWhere( 21 | (e) => e.toString().split('.')[1].toUpperCase() == value.toUpperCase()); 22 | } 23 | 24 | extension ComponentScopeToString on ComponentScope { 25 | String toShortString() { 26 | return toString().split('.').last; 27 | } 28 | } 29 | 30 | enum ComponentClusteringMode { USER_PREFERENCE, ENABLED, SINGLETON } 31 | 32 | ComponentClusteringMode componentClusteringModeFromString(String value) { 33 | return ComponentClusteringMode.values.firstWhere( 34 | (e) => e.toString().split('.')[1].toUpperCase() == value.toUpperCase()); 35 | } 36 | 37 | extension ComponentClusteringModeToString on ComponentClusteringMode { 38 | String toShortString() { 39 | return toString().split('.').last; 40 | } 41 | } 42 | 43 | class ComponentDescriptor extends BaseData { 44 | ComponentType type; 45 | ComponentScope scope; 46 | final ComponentClusteringMode clusteringMode; 47 | String name; 48 | String clazz; 49 | Map? configurationDescriptor; 50 | final int configurationVersion; 51 | String? actions; 52 | 53 | ComponentDescriptor.fromJson(Map json) 54 | : type = componentTypeFromString(json['type']), 55 | scope = componentScopeFromString(json['scope']), 56 | clusteringMode = 57 | componentClusteringModeFromString(json['clusteringMode']), 58 | name = json['name'], 59 | clazz = json['clazz'], 60 | configurationDescriptor = json['configurationDescriptor'], 61 | configurationVersion = json['configurationVersion'], 62 | actions = json['actions'], 63 | super.fromJson(json, (id) => ComponentDescriptorId(id)); 64 | 65 | @override 66 | String toString() { 67 | return 'ComponentDescriptor{${baseDataString('type: $type, scope: $scope, name: $name, clusteringMode: $clusteringMode, ' 68 | 'clazz: $clazz, configurationDescriptor: $configurationDescriptor, ' 69 | 'configurationVersion: $configurationVersion, actions: $actions')}}'; 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /lib/src/model/constants.dart: -------------------------------------------------------------------------------- 1 | class Constants { 2 | static const entryPoints = { 3 | 'login': '/api/auth/login', 4 | 'tokenRefresh': '/api/auth/token', 5 | 'nonTokenBased': '/api/noauth' 6 | }; 7 | } 8 | -------------------------------------------------------------------------------- /lib/src/model/contact_based_model.dart: -------------------------------------------------------------------------------- 1 | import 'additional_info_based.dart'; 2 | import 'has_name.dart'; 3 | import 'id/has_uuid.dart'; 4 | 5 | abstract class ContactBased extends AdditionalInfoBased 6 | with HasName { 7 | String? country; 8 | String? state; 9 | String? city; 10 | String? address; 11 | String? address2; 12 | String? zip; 13 | String? phone; 14 | String? email; 15 | 16 | ContactBased(); 17 | 18 | ContactBased.fromJson(Map json) 19 | : country = json['country'], 20 | state = json['state'], 21 | city = json['city'], 22 | address = json['address'], 23 | address2 = json['address2'], 24 | zip = json['zip'], 25 | phone = json['phone'], 26 | email = json['email'], 27 | super.fromJson(json); 28 | 29 | @override 30 | Map toJson() { 31 | var json = super.toJson(); 32 | if (country != null) { 33 | json['country'] = country; 34 | } 35 | if (state != null) { 36 | json['state'] = state; 37 | } 38 | if (city != null) { 39 | json['city'] = city; 40 | } 41 | if (address != null) { 42 | json['address'] = address; 43 | } 44 | if (address2 != null) { 45 | json['address2'] = address2; 46 | } 47 | if (zip != null) { 48 | json['zip'] = zip; 49 | } 50 | if (phone != null) { 51 | json['phone'] = phone; 52 | } 53 | if (email != null) { 54 | json['email'] = email; 55 | } 56 | return json; 57 | } 58 | 59 | @override 60 | String toString() { 61 | return 'ContactBased{${contactBasedString()}}'; 62 | } 63 | 64 | String contactBasedString([String? toStringBody]) { 65 | return '${additionalInfoBasedString('${toStringBody != null ? toStringBody + ', ' : ''}country: $country, state: $state, city: $city, address: $address, address2: $address2, zip: $zip, phone: $phone, email: $email')}'; 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /lib/src/model/customer_models.dart: -------------------------------------------------------------------------------- 1 | import 'exportable_entity.dart'; 2 | import 'has_customer_id.dart'; 3 | import 'has_tenant_id.dart'; 4 | import 'id/customer_id.dart'; 5 | import 'id/tenant_id.dart'; 6 | import 'contact_based_model.dart'; 7 | 8 | class Customer extends ContactBased 9 | with HasTenantId, HasCustomerId, ExportableEntity { 10 | TenantId? tenantId; 11 | String title; 12 | CustomerId? externalId; 13 | 14 | Customer(this.title); 15 | 16 | Customer.fromJson(Map json) 17 | : tenantId = TenantId.fromJson(json['tenantId']), 18 | title = json['title'], 19 | externalId = json['externalId'] != null 20 | ? CustomerId.fromJson(json['externalId']) 21 | : null, 22 | super.fromJson(json); 23 | 24 | @override 25 | Map toJson() { 26 | var json = super.toJson(); 27 | if (tenantId != null) { 28 | json['tenantId'] = tenantId!.toJson(); 29 | } 30 | json['title'] = title; 31 | if (externalId != null) { 32 | json['externalId'] = externalId!.toJson(); 33 | } 34 | return json; 35 | } 36 | 37 | @override 38 | String getName() { 39 | return title; 40 | } 41 | 42 | @override 43 | TenantId? getTenantId() { 44 | return tenantId; 45 | } 46 | 47 | @override 48 | void setTenantId(TenantId? tenantId) { 49 | this.tenantId = tenantId; 50 | } 51 | 52 | @override 53 | CustomerId? getCustomerId() { 54 | return id; 55 | } 56 | 57 | @override 58 | CustomerId? getExternalId() { 59 | return externalId; 60 | } 61 | 62 | @override 63 | void setExternalId(CustomerId? externalId) { 64 | this.externalId = externalId; 65 | } 66 | 67 | @override 68 | String toString() { 69 | return 'Customer{${contactBasedString('tenantId: $tenantId, title: $title, externalId: $externalId')}}'; 70 | } 71 | } 72 | 73 | class ShortCustomerInfo { 74 | CustomerId customerId; 75 | String title; 76 | bool isPublic; 77 | 78 | ShortCustomerInfo.fromJson(Map json) 79 | : customerId = CustomerId.fromJson(json['customerId']), 80 | title = json['title'], 81 | isPublic = json['isPublic'] ?? false; 82 | 83 | Map toJson() { 84 | var json = { 85 | 'customerId': customerId.toJson(), 86 | 'title': title, 87 | 'isPublic': isPublic 88 | }; 89 | return json; 90 | } 91 | 92 | @override 93 | String toString() { 94 | return 'ShortCustomerInfo{customerId: $customerId, title: $title, isPublic: $isPublic}'; 95 | } 96 | } 97 | -------------------------------------------------------------------------------- /lib/src/model/dashboard_models.dart: -------------------------------------------------------------------------------- 1 | import 'dart:math'; 2 | 3 | import 'customer_models.dart'; 4 | import 'base_data.dart'; 5 | import 'exportable_entity.dart'; 6 | import 'id/tenant_id.dart'; 7 | import 'has_name.dart'; 8 | import 'has_tenant_id.dart'; 9 | import 'id/dashboard_id.dart'; 10 | 11 | class DashboardInfo extends BaseData with HasName, HasTenantId { 12 | TenantId? tenantId; 13 | String title; 14 | String? image; 15 | Set assignedCustomers; 16 | bool? mobileHide; 17 | int? mobileOrder; 18 | 19 | DashboardInfo(this.title) : assignedCustomers = {}; 20 | 21 | DashboardInfo.fromJson(Map json) 22 | : tenantId = TenantId.fromJson(json['tenantId']), 23 | title = json['title'], 24 | image = json['image'], 25 | assignedCustomers = json['assignedCustomers'] != null 26 | ? (json['assignedCustomers'] as List) 27 | .map((e) => ShortCustomerInfo.fromJson(e)) 28 | .toSet() 29 | : {}, 30 | mobileHide = json['mobileHide'], 31 | mobileOrder = json['mobileOrder'], 32 | super.fromJson(json); 33 | 34 | @override 35 | Map toJson() { 36 | var json = super.toJson(); 37 | if (tenantId != null) { 38 | json['tenantId'] = tenantId!.toJson(); 39 | } 40 | json['title'] = title; 41 | if (image != null) { 42 | json['image'] = image; 43 | } 44 | json['assignedCustomers'] = 45 | assignedCustomers.map((e) => e.toJson()).toList(); 46 | if (mobileHide != null) { 47 | json['mobileHide'] = mobileHide; 48 | } 49 | if (mobileOrder != null) { 50 | json['mobileOrder'] = mobileOrder; 51 | } 52 | return json; 53 | } 54 | 55 | @override 56 | String getName() { 57 | return title; 58 | } 59 | 60 | @override 61 | TenantId? getTenantId() { 62 | return tenantId; 63 | } 64 | 65 | @override 66 | String toString() { 67 | return 'DashboardInfo{${dashboardInfoString()}}'; 68 | } 69 | 70 | String dashboardInfoString([String? toStringBody]) { 71 | return '${baseDataString('tenantId: $tenantId, title: $title, image: ${image != null ? '[' + image!.substring(0, min(30, image!.length)) + '...]' : 'null'}, ' 72 | 'mobileHide: $mobileHide, mobileOrder: $mobileOrder, assignedCustomers: $assignedCustomers${toStringBody != null ? ', ' + toStringBody : ''}')}'; 73 | } 74 | } 75 | 76 | class Dashboard extends DashboardInfo with ExportableEntity { 77 | Map configuration; 78 | DashboardId? externalId; 79 | 80 | Dashboard(String title) 81 | : configuration = {}, 82 | super(title); 83 | 84 | Dashboard.fromJson(Map json) 85 | : configuration = json['configuration'], 86 | externalId = json['externalId'] != null 87 | ? DashboardId.fromJson(json['externalId']) 88 | : null, 89 | super.fromJson(json); 90 | 91 | @override 92 | Map toJson() { 93 | var json = super.toJson(); 94 | json['configuration'] = configuration; 95 | if (externalId != null) { 96 | json['externalId'] = externalId!.toJson(); 97 | } 98 | return json; 99 | } 100 | 101 | @override 102 | void setTenantId(TenantId? tenantId) { 103 | this.tenantId = tenantId; 104 | } 105 | 106 | @override 107 | DashboardId? getExternalId() { 108 | return externalId; 109 | } 110 | 111 | @override 112 | void setExternalId(DashboardId? externalId) { 113 | this.externalId = externalId; 114 | } 115 | 116 | @override 117 | String toString() { 118 | return 'Dashboard{${dashboardInfoString('configuration: $configuration, externalId: $externalId')}}'; 119 | } 120 | } 121 | 122 | class HomeDashboard extends Dashboard { 123 | bool hideDashboardToolbar; 124 | 125 | HomeDashboard(String title, this.hideDashboardToolbar) : super(title); 126 | 127 | HomeDashboard.fromJson(Map json) 128 | : hideDashboardToolbar = json['hideDashboardToolbar'], 129 | super.fromJson(json); 130 | 131 | @override 132 | Map toJson() { 133 | var json = super.toJson(); 134 | json['hideDashboardToolbar'] = hideDashboardToolbar; 135 | return json; 136 | } 137 | 138 | @override 139 | String toString() { 140 | return 'HomeDashboard{${dashboardInfoString('hideDashboardToolbar: $hideDashboardToolbar, configuration: $configuration')}}'; 141 | } 142 | } 143 | 144 | class HomeDashboardInfo { 145 | DashboardId? dashboardId; 146 | bool hideDashboardToolbar; 147 | 148 | HomeDashboardInfo(this.hideDashboardToolbar); 149 | 150 | HomeDashboardInfo.fromJson(Map json) 151 | : dashboardId = json['dashboardId'] != null 152 | ? DashboardId.fromJson(json['dashboardId']) 153 | : null, 154 | hideDashboardToolbar = json['hideDashboardToolbar']; 155 | 156 | Map toJson() { 157 | var json = {}; 158 | if (dashboardId != null) { 159 | json['dashboardId'] = dashboardId!.toJson(); 160 | } 161 | json['hideDashboardToolbar'] = hideDashboardToolbar; 162 | return json; 163 | } 164 | 165 | @override 166 | String toString() { 167 | return 'HomeDashboardInfo{dashboardId: $dashboardId, hideDashboardToolbar: $hideDashboardToolbar}'; 168 | } 169 | } 170 | -------------------------------------------------------------------------------- /lib/src/model/entity_models.dart: -------------------------------------------------------------------------------- 1 | import 'id/entity_id.dart'; 2 | 3 | class EntityInfo { 4 | EntityId id; 5 | String name; 6 | 7 | EntityInfo(this.id, this.name); 8 | 9 | EntityInfo.fromJson(Map json) 10 | : id = EntityId.fromJson(json['id']), 11 | name = json['name']; 12 | 13 | @override 14 | String toString() { 15 | return 'EntityInfo{${entityInfoString()}}'; 16 | } 17 | 18 | String entityInfoString([String? toStringBody]) { 19 | return 'id: $id, name: $name${toStringBody != null ? ', ' + toStringBody : ''}'; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /lib/src/model/entity_type_models.dart: -------------------------------------------------------------------------------- 1 | import 'id/tenant_id.dart'; 2 | 3 | enum EntityType { 4 | TENANT, 5 | TENANT_PROFILE, 6 | CUSTOMER, 7 | USER, 8 | DASHBOARD, 9 | ASSET, 10 | DEVICE, 11 | DEVICE_PROFILE, 12 | ASSET_PROFILE, 13 | ALARM, 14 | RULE_CHAIN, 15 | RULE_NODE, 16 | EDGE, 17 | ENTITY_VIEW, 18 | WIDGETS_BUNDLE, 19 | WIDGET_TYPE, 20 | API_USAGE_STATE, 21 | TB_RESOURCE, 22 | OTA_PACKAGE, 23 | RPC, 24 | QUEUE, 25 | NOTIFICATION_TARGET, 26 | NOTIFICATION_TEMPLATE, 27 | NOTIFICATION_REQUEST, 28 | NOTIFICATION, 29 | NOTIFICATION_RULE 30 | } 31 | 32 | EntityType entityTypeFromString(String value) { 33 | return EntityType.values.firstWhere( 34 | (e) => e.toString().split('.')[1].toUpperCase() == value.toUpperCase()); 35 | } 36 | 37 | extension EntityTypeToString on EntityType { 38 | String toShortString() { 39 | return toString().split('.').last; 40 | } 41 | } 42 | 43 | class EntitySubtype { 44 | TenantId tenantId; 45 | EntityType entityType; 46 | String type; 47 | 48 | EntitySubtype.fromJson(Map json) 49 | : tenantId = TenantId.fromJson(json['tenantId']), 50 | entityType = entityTypeFromString(json['entityType']), 51 | type = json['type']; 52 | 53 | @override 54 | String toString() { 55 | return 'EntitySubtype{tenantId: $tenantId, entityType: $entityType, type: $type}'; 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /lib/src/model/entity_view_models.dart: -------------------------------------------------------------------------------- 1 | import 'exportable_entity.dart'; 2 | import 'relation_models.dart'; 3 | import 'has_customer_id.dart'; 4 | import 'has_name.dart'; 5 | import 'has_tenant_id.dart'; 6 | import 'id/customer_id.dart'; 7 | import 'id/entity_id.dart'; 8 | import 'id/entity_view_id.dart'; 9 | import 'additional_info_based.dart'; 10 | import 'id/tenant_id.dart'; 11 | 12 | class AttributesEntityView { 13 | List cs; 14 | List ss; 15 | List sh; 16 | 17 | AttributesEntityView() 18 | : cs = [], 19 | ss = [], 20 | sh = []; 21 | 22 | AttributesEntityView.fromJson(Map json) 23 | : cs = json['cs'], 24 | ss = json['ss'], 25 | sh = json['sh']; 26 | 27 | Map toJson() => {'cs': cs, 'ss': ss, 'sh': sh}; 28 | 29 | @override 30 | String toString() { 31 | return 'AttributesEntityView{cs: $cs, ss: $ss, sh: $sh}'; 32 | } 33 | } 34 | 35 | class TelemetryEntityView { 36 | List timeseries; 37 | AttributesEntityView attributes; 38 | 39 | TelemetryEntityView() 40 | : timeseries = [], 41 | attributes = AttributesEntityView(); 42 | 43 | TelemetryEntityView.fromJson(Map json) 44 | : timeseries = json['timeseries'], 45 | attributes = AttributesEntityView.fromJson(json['attributes']); 46 | 47 | Map toJson() => 48 | {'timeseries': timeseries, 'attributes': attributes.toJson()}; 49 | 50 | @override 51 | String toString() { 52 | return 'TelemetryEntityView{timeseries: $timeseries, attributes: $attributes}'; 53 | } 54 | } 55 | 56 | class EntityView extends AdditionalInfoBased 57 | with HasName, HasTenantId, HasCustomerId, ExportableEntity { 58 | TenantId? tenantId; 59 | CustomerId? customerId; 60 | EntityId entityId; 61 | String name; 62 | String type; 63 | TelemetryEntityView keys; 64 | int? startTimeMs; 65 | int? endTimeMs; 66 | EntityViewId? externalId; 67 | 68 | EntityView( 69 | {required this.entityId, 70 | required this.name, 71 | required this.type, 72 | required this.keys, 73 | this.startTimeMs, 74 | this.endTimeMs}); 75 | 76 | EntityView.fromJson(Map json) 77 | : tenantId = TenantId.fromJson(json['tenantId']), 78 | customerId = json['customerId'] != null 79 | ? CustomerId.fromJson(json['customerId']) 80 | : null, 81 | entityId = EntityId.fromJson(json['entityId']), 82 | name = json['name'], 83 | type = json['type'], 84 | keys = TelemetryEntityView.fromJson(json['keys']), 85 | startTimeMs = json['startTimeMs'], 86 | endTimeMs = json['endTimeMs'], 87 | externalId = json['externalId'] != null 88 | ? EntityViewId.fromJson(json['externalId']) 89 | : null, 90 | super.fromJson(json); 91 | 92 | @override 93 | Map toJson() { 94 | var json = super.toJson(); 95 | if (tenantId != null) { 96 | json['tenantId'] = tenantId!.toJson(); 97 | } 98 | if (customerId != null) { 99 | json['customerId'] = customerId!.toJson(); 100 | } 101 | json['entityId'] = entityId.toJson(); 102 | json['name'] = name; 103 | json['type'] = type; 104 | json['keys'] = keys.toJson(); 105 | if (startTimeMs != null) { 106 | json['startTimeMs'] = startTimeMs; 107 | } 108 | if (endTimeMs != null) { 109 | json['endTimeMs'] = endTimeMs; 110 | } 111 | if (externalId != null) { 112 | json['externalId'] = externalId!.toJson(); 113 | } 114 | return json; 115 | } 116 | 117 | @override 118 | String getName() { 119 | return name; 120 | } 121 | 122 | @override 123 | TenantId? getTenantId() { 124 | return tenantId; 125 | } 126 | 127 | @override 128 | void setTenantId(TenantId? tenantId) { 129 | this.tenantId = tenantId; 130 | } 131 | 132 | @override 133 | CustomerId? getCustomerId() { 134 | return customerId; 135 | } 136 | 137 | @override 138 | EntityViewId? getExternalId() { 139 | return externalId; 140 | } 141 | 142 | @override 143 | void setExternalId(EntityViewId? externalId) { 144 | this.externalId = externalId; 145 | } 146 | 147 | @override 148 | String toString() { 149 | return 'EntityView{${entityViewString()}}'; 150 | } 151 | 152 | String entityViewString([String? toStringBody]) { 153 | return '${additionalInfoBasedString('tenantId: $tenantId, customerId: $customerId, entityId: $entityId, name: $name, type: $type, ' 154 | 'keys: $keys, startTimeMs: $startTimeMs, endTimeMs: $endTimeMs, externalId: $externalId${toStringBody != null ? ', ' + toStringBody : ''}')}'; 155 | } 156 | } 157 | 158 | class EntityViewInfo extends EntityView { 159 | String? customerTitle; 160 | bool? customerIsPublic; 161 | 162 | EntityViewInfo.fromJson(Map json) 163 | : customerTitle = json['customerTitle'], 164 | customerIsPublic = json['customerIsPublic'], 165 | super.fromJson(json); 166 | 167 | @override 168 | String toString() { 169 | return 'EntityViewInfo{${entityViewString('customerTitle: $customerTitle, customerIsPublic: $customerIsPublic')}}'; 170 | } 171 | } 172 | 173 | class EntityViewSearchQuery extends EntitySearchQuery { 174 | List entityViewTypes; 175 | 176 | EntityViewSearchQuery( 177 | {required RelationsSearchParameters parameters, 178 | required this.entityViewTypes, 179 | String? relationType}) 180 | : super(parameters: parameters, relationType: relationType); 181 | 182 | @override 183 | Map toJson() { 184 | var json = super.toJson(); 185 | json['entityViewTypes'] = entityViewTypes; 186 | return json; 187 | } 188 | 189 | @override 190 | String toString() { 191 | return 'EntityViewSearchQuery{${entitySearchQueryString('entityViewTypes: $entityViewTypes')}}'; 192 | } 193 | } 194 | -------------------------------------------------------------------------------- /lib/src/model/event_models.dart: -------------------------------------------------------------------------------- 1 | import 'id/entity_id.dart'; 2 | 3 | import 'base_data.dart'; 4 | import 'id/event_id.dart'; 5 | import 'id/tenant_id.dart'; 6 | 7 | class Event extends BaseData { 8 | TenantId tenantId; 9 | EntityId entityId; 10 | String type; 11 | String uid; 12 | EventBody body; 13 | 14 | Event.fromJson(Map json) 15 | : tenantId = TenantId.fromJson(json['tenantId']), 16 | entityId = EntityId.fromJson(json['entityId']), 17 | type = json['type'], 18 | uid = json['uid'], 19 | body = EventBody.fromJson(json['type'], json['body']), 20 | super.fromJson(json, (id) => EventId(id)); 21 | 22 | @override 23 | String toString() { 24 | return 'Event{${baseDataString('tenantId: $tenantId, entityId: $entityId, type: $type, uid: $uid, body: $body')}}'; 25 | } 26 | } 27 | 28 | enum EventType { 29 | ERROR, 30 | LC_EVENT, 31 | STATS, 32 | DEBUG_RULE_NODE, 33 | DEBUG_RULE_CHAIN, 34 | RAW 35 | } 36 | 37 | abstract class EventBody { 38 | static const ERROR = 'ERROR'; 39 | static const LC_EVENT = 'LC_EVENT'; 40 | static const STATS = 'STATS'; 41 | static const DEBUG_RULE_NODE = 'DEBUG_RULE_NODE'; 42 | static const DEBUG_RULE_CHAIN = 'DEBUG_RULE_CHAIN'; 43 | 44 | EventBody(); 45 | 46 | EventType getEventType(); 47 | 48 | factory EventBody.fromJson(String type, Map json) { 49 | switch (type) { 50 | case ERROR: 51 | return ErrorEventBody.fromJson(json); 52 | case LC_EVENT: 53 | return LcEventEventBody.fromJson(json); 54 | case STATS: 55 | return StatsEventBody.fromJson(json); 56 | case DEBUG_RULE_NODE: 57 | return DebugRuleNodeEventBody.fromJson(json); 58 | case DEBUG_RULE_CHAIN: 59 | return DebugRuleChainEventBody.fromJson(json); 60 | default: 61 | return RawEventBody.fromJson(json); 62 | } 63 | } 64 | } 65 | 66 | class RawEventBody extends EventBody { 67 | Map rawBody; 68 | 69 | @override 70 | EventType getEventType() => EventType.RAW; 71 | 72 | RawEventBody.fromJson(Map json) : rawBody = json; 73 | 74 | @override 75 | String toString() { 76 | return 'RawEventBody{rawBody: $rawBody}'; 77 | } 78 | } 79 | 80 | abstract class BaseEventBody extends EventBody { 81 | String server; 82 | 83 | BaseEventBody.fromJson(Map json) : server = json['server']; 84 | 85 | String baseEventBodyString([String? toStringBody]) { 86 | return 'server: $server${toStringBody != null ? ', ' + toStringBody : ''}'; 87 | } 88 | } 89 | 90 | class ErrorEventBody extends BaseEventBody { 91 | String method; 92 | String error; 93 | 94 | @override 95 | EventType getEventType() => EventType.ERROR; 96 | 97 | ErrorEventBody.fromJson(Map json) 98 | : method = json['method'], 99 | error = json['error'], 100 | super.fromJson(json); 101 | 102 | @override 103 | String toString() { 104 | return 'ErrorEventBody{${baseEventBodyString('method: $method, error: $error')}}'; 105 | } 106 | } 107 | 108 | class LcEventEventBody extends BaseEventBody { 109 | String event; 110 | bool success; 111 | String? error; 112 | 113 | @override 114 | EventType getEventType() => EventType.LC_EVENT; 115 | 116 | LcEventEventBody.fromJson(Map json) 117 | : event = json['event'], 118 | success = json['success'], 119 | error = json['error'], 120 | super.fromJson(json); 121 | 122 | @override 123 | String toString() { 124 | return 'LcEventEventBody{${baseEventBodyString('event: $event, success: $success, error: $error')}}'; 125 | } 126 | } 127 | 128 | class StatsEventBody extends BaseEventBody { 129 | int messagesProcessed; 130 | int errorsOccurred; 131 | 132 | @override 133 | EventType getEventType() => EventType.STATS; 134 | 135 | StatsEventBody.fromJson(Map json) 136 | : messagesProcessed = json['messagesProcessed'], 137 | errorsOccurred = json['errorsOccurred'], 138 | super.fromJson(json); 139 | 140 | @override 141 | String toString() { 142 | return 'StatsEventBody{${baseEventBodyString('messagesProcessed: $messagesProcessed, errorsOccurred: $errorsOccurred')}}'; 143 | } 144 | } 145 | 146 | class DebugRuleNodeEventBody extends BaseEventBody { 147 | String type; 148 | String entityId; 149 | String entityName; 150 | String msgId; 151 | String msgType; 152 | String relationType; 153 | ContentType dataType; 154 | String data; 155 | String metadata; 156 | String? error; 157 | 158 | @override 159 | EventType getEventType() => EventType.DEBUG_RULE_NODE; 160 | 161 | DebugRuleNodeEventBody.fromJson(Map json) 162 | : type = json['type'], 163 | entityId = json['entityId'], 164 | entityName = json['entityName'], 165 | msgId = json['msgId'], 166 | msgType = json['msgType'], 167 | relationType = json['relationType'], 168 | dataType = contentTypeFromString(json['dataType']), 169 | data = json['data'], 170 | metadata = json['metadata'], 171 | error = json['error'], 172 | super.fromJson(json); 173 | 174 | @override 175 | String toString() { 176 | return 'DebugRuleNodeEventBody{${baseEventBodyString('type: $type, entityId: $entityId, entityName: $entityName, msgId: $msgId, ' 177 | 'msgType: $msgType, relationType: $relationType, dataType: ${dataType.toShortString()}, data: $data, metadata: $metadata, error: $error')}}'; 178 | } 179 | } 180 | 181 | class DebugRuleChainEventBody extends BaseEventBody { 182 | String message; 183 | String? error; 184 | 185 | @override 186 | EventType getEventType() => EventType.DEBUG_RULE_CHAIN; 187 | 188 | DebugRuleChainEventBody.fromJson(Map json) 189 | : message = json['message'], 190 | error = json['error'], 191 | super.fromJson(json); 192 | 193 | @override 194 | String toString() { 195 | return 'DebugRuleChainEventBody{${baseEventBodyString('message: $message, error: $error')}}'; 196 | } 197 | } 198 | 199 | enum ContentType { JSON, TEXT, BINARY } 200 | 201 | ContentType contentTypeFromString(String value) { 202 | return ContentType.values.firstWhere( 203 | (e) => e.toString().split('.')[1].toUpperCase() == value.toUpperCase()); 204 | } 205 | 206 | extension ContentTypeToString on ContentType { 207 | String toShortString() { 208 | return toString().split('.').last; 209 | } 210 | } 211 | -------------------------------------------------------------------------------- /lib/src/model/exportable_entity.dart: -------------------------------------------------------------------------------- 1 | import 'model.dart'; 2 | 3 | abstract mixin class ExportableEntity { 4 | void setId(I? id); 5 | 6 | I? getExternalId(); 7 | 8 | void setExternalId(I? externalId); 9 | 10 | int? getCreatedTime(); 11 | 12 | void setCreatedTime(int? createdTime); 13 | 14 | void setTenantId(TenantId? tenantId); 15 | 16 | String getName(); 17 | 18 | factory ExportableEntity.fromTypeAndJson( 19 | EntityType entityType, Map json) { 20 | switch (entityType) { 21 | case EntityType.CUSTOMER: 22 | return Customer.fromJson(json) as ExportableEntity; 23 | case EntityType.DASHBOARD: 24 | return Dashboard.fromJson(json) as ExportableEntity; 25 | case EntityType.ASSET: 26 | return Asset.fromJson(json) as ExportableEntity; 27 | case EntityType.ASSET_PROFILE: 28 | return AssetProfile.fromJson(json) as ExportableEntity; 29 | case EntityType.DEVICE: 30 | return Device.fromJson(json) as ExportableEntity; 31 | case EntityType.DEVICE_PROFILE: 32 | return DeviceProfile.fromJson(json) as ExportableEntity; 33 | case EntityType.RULE_CHAIN: 34 | return RuleChain.fromJson(json) as ExportableEntity; 35 | case EntityType.ENTITY_VIEW: 36 | return EntityView.fromJson(json) as ExportableEntity; 37 | case EntityType.WIDGETS_BUNDLE: 38 | return WidgetsBundle.fromJson(json) as ExportableEntity; 39 | default: 40 | throw FormatException('Not exportable entity type: $entityType!'); 41 | } 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /lib/src/model/has_additional_info.dart: -------------------------------------------------------------------------------- 1 | abstract mixin class HasAdditionalInfo { 2 | Map? getAdditionalInfo(); 3 | } 4 | -------------------------------------------------------------------------------- /lib/src/model/has_customer_id.dart: -------------------------------------------------------------------------------- 1 | import 'id/customer_id.dart'; 2 | 3 | abstract mixin class HasCustomerId { 4 | CustomerId? getCustomerId(); 5 | } 6 | -------------------------------------------------------------------------------- /lib/src/model/has_name.dart: -------------------------------------------------------------------------------- 1 | abstract mixin class HasName { 2 | String getName(); 3 | } 4 | -------------------------------------------------------------------------------- /lib/src/model/has_ota_package.dart: -------------------------------------------------------------------------------- 1 | import 'id/ota_package_id.dart'; 2 | 3 | abstract mixin class HasOtaPackage { 4 | OtaPackageId? getFirmwareId(); 5 | 6 | OtaPackageId? getSoftwareId(); 7 | } 8 | -------------------------------------------------------------------------------- /lib/src/model/has_rule_engine_profile.dart: -------------------------------------------------------------------------------- 1 | import 'id/rule_chain_id.dart'; 2 | 3 | abstract mixin class HasRuleEngineProfile { 4 | RuleChainId? getDefaultRuleChainId(); 5 | 6 | String? getDefaultQueueName(); 7 | } 8 | -------------------------------------------------------------------------------- /lib/src/model/has_tenant_id.dart: -------------------------------------------------------------------------------- 1 | import 'id/tenant_id.dart'; 2 | 3 | abstract mixin class HasTenantId { 4 | TenantId? getTenantId(); 5 | } 6 | -------------------------------------------------------------------------------- /lib/src/model/id/admin_settings_id.dart: -------------------------------------------------------------------------------- 1 | import 'has_uuid.dart'; 2 | 3 | class AdminSettingsId extends HasUuid { 4 | AdminSettingsId(String? id) : super(id); 5 | 6 | @override 7 | factory AdminSettingsId.fromJson(Map json) { 8 | return HasUuid.fromJson(json, (id) => AdminSettingsId(id)) 9 | as AdminSettingsId; 10 | } 11 | 12 | @override 13 | String toString() { 14 | return 'AdminSettingsId {id: $id}'; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /lib/src/model/id/alarm_comment_id.dart: -------------------------------------------------------------------------------- 1 | import 'has_uuid.dart'; 2 | 3 | class AlarmCommentId extends HasUuid { 4 | AlarmCommentId(String? id) : super(id); 5 | 6 | @override 7 | factory AlarmCommentId.fromJson(Map json) { 8 | return HasUuid.fromJson(json, (id) => AlarmCommentId(id)) as AlarmCommentId; 9 | } 10 | 11 | @override 12 | String toString() { 13 | return 'AlarmCommentId {id: $id}'; 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /lib/src/model/id/alarm_id.dart: -------------------------------------------------------------------------------- 1 | import '../entity_type_models.dart'; 2 | import 'entity_id.dart'; 3 | 4 | class AlarmId extends EntityId { 5 | AlarmId(String id) : super(EntityType.ALARM, id); 6 | 7 | @override 8 | factory AlarmId.fromJson(Map json) { 9 | return EntityId.fromJson(json) as AlarmId; 10 | } 11 | 12 | @override 13 | String toString() { 14 | return 'AlarmId {id: $id}'; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /lib/src/model/id/api_usage_state_id.dart: -------------------------------------------------------------------------------- 1 | import '../entity_type_models.dart'; 2 | import 'entity_id.dart'; 3 | 4 | class ApiUsageStateId extends EntityId { 5 | ApiUsageStateId(String id) : super(EntityType.API_USAGE_STATE, id); 6 | 7 | @override 8 | factory ApiUsageStateId.fromJson(Map json) { 9 | return EntityId.fromJson(json) as ApiUsageStateId; 10 | } 11 | 12 | @override 13 | String toString() { 14 | return 'ApiUsageStateId {id: $id}'; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /lib/src/model/id/asset_id.dart: -------------------------------------------------------------------------------- 1 | import '../entity_type_models.dart'; 2 | import 'entity_id.dart'; 3 | 4 | class AssetId extends EntityId { 5 | AssetId(String id) : super(EntityType.ASSET, id); 6 | 7 | @override 8 | factory AssetId.fromJson(Map json) { 9 | return EntityId.fromJson(json) as AssetId; 10 | } 11 | 12 | @override 13 | String toString() { 14 | return 'AssetId {id: $id}'; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /lib/src/model/id/asset_profile_id.dart: -------------------------------------------------------------------------------- 1 | import '../entity_type_models.dart'; 2 | import 'entity_id.dart'; 3 | 4 | class AssetProfileId extends EntityId { 5 | AssetProfileId(String id) : super(EntityType.ASSET_PROFILE, id); 6 | 7 | @override 8 | factory AssetProfileId.fromJson(Map json) { 9 | return EntityId.fromJson(json) as AssetProfileId; 10 | } 11 | 12 | @override 13 | String toString() { 14 | return 'AssetProfileId {id: $id}'; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /lib/src/model/id/audit_log_id.dart: -------------------------------------------------------------------------------- 1 | import 'has_uuid.dart'; 2 | 3 | class AuditLogId extends HasUuid { 4 | AuditLogId(String? id) : super(id); 5 | 6 | @override 7 | factory AuditLogId.fromJson(Map json) { 8 | return HasUuid.fromJson(json, (id) => AuditLogId(id)) as AuditLogId; 9 | } 10 | 11 | @override 12 | String toString() { 13 | return 'AuditLogId {id: $id}'; 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /lib/src/model/id/component_descriptor_id.dart: -------------------------------------------------------------------------------- 1 | import 'has_uuid.dart'; 2 | 3 | class ComponentDescriptorId extends HasUuid { 4 | ComponentDescriptorId(String? id) : super(id); 5 | 6 | @override 7 | factory ComponentDescriptorId.fromJson(Map json) { 8 | return HasUuid.fromJson(json, (id) => ComponentDescriptorId(id)) 9 | as ComponentDescriptorId; 10 | } 11 | 12 | @override 13 | String toString() { 14 | return 'ComponentDescriptorId {id: $id}'; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /lib/src/model/id/customer_id.dart: -------------------------------------------------------------------------------- 1 | import '../entity_type_models.dart'; 2 | import 'entity_id.dart'; 3 | 4 | class CustomerId extends EntityId { 5 | CustomerId(String id) : super(EntityType.CUSTOMER, id); 6 | 7 | @override 8 | factory CustomerId.fromJson(Map json) { 9 | return EntityId.fromJson(json) as CustomerId; 10 | } 11 | 12 | @override 13 | String toString() { 14 | return 'CustomerId {id: $id}'; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /lib/src/model/id/dashboard_id.dart: -------------------------------------------------------------------------------- 1 | import '../entity_type_models.dart'; 2 | import 'entity_id.dart'; 3 | 4 | class DashboardId extends EntityId { 5 | DashboardId(String id) : super(EntityType.DASHBOARD, id); 6 | 7 | @override 8 | factory DashboardId.fromJson(Map json) { 9 | return EntityId.fromJson(json) as DashboardId; 10 | } 11 | 12 | @override 13 | String toString() { 14 | return 'DashboardId {id: $id}'; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /lib/src/model/id/device_credentials_id.dart: -------------------------------------------------------------------------------- 1 | import 'has_uuid.dart'; 2 | 3 | class DeviceCredentialsId extends HasUuid { 4 | DeviceCredentialsId(String? id) : super(id); 5 | 6 | @override 7 | factory DeviceCredentialsId.fromJson(Map json) { 8 | return HasUuid.fromJson(json, (id) => DeviceCredentialsId(id)) 9 | as DeviceCredentialsId; 10 | } 11 | 12 | @override 13 | String toString() { 14 | return 'DeviceCredentialsId {id: $id}'; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /lib/src/model/id/device_id.dart: -------------------------------------------------------------------------------- 1 | import '../entity_type_models.dart'; 2 | import 'entity_id.dart'; 3 | 4 | class DeviceId extends EntityId { 5 | DeviceId(String id) : super(EntityType.DEVICE, id); 6 | 7 | @override 8 | factory DeviceId.fromJson(Map json) { 9 | return EntityId.fromJson(json) as DeviceId; 10 | } 11 | 12 | @override 13 | String toString() { 14 | return 'DeviceId {id: $id}'; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /lib/src/model/id/device_profile_id.dart: -------------------------------------------------------------------------------- 1 | import '../entity_type_models.dart'; 2 | import 'entity_id.dart'; 3 | 4 | class DeviceProfileId extends EntityId { 5 | DeviceProfileId(String id) : super(EntityType.DEVICE_PROFILE, id); 6 | 7 | @override 8 | factory DeviceProfileId.fromJson(Map json) { 9 | return EntityId.fromJson(json) as DeviceProfileId; 10 | } 11 | 12 | @override 13 | String toString() { 14 | return 'DeviceProfileId {id: $id}'; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /lib/src/model/id/edge_event_id.dart: -------------------------------------------------------------------------------- 1 | import 'has_uuid.dart'; 2 | 3 | class EdgeEventId extends HasUuid { 4 | EdgeEventId(String? id) : super(id); 5 | 6 | @override 7 | factory EdgeEventId.fromJson(Map json) { 8 | return HasUuid.fromJson(json, (id) => EdgeEventId(id)) as EdgeEventId; 9 | } 10 | 11 | @override 12 | String toString() { 13 | return 'EdgeEventId {id: $id}'; 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /lib/src/model/id/edge_id.dart: -------------------------------------------------------------------------------- 1 | import '../entity_type_models.dart'; 2 | import 'entity_id.dart'; 3 | 4 | class EdgeId extends EntityId { 5 | EdgeId(String id) : super(EntityType.EDGE, id); 6 | 7 | @override 8 | factory EdgeId.fromJson(Map json) { 9 | return EntityId.fromJson(json) as EdgeId; 10 | } 11 | 12 | @override 13 | String toString() { 14 | return 'EdgeId {id: $id}'; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /lib/src/model/id/entity_id.dart: -------------------------------------------------------------------------------- 1 | import 'ota_package_id.dart'; 2 | import 'alarm_id.dart'; 3 | import 'api_usage_state_id.dart'; 4 | import 'asset_id.dart'; 5 | import 'dashboard_id.dart'; 6 | import 'device_profile_id.dart'; 7 | import 'asset_profile_id.dart'; 8 | import 'edge_id.dart'; 9 | import 'entity_view_id.dart'; 10 | import 'rule_chain_id.dart'; 11 | import 'rule_node_id.dart'; 12 | import 'tb_resource_id.dart'; 13 | import 'tenant_profile_id.dart'; 14 | import 'user_id.dart'; 15 | import 'widget_type_id.dart'; 16 | import 'widgets_bundle_id.dart'; 17 | import 'customer_id.dart'; 18 | import 'device_id.dart'; 19 | import 'tenant_id.dart'; 20 | import 'rpc_id.dart'; 21 | import 'queue_id.dart'; 22 | import 'notification_id.dart'; 23 | import 'notification_request_id.dart'; 24 | import 'notification_rule_id.dart'; 25 | import 'notification_target_id.dart'; 26 | import 'notification_template_id.dart'; 27 | 28 | import '../entity_type_models.dart'; 29 | import './has_uuid.dart'; 30 | 31 | abstract class EntityId extends HasUuid { 32 | EntityType entityType; 33 | 34 | EntityId(this.entityType, String id) : super(id); 35 | 36 | factory EntityId.fromJson(Map json) { 37 | if (json.containsKey('entityType') && json.containsKey('id')) { 38 | var entityType = entityTypeFromString(json['entityType']); 39 | String uuid = json['id']; 40 | return EntityId.fromTypeAndUuid(entityType, uuid); 41 | } else { 42 | throw FormatException('Missing entityType or id!'); 43 | } 44 | } 45 | 46 | factory EntityId.fromTypeAndUuid(EntityType type, String uuid) { 47 | switch (type) { 48 | case EntityType.TENANT: 49 | return TenantId(uuid); 50 | case EntityType.TENANT_PROFILE: 51 | return TenantProfileId(uuid); 52 | case EntityType.CUSTOMER: 53 | return CustomerId(uuid); 54 | case EntityType.USER: 55 | return UserId(uuid); 56 | case EntityType.DASHBOARD: 57 | return DashboardId(uuid); 58 | case EntityType.ASSET: 59 | return AssetId(uuid); 60 | case EntityType.DEVICE: 61 | return DeviceId(uuid); 62 | case EntityType.DEVICE_PROFILE: 63 | return DeviceProfileId(uuid); 64 | case EntityType.ASSET_PROFILE: 65 | return AssetProfileId(uuid); 66 | case EntityType.ALARM: 67 | return AlarmId(uuid); 68 | case EntityType.RULE_CHAIN: 69 | return RuleChainId(uuid); 70 | case EntityType.RULE_NODE: 71 | return RuleNodeId(uuid); 72 | case EntityType.EDGE: 73 | return EdgeId(uuid); 74 | case EntityType.ENTITY_VIEW: 75 | return EntityViewId(uuid); 76 | case EntityType.WIDGETS_BUNDLE: 77 | return WidgetsBundleId(uuid); 78 | case EntityType.WIDGET_TYPE: 79 | return WidgetTypeId(uuid); 80 | case EntityType.API_USAGE_STATE: 81 | return ApiUsageStateId(uuid); 82 | case EntityType.TB_RESOURCE: 83 | return TbResourceId(uuid); 84 | case EntityType.OTA_PACKAGE: 85 | return OtaPackageId(uuid); 86 | case EntityType.RPC: 87 | return RpcId(uuid); 88 | case EntityType.QUEUE: 89 | return QueueId(uuid); 90 | case EntityType.NOTIFICATION_TARGET: 91 | return NotificationTargetId(uuid); 92 | case EntityType.NOTIFICATION_TEMPLATE: 93 | return NotificationTemplateId(uuid); 94 | case EntityType.NOTIFICATION_REQUEST: 95 | return NotificationRequestId(uuid); 96 | case EntityType.NOTIFICATION: 97 | return NotificationId(uuid); 98 | case EntityType.NOTIFICATION_RULE: 99 | return NotificationRuleId(uuid); 100 | } 101 | } 102 | 103 | @override 104 | Map toJson() { 105 | var json = super.toJson(); 106 | json['entityType'] = entityType.toShortString(); 107 | return json; 108 | } 109 | } 110 | -------------------------------------------------------------------------------- /lib/src/model/id/entity_view_id.dart: -------------------------------------------------------------------------------- 1 | import '../entity_type_models.dart'; 2 | import 'entity_id.dart'; 3 | 4 | class EntityViewId extends EntityId { 5 | EntityViewId(String id) : super(EntityType.ENTITY_VIEW, id); 6 | 7 | @override 8 | factory EntityViewId.fromJson(Map json) { 9 | return EntityId.fromJson(json) as EntityViewId; 10 | } 11 | 12 | @override 13 | String toString() { 14 | return 'EntityViewId {id: $id}'; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /lib/src/model/id/event_id.dart: -------------------------------------------------------------------------------- 1 | import 'has_uuid.dart'; 2 | 3 | class EventId extends HasUuid { 4 | EventId(String? id) : super(id); 5 | 6 | @override 7 | factory EventId.fromJson(Map json) { 8 | return HasUuid.fromJson(json, (id) => EventId(id)) as EventId; 9 | } 10 | 11 | @override 12 | String toString() { 13 | return 'EventId {id: $id}'; 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /lib/src/model/id/has_id.dart: -------------------------------------------------------------------------------- 1 | import 'has_uuid.dart'; 2 | 3 | abstract class HasId { 4 | I? getId(); 5 | } 6 | -------------------------------------------------------------------------------- /lib/src/model/id/has_uuid.dart: -------------------------------------------------------------------------------- 1 | import 'entity_id.dart'; 2 | 3 | const nullUuid = '13814000-1dd2-11b2-8080-808080808080'; 4 | 5 | abstract class HasUuid { 6 | String? id; 7 | 8 | HasUuid(this.id); 9 | 10 | factory HasUuid.fromJson(Map json, 11 | [FromIdFunction? fromId]) { 12 | if (json.containsKey('id')) { 13 | if (json.containsKey('entityType')) { 14 | return EntityId.fromJson(json); 15 | } else { 16 | String id = json['id']; 17 | return fromId!(id); 18 | } 19 | } else { 20 | throw FormatException('Missing id!'); 21 | } 22 | } 23 | 24 | Map toJson() { 25 | return {'id': id}; 26 | } 27 | } 28 | 29 | typedef FromIdFunction = T Function(String id); 30 | -------------------------------------------------------------------------------- /lib/src/model/id/id_based.dart: -------------------------------------------------------------------------------- 1 | import 'has_id.dart'; 2 | import 'has_uuid.dart'; 3 | 4 | abstract class IdBased extends HasId { 5 | I? id; 6 | 7 | IdBased(); 8 | 9 | IdBased.fromJson(Map json, [FromIdFunction? fromId]) 10 | : id = json['id'] != null 11 | ? HasUuid.fromJson(json['id'], fromId) as I 12 | : null; 13 | 14 | Map toJson() { 15 | var json = {}; 16 | if (id != null) { 17 | json['id'] = id!.toJson(); 18 | } 19 | return json; 20 | } 21 | 22 | @override 23 | I? getId() { 24 | return id; 25 | } 26 | 27 | setId(I? id) { 28 | this.id = id; 29 | } 30 | 31 | @override 32 | String toString() { 33 | return 'IdBased{${idBasedString()}}'; 34 | } 35 | 36 | String idBasedString() { 37 | return 'id: $id'; 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /lib/src/model/id/ids.dart: -------------------------------------------------------------------------------- 1 | export 'admin_settings_id.dart'; 2 | export 'alarm_comment_id.dart'; 3 | export 'alarm_id.dart'; 4 | export 'api_usage_state_id.dart'; 5 | export 'asset_id.dart'; 6 | export 'audit_log_id.dart'; 7 | export 'customer_id.dart'; 8 | export 'dashboard_id.dart'; 9 | export 'device_credentials_id.dart'; 10 | export 'device_id.dart'; 11 | export 'device_profile_id.dart'; 12 | export 'asset_profile_id.dart'; 13 | export 'edge_id.dart'; 14 | export 'entity_id.dart'; 15 | export 'entity_view_id.dart'; 16 | export 'event_id.dart'; 17 | export 'notification_id.dart'; 18 | export 'notification_request_id.dart'; 19 | export 'notification_rule_id.dart'; 20 | export 'notification_target_id.dart'; 21 | export 'notification_template_id.dart'; 22 | export 'ota_package_id.dart'; 23 | export 'has_uuid.dart'; 24 | export 'rule_chain_id.dart'; 25 | export 'rule_node_id.dart'; 26 | export 'tb_resource_id.dart'; 27 | export 'tenant_id.dart'; 28 | export 'tenant_profile_id.dart'; 29 | export 'user_id.dart'; 30 | export 'widget_type_id.dart'; 31 | export 'widgets_bundle_id.dart'; 32 | export 'component_descriptor_id.dart'; 33 | export 'oauth2_client_registration_template_id.dart'; 34 | export 'edge_event_id.dart'; 35 | export 'rpc_id.dart'; 36 | export 'queue_id.dart'; 37 | -------------------------------------------------------------------------------- /lib/src/model/id/notification_id.dart: -------------------------------------------------------------------------------- 1 | import '../entity_type_models.dart'; 2 | import 'entity_id.dart'; 3 | 4 | class NotificationId extends EntityId { 5 | NotificationId(String id) : super(EntityType.NOTIFICATION, id); 6 | 7 | @override 8 | factory NotificationId.fromJson(Map json) { 9 | return EntityId.fromJson(json) as NotificationId; 10 | } 11 | 12 | @override 13 | String toString() { 14 | return 'NotificationId {id: $id}'; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /lib/src/model/id/notification_request_id.dart: -------------------------------------------------------------------------------- 1 | import '../entity_type_models.dart'; 2 | import 'entity_id.dart'; 3 | 4 | class NotificationRequestId extends EntityId { 5 | NotificationRequestId(String id) : super(EntityType.NOTIFICATION_REQUEST, id); 6 | 7 | @override 8 | factory NotificationRequestId.fromJson(Map json) { 9 | return EntityId.fromJson(json) as NotificationRequestId; 10 | } 11 | 12 | @override 13 | String toString() { 14 | return 'NotificationRequestId {id: $id}'; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /lib/src/model/id/notification_rule_id.dart: -------------------------------------------------------------------------------- 1 | import '../entity_type_models.dart'; 2 | import 'entity_id.dart'; 3 | 4 | class NotificationRuleId extends EntityId { 5 | NotificationRuleId(String id) : super(EntityType.NOTIFICATION_RULE, id); 6 | 7 | @override 8 | factory NotificationRuleId.fromJson(Map json) { 9 | return EntityId.fromJson(json) as NotificationRuleId; 10 | } 11 | 12 | @override 13 | String toString() { 14 | return 'NotificationRuleId {id: $id}'; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /lib/src/model/id/notification_target_id.dart: -------------------------------------------------------------------------------- 1 | import '../entity_type_models.dart'; 2 | import 'entity_id.dart'; 3 | 4 | class NotificationTargetId extends EntityId { 5 | NotificationTargetId(String id) : super(EntityType.NOTIFICATION_TARGET, id); 6 | 7 | @override 8 | factory NotificationTargetId.fromJson(Map json) { 9 | return EntityId.fromJson(json) as NotificationTargetId; 10 | } 11 | 12 | @override 13 | String toString() { 14 | return 'NotificationTargetId {id: $id}'; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /lib/src/model/id/notification_template_id.dart: -------------------------------------------------------------------------------- 1 | import '../entity_type_models.dart'; 2 | import 'entity_id.dart'; 3 | 4 | class NotificationTemplateId extends EntityId { 5 | NotificationTemplateId(String id) 6 | : super(EntityType.NOTIFICATION_TEMPLATE, id); 7 | 8 | @override 9 | factory NotificationTemplateId.fromJson(Map json) { 10 | return EntityId.fromJson(json) as NotificationTemplateId; 11 | } 12 | 13 | @override 14 | String toString() { 15 | return 'NotificationTemplateId {id: $id}'; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /lib/src/model/id/oauth2_client_registration_template_id.dart: -------------------------------------------------------------------------------- 1 | import 'has_uuid.dart'; 2 | 3 | class OAuth2ClientRegistrationTemplateId extends HasUuid { 4 | OAuth2ClientRegistrationTemplateId(String? id) : super(id); 5 | 6 | @override 7 | factory OAuth2ClientRegistrationTemplateId.fromJson( 8 | Map json) { 9 | return HasUuid.fromJson( 10 | json, (id) => OAuth2ClientRegistrationTemplateId(id)) 11 | as OAuth2ClientRegistrationTemplateId; 12 | } 13 | 14 | @override 15 | String toString() { 16 | return 'OAuth2ClientRegistrationTemplateId {id: $id}'; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /lib/src/model/id/ota_package_id.dart: -------------------------------------------------------------------------------- 1 | import '../entity_type_models.dart'; 2 | import 'entity_id.dart'; 3 | 4 | class OtaPackageId extends EntityId { 5 | OtaPackageId(String id) : super(EntityType.OTA_PACKAGE, id); 6 | 7 | @override 8 | factory OtaPackageId.fromJson(Map json) { 9 | return EntityId.fromJson(json) as OtaPackageId; 10 | } 11 | 12 | @override 13 | String toString() { 14 | return 'OtaPackageId {id: $id}'; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /lib/src/model/id/queue_id.dart: -------------------------------------------------------------------------------- 1 | import '../entity_type_models.dart'; 2 | import 'entity_id.dart'; 3 | 4 | class QueueId extends EntityId { 5 | QueueId(String id) : super(EntityType.QUEUE, id); 6 | 7 | @override 8 | factory QueueId.fromJson(Map json) { 9 | return EntityId.fromJson(json) as QueueId; 10 | } 11 | 12 | @override 13 | String toString() { 14 | return 'QueueId {id: $id}'; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /lib/src/model/id/rpc_id.dart: -------------------------------------------------------------------------------- 1 | import '../entity_type_models.dart'; 2 | import 'entity_id.dart'; 3 | 4 | class RpcId extends EntityId { 5 | RpcId(String id) : super(EntityType.RPC, id); 6 | 7 | @override 8 | factory RpcId.fromJson(Map json) { 9 | return EntityId.fromJson(json) as RpcId; 10 | } 11 | 12 | @override 13 | String toString() { 14 | return 'RpcId {id: $id}'; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /lib/src/model/id/rule_chain_id.dart: -------------------------------------------------------------------------------- 1 | import '../entity_type_models.dart'; 2 | import 'entity_id.dart'; 3 | 4 | class RuleChainId extends EntityId { 5 | RuleChainId(String id) : super(EntityType.RULE_CHAIN, id); 6 | 7 | @override 8 | factory RuleChainId.fromJson(Map json) { 9 | return EntityId.fromJson(json) as RuleChainId; 10 | } 11 | 12 | @override 13 | String toString() { 14 | return 'RuleChainId {id: $id}'; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /lib/src/model/id/rule_node_id.dart: -------------------------------------------------------------------------------- 1 | import '../entity_type_models.dart'; 2 | import 'entity_id.dart'; 3 | 4 | class RuleNodeId extends EntityId { 5 | RuleNodeId(String id) : super(EntityType.RULE_NODE, id); 6 | 7 | @override 8 | factory RuleNodeId.fromJson(Map json) { 9 | return EntityId.fromJson(json) as RuleNodeId; 10 | } 11 | 12 | @override 13 | String toString() { 14 | return 'RuleNodeId {id: $id}'; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /lib/src/model/id/tb_resource_id.dart: -------------------------------------------------------------------------------- 1 | import '../entity_type_models.dart'; 2 | import 'entity_id.dart'; 3 | 4 | class TbResourceId extends EntityId { 5 | TbResourceId(String id) : super(EntityType.TB_RESOURCE, id); 6 | 7 | @override 8 | factory TbResourceId.fromJson(Map json) { 9 | return EntityId.fromJson(json) as TbResourceId; 10 | } 11 | 12 | @override 13 | String toString() { 14 | return 'TbResourceId {id: $id}'; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /lib/src/model/id/tenant_id.dart: -------------------------------------------------------------------------------- 1 | import '../entity_type_models.dart'; 2 | import 'entity_id.dart'; 3 | 4 | class TenantId extends EntityId { 5 | TenantId(String id) : super(EntityType.TENANT, id); 6 | 7 | @override 8 | factory TenantId.fromJson(Map json) { 9 | return EntityId.fromJson(json) as TenantId; 10 | } 11 | 12 | @override 13 | String toString() { 14 | return 'TenantId {id: $id}'; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /lib/src/model/id/tenant_profile_id.dart: -------------------------------------------------------------------------------- 1 | import '../entity_type_models.dart'; 2 | import 'entity_id.dart'; 3 | 4 | class TenantProfileId extends EntityId { 5 | TenantProfileId(String id) : super(EntityType.TENANT_PROFILE, id); 6 | 7 | @override 8 | factory TenantProfileId.fromJson(Map json) { 9 | return EntityId.fromJson(json) as TenantProfileId; 10 | } 11 | 12 | @override 13 | String toString() { 14 | return 'TenantProfileId {id: $id}'; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /lib/src/model/id/user_id.dart: -------------------------------------------------------------------------------- 1 | import '../entity_type_models.dart'; 2 | import 'entity_id.dart'; 3 | 4 | class UserId extends EntityId { 5 | UserId(String id) : super(EntityType.USER, id); 6 | 7 | @override 8 | factory UserId.fromJson(Map json) { 9 | return EntityId.fromJson(json) as UserId; 10 | } 11 | 12 | @override 13 | String toString() { 14 | return 'UserId {id: $id}'; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /lib/src/model/id/widget_type_id.dart: -------------------------------------------------------------------------------- 1 | import '../entity_type_models.dart'; 2 | import 'entity_id.dart'; 3 | 4 | class WidgetTypeId extends EntityId { 5 | WidgetTypeId(String id) : super(EntityType.WIDGET_TYPE, id); 6 | 7 | @override 8 | factory WidgetTypeId.fromJson(Map json) { 9 | return EntityId.fromJson(json) as WidgetTypeId; 10 | } 11 | 12 | @override 13 | String toString() { 14 | return 'WidgetTypeId {id: $id}'; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /lib/src/model/id/widgets_bundle_id.dart: -------------------------------------------------------------------------------- 1 | import '../entity_type_models.dart'; 2 | import 'entity_id.dart'; 3 | 4 | class WidgetsBundleId extends EntityId { 5 | WidgetsBundleId(String id) : super(EntityType.WIDGETS_BUNDLE, id); 6 | 7 | @override 8 | factory WidgetsBundleId.fromJson(Map json) { 9 | return EntityId.fromJson(json) as WidgetsBundleId; 10 | } 11 | 12 | @override 13 | String toString() { 14 | return 'WidgetsBundleId {id: $id}'; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /lib/src/model/login_models.dart: -------------------------------------------------------------------------------- 1 | import 'authority_enum.dart'; 2 | 3 | class LoginRequest { 4 | String username; 5 | String password; 6 | 7 | LoginRequest(this.username, this.password); 8 | 9 | Map toJson() { 10 | return { 11 | 'username': username, 12 | 'password': password, 13 | }; 14 | } 15 | } 16 | 17 | class LoginResponse { 18 | final String token; 19 | String? refreshToken; 20 | Authority? scope; 21 | 22 | LoginResponse(this.token, this.refreshToken); 23 | 24 | LoginResponse.fromJson(Map json) 25 | : token = json['token'], 26 | refreshToken = json['refreshToken'], 27 | scope = 28 | json['scope'] != null ? authorityFromString(json['scope']) : null; 29 | } 30 | 31 | class RefreshTokenRequest { 32 | final String refreshToken; 33 | 34 | RefreshTokenRequest(this.refreshToken); 35 | 36 | Map toJson() { 37 | return {'refreshToken': refreshToken}; 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /lib/src/model/mobile/basic_mobile_info.dart: -------------------------------------------------------------------------------- 1 | import 'package:thingsboard_client/thingsboard_client.dart'; 2 | 3 | class MobileBasicInfo { 4 | const MobileBasicInfo({ 5 | required this.user, 6 | required this.homeDashboardInfo, 7 | required this.pages, 8 | required this.versionInfo, 9 | required this.storeInfo, 10 | }); 11 | 12 | factory MobileBasicInfo.fromJson(Map json) { 13 | return MobileBasicInfo( 14 | user: json['user'] != null ? User.fromJson(json['user']) : null, 15 | homeDashboardInfo: json['homeDashboardInfo'] != null 16 | ? HomeDashboardInfo.fromJson(json['homeDashboardInfo']) 17 | : null, 18 | pages: json['pages'] != null 19 | ? json['pages'] 20 | .map((e) => PageLayout.fromJson(e)) 21 | .toList() 22 | : null, 23 | storeInfo: json['storeInfo'] != null 24 | ? StoreInfo.fromJson(json['storeInfo']) 25 | : null, 26 | versionInfo: json['versionInfo'] != null 27 | ? VersionInfo.fromJson(json['versionInfo']) 28 | : null, 29 | ); 30 | } 31 | 32 | final User? user; 33 | final HomeDashboardInfo? homeDashboardInfo; 34 | final List? pages; 35 | final StoreInfo? storeInfo; 36 | final VersionInfo? versionInfo; 37 | } 38 | -------------------------------------------------------------------------------- /lib/src/model/mobile/login_mobile_info.dart: -------------------------------------------------------------------------------- 1 | import 'package:thingsboard_client/thingsboard_client.dart' 2 | show OAuth2ClientInfo, VersionInfo, StoreInfo; 3 | 4 | class LoginMobileInfo { 5 | const LoginMobileInfo({ 6 | required this.oAuth2Clients, 7 | required this.storeInfo, 8 | required this.versionInfo, 9 | }); 10 | 11 | final List oAuth2Clients; 12 | final StoreInfo? storeInfo; 13 | final VersionInfo? versionInfo; 14 | 15 | factory LoginMobileInfo.fromJson(Map json) { 16 | return LoginMobileInfo( 17 | oAuth2Clients: json['oAuth2ClientLoginInfos'] 18 | .map((e) => OAuth2ClientInfo.fromJson(e)) 19 | .toList(), 20 | storeInfo: json['storeInfo'] != null 21 | ? StoreInfo.fromJson(json['storeInfo']) 22 | : null, 23 | versionInfo: json['versionInfo'] != null 24 | ? VersionInfo.fromJson(json['versionInfo']) 25 | : null, 26 | ); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /lib/src/model/mobile/mobile_info_query.dart: -------------------------------------------------------------------------------- 1 | import 'package:thingsboard_client/thingsboard_client.dart' 2 | show PlatformType, PlatformTypeToString; 3 | 4 | class MobileInfoQuery { 5 | const MobileInfoQuery({ 6 | required this.packageName, 7 | required this.platformType, 8 | }); 9 | 10 | final String packageName; 11 | final PlatformType platformType; 12 | 13 | Map toQueryParameters() { 14 | return { 15 | 'pkgName': packageName, 16 | 'platform': platformType.toShortString(), 17 | }; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /lib/src/model/mobile/mobile_models.dart: -------------------------------------------------------------------------------- 1 | export 'basic_mobile_info.dart'; 2 | export 'login_mobile_info.dart'; 3 | export 'mobile_info_query.dart'; 4 | export 'mobile_version_info.dart'; 5 | export 'pages_layout.dart'; 6 | export 'recaptcha_model.dart'; 7 | export 'store_info.dart'; 8 | export 'version_info.dart'; 9 | -------------------------------------------------------------------------------- /lib/src/model/mobile/mobile_version_info.dart: -------------------------------------------------------------------------------- 1 | import 'package:thingsboard_client/src/model/model.dart' show PlatformVersion; 2 | 3 | class MobileVersionInfo { 4 | const MobileVersionInfo({ 5 | required this.minVersion, 6 | required this.minVersionReleaseNotes, 7 | required this.latestVersion, 8 | required this.latestVersionReleaseNotes, 9 | }); 10 | 11 | factory MobileVersionInfo.fromJson(Map json) { 12 | return MobileVersionInfo( 13 | minVersion: PlatformVersion.fromString(json['minVersion']), 14 | minVersionReleaseNotes: json['minVersionReleaseNotes'], 15 | latestVersion: PlatformVersion.fromString(json['latestVersion']), 16 | latestVersionReleaseNotes: json['latestVersionReleaseNotes'], 17 | ); 18 | } 19 | 20 | final PlatformVersion minVersion; 21 | final String minVersionReleaseNotes; 22 | final PlatformVersion latestVersion; 23 | final String latestVersionReleaseNotes; 24 | } 25 | -------------------------------------------------------------------------------- /lib/src/model/mobile/pages_layout.dart: -------------------------------------------------------------------------------- 1 | enum Pages { 2 | home, 3 | alarms, 4 | devices, 5 | customers, 6 | assets, 7 | audit_logs, 8 | notifications, 9 | device_list, 10 | dashboards, 11 | undefined, 12 | } 13 | 14 | Pages pagesFromString(String? value) { 15 | return Pages.values.firstWhere( 16 | (e) => e.toString().split('.')[1].toUpperCase() == value?.toUpperCase(), 17 | orElse: () => Pages.undefined, 18 | ); 19 | } 20 | 21 | class PageLayout { 22 | const PageLayout({ 23 | this.id, 24 | this.label, 25 | this.icon, 26 | this.dashboardId, 27 | this.path, 28 | this.url, 29 | }); 30 | 31 | final Pages? id; 32 | final String? label; 33 | final String? icon; 34 | final String? dashboardId; 35 | final String? path; 36 | final String? url; 37 | 38 | factory PageLayout.fromJson(Map json) { 39 | return PageLayout( 40 | id: pagesFromString(json['id']), 41 | label: json['label'], 42 | icon: json['icon'], 43 | dashboardId: json['dashboardId'], 44 | path: json['path'], 45 | url: json['url'], 46 | ); 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /lib/src/model/mobile/recaptcha_model.dart: -------------------------------------------------------------------------------- 1 | class RecaptchaModel { 2 | const RecaptchaModel({ 3 | required this.siteKey, 4 | required this.androidSiteKey, 5 | required this.iosSiteKey, 6 | required this.version, 7 | required this.projectId, 8 | this.logActionName, 9 | }); 10 | 11 | final String version; 12 | final String? logActionName; 13 | final String? androidSiteKey; 14 | final String? iosSiteKey; 15 | final String? projectId; 16 | final String? siteKey; 17 | 18 | factory RecaptchaModel.fromJson(Map json) { 19 | return RecaptchaModel( 20 | siteKey: json['siteKey'], 21 | androidSiteKey: json['androidKey'], 22 | iosSiteKey: json['iosKey'], 23 | projectId: json['projectId'], 24 | version: json['version'], 25 | logActionName: json['logActionName'], 26 | ); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /lib/src/model/mobile/store_info.dart: -------------------------------------------------------------------------------- 1 | class StoreInfo { 2 | const StoreInfo({ 3 | required this.appId, 4 | required this.sha256CertFingerprints, 5 | required this.storeLink, 6 | }); 7 | 8 | factory StoreInfo.fromJson(Map json) { 9 | return StoreInfo( 10 | appId: json['appId'], 11 | sha256CertFingerprints: json['sha256CertFingerprints'], 12 | storeLink: json['storeLink'], 13 | ); 14 | } 15 | 16 | final String? appId; 17 | final String? sha256CertFingerprints; 18 | final String? storeLink; 19 | } 20 | -------------------------------------------------------------------------------- /lib/src/model/mobile/version_info.dart: -------------------------------------------------------------------------------- 1 | import 'package:thingsboard_client/src/model/model.dart' show PlatformVersion; 2 | 3 | class VersionInfo { 4 | const VersionInfo({ 5 | required this.minVersion, 6 | required this.minVersionReleaseNotes, 7 | required this.latestVersion, 8 | required this.latestVersionReleaseNotes, 9 | }); 10 | 11 | factory VersionInfo.fromJson(Map json) { 12 | return VersionInfo( 13 | minVersion: json['minVersion'] != null && json['minVersion'] != '' 14 | ? PlatformVersion.fromString(json['minVersion']) 15 | : null, 16 | minVersionReleaseNotes: json['minVersionReleaseNotes'], 17 | latestVersion: 18 | json['latestVersion'] != null && json['latestVersion'] != '' 19 | ? PlatformVersion.fromString(json['latestVersion']) 20 | : null, 21 | latestVersionReleaseNotes: json['latestVersionReleaseNotes'], 22 | ); 23 | } 24 | 25 | final PlatformVersion? minVersion; 26 | final String? minVersionReleaseNotes; 27 | final PlatformVersion? latestVersion; 28 | final String? latestVersionReleaseNotes; 29 | } 30 | -------------------------------------------------------------------------------- /lib/src/model/mobile_session_models.dart: -------------------------------------------------------------------------------- 1 | class MobileSessionInfo { 2 | int fcmTokenTimestamp; 3 | 4 | MobileSessionInfo(this.fcmTokenTimestamp); 5 | 6 | MobileSessionInfo.fromJson(Map json) 7 | : fcmTokenTimestamp = json['fcmTokenTimestamp']; 8 | 9 | Map toJson() { 10 | return { 11 | 'fcmTokenTimestamp': fcmTokenTimestamp, 12 | }; 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /lib/src/model/model.dart: -------------------------------------------------------------------------------- 1 | export 'additional_info_based.dart'; 2 | export 'alarm_models.dart'; 3 | export 'asset_models.dart'; 4 | export 'audit_log_models.dart'; 5 | export 'authority_enum.dart'; 6 | export 'base_data.dart'; 7 | export 'component_descriptor_models.dart'; 8 | export 'constants.dart'; 9 | export 'contact_based_model.dart'; 10 | export 'customer_models.dart'; 11 | export 'dashboard_models.dart'; 12 | export 'device_models.dart'; 13 | export 'edge_models.dart'; 14 | export 'entity_models.dart'; 15 | export 'entity_type_models.dart'; 16 | export 'entity_view_models.dart'; 17 | export 'event_models.dart'; 18 | export 'exportable_entity.dart'; 19 | export 'has_additional_info.dart'; 20 | export 'has_customer_id.dart'; 21 | export 'has_name.dart'; 22 | export 'has_ota_package.dart'; 23 | export 'has_rule_engine_profile.dart'; 24 | export 'has_tenant_id.dart'; 25 | export 'id/ids.dart'; 26 | export 'login_models.dart'; 27 | export 'mobile/mobile_models.dart'; 28 | export 'mobile_session_models.dart'; 29 | export 'oauth2_models.dart'; 30 | export 'ota_models.dart'; 31 | export 'page/page_data.dart'; 32 | export 'page/page_link.dart'; 33 | export 'page/sort_order.dart'; 34 | export 'push_notification_models.dart'; 35 | export 'query/query_models.dart'; 36 | export 'queue_models.dart'; 37 | export 'relation_models.dart'; 38 | export 'resource_models.dart'; 39 | export 'rpc_models.dart'; 40 | export 'rule_chain_models.dart'; 41 | export 'rule_node_models.dart'; 42 | export 'settings_models.dart'; 43 | export 'telemetry_models.dart'; 44 | export 'tenant_models.dart'; 45 | export 'two_factor_auth_models.dart'; 46 | export 'user_models.dart'; 47 | export 'vc_models.dart'; 48 | export 'version.dart'; 49 | export 'widget_models.dart'; 50 | export 'widgets_bundle_model.dart'; 51 | -------------------------------------------------------------------------------- /lib/src/model/ota_models.dart: -------------------------------------------------------------------------------- 1 | import 'dart:math'; 2 | 3 | import 'additional_info_based.dart'; 4 | import 'has_name.dart'; 5 | import 'has_tenant_id.dart'; 6 | import 'id/device_profile_id.dart'; 7 | import 'id/ota_package_id.dart'; 8 | import 'id/tenant_id.dart'; 9 | 10 | enum OtaPackageType { FIRMWARE, SOFTWARE } 11 | 12 | OtaPackageType otaPackageTypeFromString(String value) { 13 | return OtaPackageType.values.firstWhere( 14 | (e) => e.toString().split('.')[1].toUpperCase() == value.toUpperCase()); 15 | } 16 | 17 | extension OtaPackageTypeToString on OtaPackageType { 18 | String toShortString() { 19 | return toString().split('.').last; 20 | } 21 | } 22 | 23 | enum ChecksumAlgorithm { 24 | MD5, 25 | SHA256, 26 | SHA384, 27 | SHA512, 28 | CRC32, 29 | MURMUR3_32, 30 | MURMUR3_128 31 | } 32 | 33 | ChecksumAlgorithm checksumAlgorithmFromString(String value) { 34 | return ChecksumAlgorithm.values.firstWhere( 35 | (e) => e.toString().split('.')[1].toUpperCase() == value.toUpperCase()); 36 | } 37 | 38 | extension ChecksumAlgorithmToString on ChecksumAlgorithm { 39 | String toShortString() { 40 | return toString().split('.').last; 41 | } 42 | } 43 | 44 | class OtaPackageInfo extends AdditionalInfoBased 45 | with HasName, HasTenantId { 46 | TenantId? tenantId; 47 | DeviceProfileId deviceProfileId; 48 | OtaPackageType type; 49 | String title; 50 | String version; 51 | String? url; 52 | bool? hasData; 53 | String? fileName; 54 | String? contentType; 55 | ChecksumAlgorithm? checksumAlgorithm; 56 | String? checksum; 57 | int? dataSize; 58 | 59 | OtaPackageInfo(this.deviceProfileId, this.type, this.title, this.version); 60 | 61 | OtaPackageInfo.fromJson(Map json) 62 | : tenantId = json['tenantId'] != null 63 | ? TenantId.fromJson(json['tenantId']) 64 | : null, 65 | deviceProfileId = DeviceProfileId.fromJson(json['deviceProfileId']), 66 | type = otaPackageTypeFromString(json['type']), 67 | title = json['title'], 68 | version = json['version'], 69 | url = json['url'], 70 | hasData = json['hasData'], 71 | fileName = json['fileName'], 72 | contentType = json['contentType'], 73 | checksumAlgorithm = json['checksumAlgorithm'] != null 74 | ? checksumAlgorithmFromString(json['checksumAlgorithm']) 75 | : null, 76 | checksum = json['checksum'], 77 | dataSize = json['dataSize'], 78 | super.fromJson(json); 79 | 80 | @override 81 | Map toJson() { 82 | var json = super.toJson(); 83 | if (tenantId != null) { 84 | json['tenantId'] = tenantId!.toJson(); 85 | } 86 | json['deviceProfileId'] = deviceProfileId.toJson(); 87 | json['type'] = type.toShortString(); 88 | json['title'] = title; 89 | json['version'] = version; 90 | if (url != null) { 91 | json['url'] = url; 92 | } 93 | if (hasData != null) { 94 | json['hasData'] = hasData; 95 | } 96 | if (fileName != null) { 97 | json['fileName'] = fileName; 98 | } 99 | if (contentType != null) { 100 | json['contentType'] = contentType; 101 | } 102 | if (checksumAlgorithm != null) { 103 | json['checksumAlgorithm'] = checksumAlgorithm!.toShortString(); 104 | } 105 | if (checksum != null) { 106 | json['checksum'] = checksum; 107 | } 108 | if (dataSize != null) { 109 | json['dataSize'] = dataSize; 110 | } 111 | return json; 112 | } 113 | 114 | @override 115 | TenantId? getTenantId() { 116 | return tenantId; 117 | } 118 | 119 | @override 120 | String getName() { 121 | return title; 122 | } 123 | 124 | @override 125 | String toString() { 126 | return 'OtaPackageInfo{${otaPackageInfoString()}}'; 127 | } 128 | 129 | String otaPackageInfoString([String? toStringBody]) { 130 | return '${additionalInfoBasedString('tenantId: $tenantId, deviceProfileId: $deviceProfileId, type: ${type.toShortString()}, title: $title, version: $version, ' 131 | 'url: $url, hasData: $hasData, fileName: $fileName, contentType: $contentType, checksumAlgorithm: ${checksumAlgorithm?.toShortString()}, ' 132 | 'checksum: $checksum, dataSize: $dataSize${toStringBody != null ? ', ' + toStringBody : ''}')}'; 133 | } 134 | } 135 | 136 | class OtaPackage extends OtaPackageInfo { 137 | String data; 138 | 139 | OtaPackage(DeviceProfileId deviceProfileId, OtaPackageType type, String title, 140 | String version, this.data) 141 | : super(deviceProfileId, type, title, version); 142 | 143 | OtaPackage.fromJson(Map json) 144 | : data = json['data'], 145 | super.fromJson(json); 146 | 147 | @override 148 | Map toJson() { 149 | var json = super.toJson(); 150 | json['data'] = data; 151 | return json; 152 | } 153 | 154 | @override 155 | String toString() { 156 | return 'OtaPackage{${otaPackageInfoString('data: [${data.substring(0, min(30, data.length))}...]')}}'; 157 | } 158 | } 159 | -------------------------------------------------------------------------------- /lib/src/model/page/page_data.dart: -------------------------------------------------------------------------------- 1 | import '../base_data.dart'; 2 | 3 | class PageData { 4 | List data; 5 | int totalPages; 6 | int totalElements; 7 | bool hasNext; 8 | 9 | PageData(this.data, this.totalPages, this.totalElements, this.hasNext); 10 | 11 | PageData.fromJson(Map json, FromJsonFunction fromJson) 12 | : data = dataFromJson(json['data'], fromJson), 13 | totalPages = json['totalPages'], 14 | totalElements = json['totalElements'], 15 | hasNext = json['hasNext']; 16 | 17 | Map toJson() { 18 | return { 19 | 'data': data.map((dynamic e) => e.toJson()).toList(), 20 | 'totalPages': totalPages, 21 | 'totalElements': totalElements, 22 | 'hasNext': hasNext 23 | }; 24 | } 25 | 26 | @override 27 | String toString() { 28 | return 'PageData{data: ${dataToString(data)}, totalPages: $totalPages, totalElements: $totalElements, hasNext: $hasNext}'; 29 | } 30 | } 31 | 32 | PageData emptyPageData() => PageData([], 0, 0, false); 33 | 34 | List dataFromJson(List jsonData, FromJsonFunction fromJson) { 35 | return jsonData.map((e) => fromJson(e)).toList(); 36 | } 37 | 38 | String dataToString(List data) { 39 | var res = data.isNotEmpty ? '\n' : ''; 40 | res += data.map((e) => e.toString()).join('\n'); 41 | res += data.isNotEmpty ? '\n' : ''; 42 | return res; 43 | } 44 | -------------------------------------------------------------------------------- /lib/src/model/page/page_link.dart: -------------------------------------------------------------------------------- 1 | import 'sort_order.dart'; 2 | 3 | class PageLink { 4 | String? textSearch; 5 | int pageSize; 6 | int page; 7 | SortOrder? sortOrder; 8 | 9 | PageLink(this.pageSize, [this.page = 0, this.textSearch, this.sortOrder]); 10 | 11 | PageLink nextPageLink() { 12 | return PageLink(pageSize, page + 1, textSearch, sortOrder); 13 | } 14 | 15 | Map toQueryParameters() { 16 | var queryParameters = {'pageSize': pageSize, 'page': page}; 17 | if (textSearch != null && textSearch!.isNotEmpty) { 18 | queryParameters['textSearch'] = textSearch!; 19 | } 20 | if (sortOrder != null) { 21 | queryParameters['sortProperty'] = sortOrder!.property; 22 | queryParameters['sortOrder'] = sortOrder!.direction.toShortString(); 23 | } 24 | return queryParameters; 25 | } 26 | } 27 | 28 | class TimePageLink extends PageLink { 29 | int? startTime; 30 | int? endTime; 31 | 32 | TimePageLink(int pageSize, 33 | [int page = 0, 34 | String? textSearch, 35 | SortOrder? sortOrder, 36 | this.startTime, 37 | this.endTime]) 38 | : super(pageSize, page, textSearch, sortOrder); 39 | 40 | @override 41 | TimePageLink nextPageLink() { 42 | return TimePageLink( 43 | pageSize, page + 1, textSearch, sortOrder, startTime, endTime); 44 | } 45 | 46 | @override 47 | Map toQueryParameters() { 48 | final queryParameters = super.toQueryParameters(); 49 | if (startTime != null) { 50 | queryParameters['startTime'] = startTime; 51 | } 52 | if (endTime != null) { 53 | queryParameters['endTime'] = endTime; 54 | } 55 | 56 | return queryParameters; 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /lib/src/model/page/sort_order.dart: -------------------------------------------------------------------------------- 1 | enum Direction { ASC, DESC } 2 | 3 | extension DirectionToString on Direction { 4 | String toShortString() { 5 | return toString().split('.').last; 6 | } 7 | } 8 | 9 | class SortOrder { 10 | String property; 11 | Direction direction; 12 | SortOrder(this.property, this.direction); 13 | } 14 | 15 | SortOrder sortOrderFromString(String strSortOrder) { 16 | String property; 17 | var direction = Direction.ASC; 18 | if (strSortOrder.startsWith('-')) { 19 | direction = Direction.DESC; 20 | property = strSortOrder.substring(1); 21 | } else { 22 | if (strSortOrder.startsWith('+')) { 23 | property = strSortOrder.substring(1); 24 | } else { 25 | property = strSortOrder; 26 | } 27 | } 28 | return SortOrder(property, direction); 29 | } 30 | -------------------------------------------------------------------------------- /lib/src/model/push_notification_models.dart: -------------------------------------------------------------------------------- 1 | import 'package:thingsboard_client/thingsboard_client.dart'; 2 | 3 | enum PushNotificationType { 4 | GENERAL, 5 | ALARM, 6 | DEVICE_ACTIVITY, 7 | ENTITY_ACTION, 8 | ALARM_COMMENT, 9 | RULE_ENGINE_COMPONENT_LIFECYCLE_EVENT, 10 | ALARM_ASSIGNMENT, 11 | NEW_PLATFORM_VERSION, 12 | ENTITIES_LIMIT, 13 | API_USAGE_LIMIT, 14 | RULE_NODE, 15 | RATE_LIMITS, 16 | INTEGRATION_LIFECYCLE_EVENT, 17 | EDGE_CONNECTION, 18 | EDGE_COMMUNICATION_FAILURE, 19 | EXCEEDED_RATE_LIMITS, 20 | USER_ACTIVATED, 21 | USER_REGISTERED, 22 | UNKNOWN, 23 | } 24 | 25 | PushNotificationType notificationTypeFromString(String value) { 26 | return PushNotificationType.values.firstWhere( 27 | (e) => e.toString().split('.')[1].toUpperCase() == value.toUpperCase(), 28 | orElse: () => PushNotificationType.UNKNOWN, 29 | ); 30 | } 31 | 32 | extension NotificationTypeToString on PushNotificationType { 33 | String toShortString() { 34 | return toString().split('.').last; 35 | } 36 | } 37 | 38 | enum PushNotificationStatus { SENT, READ } 39 | 40 | PushNotificationStatus notificationStatusFromString(String value) { 41 | return PushNotificationStatus.values.firstWhere( 42 | (e) => e.toString().split('.')[1].toUpperCase() == value.toUpperCase()); 43 | } 44 | 45 | extension NotificationStatusToString on PushNotificationStatus { 46 | String toShortString() { 47 | return toString().split('.').last; 48 | } 49 | } 50 | 51 | class PushNotification extends BaseData { 52 | final NotificationRequestId requestId; 53 | final UserId recipientId; 54 | final String subject; 55 | final String text; 56 | final PushNotificationType type; 57 | final PushNotificationStatus status; 58 | final PushNotificationInfo? info; 59 | Map? additionalConfig; 60 | 61 | PushNotification(this.requestId, this.recipientId, this.subject, this.text, 62 | this.type, this.status, this.info); 63 | 64 | PushNotification.fromJson(Map json) 65 | : requestId = NotificationRequestId.fromJson(json['requestId']), 66 | recipientId = UserId.fromJson(json['recipientId']), 67 | subject = json['subject'], 68 | text = json['text'], 69 | type = notificationTypeFromString(json['type']), 70 | status = notificationStatusFromString(json['status']), 71 | info = json['info'] != null 72 | ? PushNotificationInfo.fromJson(json['info']) 73 | : null, 74 | additionalConfig = json['additionalConfig'], 75 | super.fromJson(json); 76 | 77 | Map toJson() { 78 | var json = super.toJson(); 79 | json['requestId'] = requestId.toString(); 80 | json['recipientId'] = recipientId.toString(); 81 | json['subject'] = subject; 82 | json['text'] = text; 83 | json['type'] = type.toString(); 84 | json['status'] = status.toString(); 85 | json['info'] = info?.toString(); 86 | if (additionalConfig != null) { 87 | json['additionalConfig'] = additionalConfig; 88 | } 89 | return json; 90 | } 91 | 92 | @override 93 | String toString() { 94 | return 'Notification{${notificationString()}}'; 95 | } 96 | 97 | String notificationString([String? toStringBody]) { 98 | return '${baseDataString('requestId: $recipientId, recipientId: $recipientId,' 99 | 'subject: $subject, text: $text, type: $type, status: $status, info: $info, ' 100 | 'additionalConfig: $additionalConfig')}'; 101 | } 102 | } 103 | 104 | class PushNotificationInfo { 105 | final String? description; 106 | final String? type; 107 | final AlarmSeverity? alarmSeverity; 108 | final AlarmStatus? alarmStatus; 109 | final String? alarmId; 110 | final String? alarmType; 111 | final EntityId? stateEntityId; 112 | final bool? acknowledged; 113 | final bool? cleared; 114 | 115 | PushNotificationInfo.fromJson(Map json) 116 | : description = json['description'], 117 | type = json['type'], 118 | alarmSeverity = json['alarmSeverity'] != null 119 | ? alarmSeverityFromString(json['alarmSeverity']) 120 | : null, 121 | alarmStatus = json['alarmStatus'] != null 122 | ? alarmStatusFromString(json['alarmStatus']) 123 | : null, 124 | alarmId = json['alarmId'], 125 | alarmType = json['alarmType'], 126 | stateEntityId = json['stateEntityId'] != null 127 | ? EntityId.fromJson(json['stateEntityId']) 128 | : null, 129 | acknowledged = json['acknowledged'], 130 | cleared = json['cleared']; 131 | 132 | String toString() { 133 | return 'NotificationInfo{description: $description, type: $type, alarmSeverity: $alarmSeverity,' 134 | 'alarmStatus: $alarmStatus, alarmType: $alarmType, stateEntityId: $stateEntityId,' 135 | 'acknowledged: $acknowledged, cleared: $cleared}'; 136 | } 137 | } 138 | 139 | class PushNotificationQuery { 140 | PushNotificationQuery( 141 | this.pageLink, { 142 | this.unreadOnly = false, 143 | this.deliveryMethod = 'MOBILE_APP', 144 | }); 145 | 146 | final TimePageLink pageLink; 147 | bool unreadOnly; 148 | final String deliveryMethod; 149 | 150 | Map toQueryParameters() { 151 | final queryParameters = pageLink.toQueryParameters(); 152 | queryParameters['unreadOnly'] = unreadOnly; 153 | queryParameters['deliveryMethod'] = deliveryMethod; 154 | 155 | return queryParameters; 156 | } 157 | } 158 | -------------------------------------------------------------------------------- /lib/src/model/queue_models.dart: -------------------------------------------------------------------------------- 1 | import 'has_name.dart'; 2 | import 'has_tenant_id.dart'; 3 | import 'id/queue_id.dart'; 4 | import 'additional_info_based.dart'; 5 | import 'id/tenant_id.dart'; 6 | 7 | enum SubmitStrategyType { 8 | BURST, 9 | BATCH, 10 | SEQUENTIAL_BY_ORIGINATOR, 11 | SEQUENTIAL_BY_TENANT, 12 | SEQUENTIAL 13 | } 14 | 15 | SubmitStrategyType submitStrategyTypeFromString(String value) { 16 | return SubmitStrategyType.values.firstWhere( 17 | (e) => e.toString().split('.')[1].toUpperCase() == value.toUpperCase()); 18 | } 19 | 20 | extension SubmitStrategyTypeToString on SubmitStrategyType { 21 | String toShortString() { 22 | return toString().split('.').last; 23 | } 24 | } 25 | 26 | enum ProcessingStrategyType { 27 | SKIP_ALL_FAILURES, 28 | SKIP_ALL_FAILURES_AND_TIMED_OUT, 29 | RETRY_ALL, 30 | RETRY_FAILED, 31 | RETRY_TIMED_OUT, 32 | RETRY_FAILED_AND_TIMED_OUT 33 | } 34 | 35 | ProcessingStrategyType processingStrategyTypeFromString(String value) { 36 | return ProcessingStrategyType.values.firstWhere( 37 | (e) => e.toString().split('.')[1].toUpperCase() == value.toUpperCase()); 38 | } 39 | 40 | extension ProcessingStrategyTypeToString on ProcessingStrategyType { 41 | String toShortString() { 42 | return toString().split('.').last; 43 | } 44 | } 45 | 46 | enum ServiceType { TB_CORE, TB_RULE_ENGINE, TB_TRANSPORT, JS_EXECUTOR } 47 | 48 | extension ServiceTypeToString on ServiceType { 49 | String toShortString() { 50 | return toString().split('.').last; 51 | } 52 | } 53 | 54 | class SubmitStrategy { 55 | SubmitStrategyType type; 56 | int? batchSize; 57 | 58 | SubmitStrategy(this.type); 59 | 60 | SubmitStrategy.fromJson(Map json) 61 | : type = submitStrategyTypeFromString(json['type']), 62 | batchSize = json['batchSize']; 63 | 64 | Map toJson() { 65 | var json = {}; 66 | json['type'] = type.toShortString(); 67 | if (batchSize != null) { 68 | json['batchSize'] = batchSize; 69 | } 70 | return json; 71 | } 72 | 73 | @override 74 | String toString() { 75 | return 'SubmitStrategy{type: $type, batchSize: $batchSize}'; 76 | } 77 | } 78 | 79 | class ProcessingStrategy { 80 | ProcessingStrategyType type; 81 | int? retries; 82 | double? failurePercentage; 83 | int? pauseBetweenRetries; 84 | int? maxPauseBetweenRetries; 85 | 86 | ProcessingStrategy(this.type); 87 | 88 | ProcessingStrategy.fromJson(Map json) 89 | : type = processingStrategyTypeFromString(json['type']), 90 | retries = json['retries'], 91 | failurePercentage = json['failurePercentage'], 92 | pauseBetweenRetries = json['pauseBetweenRetries'], 93 | maxPauseBetweenRetries = json['maxPauseBetweenRetries']; 94 | 95 | Map toJson() { 96 | var json = {}; 97 | json['type'] = type.toShortString(); 98 | if (retries != null) { 99 | json['retries'] = retries; 100 | } 101 | if (failurePercentage != null) { 102 | json['failurePercentage'] = failurePercentage; 103 | } 104 | if (pauseBetweenRetries != null) { 105 | json['pauseBetweenRetries'] = pauseBetweenRetries; 106 | } 107 | if (maxPauseBetweenRetries != null) { 108 | json['maxPauseBetweenRetries'] = maxPauseBetweenRetries; 109 | } 110 | return json; 111 | } 112 | 113 | @override 114 | String toString() { 115 | return 'ProcessingStrategy{type: $type, retries: $retries, failurePercentage: $failurePercentage, pauseBetweenRetries: $pauseBetweenRetries, maxPauseBetweenRetries: $maxPauseBetweenRetries}'; 116 | } 117 | } 118 | 119 | class Queue extends AdditionalInfoBased with HasName, HasTenantId { 120 | TenantId? tenantId; 121 | String name; 122 | String topic; 123 | int? pollInterval; 124 | int? partitions; 125 | bool? consumerPerPartition; 126 | int? packProcessingTimeout; 127 | SubmitStrategy submitStrategy; 128 | ProcessingStrategy processingStrategy; 129 | 130 | Queue(this.name, this.topic, this.submitStrategy, this.processingStrategy); 131 | 132 | Queue.fromJson(Map json) 133 | : tenantId = TenantId.fromJson(json['tenantId']), 134 | name = json['name'], 135 | topic = json['topic'], 136 | pollInterval = json['pollInterval'], 137 | partitions = json['partitions'], 138 | consumerPerPartition = json['consumerPerPartition'], 139 | packProcessingTimeout = json['packProcessingTimeout'], 140 | submitStrategy = SubmitStrategy.fromJson(json['submitStrategy']), 141 | processingStrategy = 142 | ProcessingStrategy.fromJson(json['processingStrategy']), 143 | super.fromJson(json); 144 | 145 | @override 146 | Map toJson() { 147 | var json = super.toJson(); 148 | if (tenantId != null) { 149 | json['tenantId'] = tenantId!.toJson(); 150 | } 151 | json['name'] = name; 152 | json['topic'] = topic; 153 | if (pollInterval != null) { 154 | json['pollInterval'] = pollInterval; 155 | } 156 | if (partitions != null) { 157 | json['partitions'] = partitions; 158 | } 159 | if (consumerPerPartition != null) { 160 | json['consumerPerPartition'] = consumerPerPartition; 161 | } 162 | if (packProcessingTimeout != null) { 163 | json['packProcessingTimeout'] = packProcessingTimeout; 164 | } 165 | json['submitStrategy'] = submitStrategy.toJson(); 166 | json['processingStrategy'] = processingStrategy.toJson(); 167 | return json; 168 | } 169 | 170 | @override 171 | String getName() { 172 | return name; 173 | } 174 | 175 | @override 176 | TenantId? getTenantId() { 177 | return tenantId; 178 | } 179 | 180 | @override 181 | String toString() { 182 | return 'Queue{${additionalInfoBasedString('tenantId: $tenantId, name: $name, topic: $topic, pollInterval: $pollInterval, partitions: $partitions, ' 183 | 'consumerPerPartition: $consumerPerPartition, packProcessingTimeout: $packProcessingTimeout, submitStrategy: $submitStrategy, processingStrategy: $processingStrategy')}}'; 184 | } 185 | } 186 | -------------------------------------------------------------------------------- /lib/src/model/relation_models.dart: -------------------------------------------------------------------------------- 1 | import 'entity_type_models.dart'; 2 | import 'id/entity_id.dart'; 3 | 4 | const CONTAINS_TYPE = 'Contains'; 5 | const MANAGES_TYPE = 'Manages'; 6 | 7 | enum RelationTypeGroup { COMMON, ALARM, DASHBOARD, RULE_CHAIN, RULE_NODE } 8 | 9 | RelationTypeGroup relationTypeGroupFromString(String value) { 10 | return RelationTypeGroup.values.firstWhere( 11 | (e) => e.toString().split('.')[1].toUpperCase() == value.toUpperCase()); 12 | } 13 | 14 | extension RelationTypeGroupToString on RelationTypeGroup { 15 | String toShortString() { 16 | return toString().split('.').last; 17 | } 18 | } 19 | 20 | enum EntitySearchDirection { FROM, TO } 21 | 22 | EntitySearchDirection entitySearchDirectionFromString(String value) { 23 | return EntitySearchDirection.values.firstWhere( 24 | (e) => e.toString().split('.')[1].toUpperCase() == value.toUpperCase()); 25 | } 26 | 27 | extension EntitySearchDirectionToString on EntitySearchDirection { 28 | String toShortString() { 29 | return toString().split('.').last; 30 | } 31 | } 32 | 33 | class RelationEntityTypeFilter { 34 | String relationType; 35 | List entityTypes; 36 | 37 | RelationEntityTypeFilter(this.relationType, this.entityTypes); 38 | 39 | Map toJson() { 40 | var json = {}; 41 | json['relationType'] = relationType; 42 | json['entityTypes'] = entityTypes.map((e) => e.toShortString()).toList(); 43 | return json; 44 | } 45 | 46 | @override 47 | String toString() { 48 | return 'RelationEntityTypeFilter{relationType: $relationType, entityTypes: $entityTypes}'; 49 | } 50 | } 51 | 52 | class RelationsSearchParameters { 53 | String rootId; 54 | EntityType rootType; 55 | EntitySearchDirection direction; 56 | RelationTypeGroup? relationTypeGroup; 57 | int maxLevel; 58 | bool fetchLastLevelOnly; 59 | 60 | RelationsSearchParameters( 61 | {required this.rootId, 62 | required this.rootType, 63 | this.direction = EntitySearchDirection.FROM, 64 | this.relationTypeGroup, 65 | this.maxLevel = 1, 66 | this.fetchLastLevelOnly = false}); 67 | 68 | Map toJson() { 69 | var json = {}; 70 | json['rootId'] = rootId; 71 | json['rootType'] = rootType.toShortString(); 72 | json['direction'] = direction.toShortString(); 73 | if (relationTypeGroup != null) { 74 | json['relationTypeGroup'] = relationTypeGroup!.toShortString(); 75 | } 76 | json['maxLevel'] = maxLevel; 77 | json['fetchLastLevelOnly'] = fetchLastLevelOnly; 78 | return json; 79 | } 80 | 81 | @override 82 | String toString() { 83 | return 'RelationsSearchParameters{rootId: $rootId, rootType: $rootType, direction: $direction, relationTypeGroup: $relationTypeGroup, maxLevel: $maxLevel, fetchLastLevelOnly: $fetchLastLevelOnly}'; 84 | } 85 | } 86 | 87 | class EntityRelationsQuery { 88 | RelationsSearchParameters parameters; 89 | List? filters; 90 | 91 | EntityRelationsQuery({required this.parameters, this.filters}); 92 | 93 | Map toJson() { 94 | var json = {}; 95 | json['parameters'] = parameters.toJson(); 96 | if (filters != null) { 97 | json['filters'] = filters!.map((e) => e.toJson()).toList(); 98 | } 99 | return json; 100 | } 101 | 102 | @override 103 | String toString() { 104 | return 'EntityRelationsQuery{parameters: $parameters, filters: $filters}'; 105 | } 106 | } 107 | 108 | class EntitySearchQuery { 109 | RelationsSearchParameters parameters; 110 | String? relationType; 111 | 112 | EntitySearchQuery({required this.parameters, this.relationType}); 113 | 114 | Map toJson() { 115 | var json = {}; 116 | json['parameters'] = parameters.toJson(); 117 | if (relationType != null) { 118 | json['relationType'] = relationType; 119 | } 120 | return json; 121 | } 122 | 123 | @override 124 | String toString() { 125 | return 'EntitySearchQuery{${entitySearchQueryString()}}'; 126 | } 127 | 128 | String entitySearchQueryString([String? toStringBody]) { 129 | return 'parameters: $parameters, relationType: $relationType${toStringBody != null ? ', ' + toStringBody : ''}'; 130 | } 131 | } 132 | 133 | class EntityRelation { 134 | EntityId from; 135 | EntityId to; 136 | String type; 137 | RelationTypeGroup typeGroup; 138 | Map? additionalInfo; 139 | 140 | EntityRelation( 141 | {required this.from, 142 | required this.to, 143 | this.type = CONTAINS_TYPE, 144 | this.typeGroup = RelationTypeGroup.COMMON, 145 | this.additionalInfo}); 146 | 147 | EntityRelation.fromJson(Map json) 148 | : from = EntityId.fromJson(json['from']), 149 | to = EntityId.fromJson(json['to']), 150 | type = json['type'], 151 | typeGroup = relationTypeGroupFromString(json['typeGroup']), 152 | additionalInfo = json['additionalInfo']; 153 | 154 | Map toJson() { 155 | var json = {}; 156 | json['from'] = from.toJson(); 157 | json['to'] = to.toJson(); 158 | json['type'] = type; 159 | json['typeGroup'] = typeGroup.toShortString(); 160 | if (additionalInfo != null) { 161 | json['additionalInfo'] = additionalInfo; 162 | } 163 | return json; 164 | } 165 | 166 | @override 167 | String toString() { 168 | return 'EntityRelation{${entityRelationString()}}'; 169 | } 170 | 171 | String entityRelationString([String? toStringBody]) { 172 | return 'from: $from, to: $to, type: $type, typeGroup: $typeGroup, additionalInfo: $additionalInfo${toStringBody != null ? ', ' + toStringBody : ''}'; 173 | } 174 | } 175 | 176 | class EntityRelationInfo extends EntityRelation { 177 | String fromName; 178 | String? fromEntityTypeName; 179 | String toName; 180 | String? toEntityTypeName; 181 | 182 | EntityRelationInfo.fromJson(Map json) 183 | : fromName = json['fromName'], 184 | fromEntityTypeName = json['fromEntityTypeName'], 185 | toName = json['toName'], 186 | toEntityTypeName = json['toEntityTypeName'], 187 | super.fromJson(json); 188 | 189 | @override 190 | String toString() { 191 | return 'EntityRelationInfo{${entityRelationString('fromName: $fromName, fromEntityTypeName: $fromEntityTypeName, toName: $toName, toEntityTypeName: $toEntityTypeName')}}'; 192 | } 193 | } 194 | -------------------------------------------------------------------------------- /lib/src/model/resource_models.dart: -------------------------------------------------------------------------------- 1 | import 'dart:math'; 2 | 3 | import 'has_name.dart'; 4 | import 'has_tenant_id.dart'; 5 | import 'id/tb_resource_id.dart'; 6 | import 'base_data.dart'; 7 | import 'id/tenant_id.dart'; 8 | 9 | enum ResourceType { LWM2M_MODEL, JKS, PKCS_12, JS_MODULE } 10 | 11 | ResourceType resourceTypeFromString(String value) { 12 | return ResourceType.values.firstWhere( 13 | (e) => e.toString().split('.')[1].toUpperCase() == value.toUpperCase()); 14 | } 15 | 16 | extension ResourceTypeToString on ResourceType { 17 | String toShortString() { 18 | return toString().split('.').last; 19 | } 20 | } 21 | 22 | class TbResourceInfo extends BaseData with HasName, HasTenantId { 23 | TenantId? tenantId; 24 | String title; 25 | ResourceType resourceType; 26 | String resourceKey; 27 | 28 | TbResourceInfo(this.title, this.resourceType, this.resourceKey); 29 | 30 | TbResourceInfo.fromJson(Map json) 31 | : tenantId = json['tenantId'] != null 32 | ? TenantId.fromJson(json['tenantId']) 33 | : null, 34 | title = json['title'], 35 | resourceType = resourceTypeFromString(json['resourceType']), 36 | resourceKey = json['resourceKey'], 37 | super.fromJson(json); 38 | 39 | @override 40 | Map toJson() { 41 | var json = super.toJson(); 42 | if (tenantId != null) { 43 | json['tenantId'] = tenantId!.toJson(); 44 | } 45 | json['title'] = title; 46 | json['resourceType'] = resourceType.toShortString(); 47 | json['resourceKey'] = resourceKey; 48 | return json; 49 | } 50 | 51 | @override 52 | TenantId? getTenantId() { 53 | return tenantId; 54 | } 55 | 56 | @override 57 | String getName() { 58 | return title; 59 | } 60 | 61 | @override 62 | String toString() { 63 | return 'TbResourceInfo{${resourceInfoString()}}'; 64 | } 65 | 66 | String resourceInfoString([String? toStringBody]) { 67 | return '${baseDataString('tenantId: $tenantId, title: $title, resourceType: ${resourceType.toShortString()}, resourceKey: $resourceKey${toStringBody != null ? ', ' + toStringBody : ''}')}'; 68 | } 69 | } 70 | 71 | class TbResource extends TbResourceInfo { 72 | String fileName; 73 | String data; 74 | 75 | TbResource(String title, ResourceType resourceType, String resourceKey, 76 | this.fileName, this.data) 77 | : super(title, resourceType, resourceKey); 78 | 79 | TbResource.fromJson(Map json) 80 | : fileName = json['fileName'], 81 | data = json['data'], 82 | super.fromJson(json); 83 | 84 | @override 85 | Map toJson() { 86 | var json = super.toJson(); 87 | json['fileName'] = fileName; 88 | json['data'] = data; 89 | return json; 90 | } 91 | 92 | @override 93 | String toString() { 94 | return 'TbResource{${resourceInfoString('fileName: $fileName, data: [${data.substring(0, min(30, data.length))}...]')}}'; 95 | } 96 | } 97 | -------------------------------------------------------------------------------- /lib/src/model/rpc_models.dart: -------------------------------------------------------------------------------- 1 | import 'base_data.dart'; 2 | import 'has_tenant_id.dart'; 3 | import 'id/device_id.dart'; 4 | import 'id/rpc_id.dart'; 5 | import 'id/tenant_id.dart'; 6 | 7 | enum RpcStatus { QUEUED, DELIVERED, SUCCESSFUL, TIMEOUT, FAILED } 8 | 9 | RpcStatus rpcStatusFromString(String value) { 10 | return RpcStatus.values.firstWhere( 11 | (e) => e.toString().split('.')[1].toUpperCase() == value.toUpperCase()); 12 | } 13 | 14 | extension RpcStatusToString on RpcStatus { 15 | String toShortString() { 16 | return toString().split('.').last; 17 | } 18 | } 19 | 20 | class Rpc extends BaseData with HasTenantId { 21 | TenantId tenantId; 22 | DeviceId deviceId; 23 | int expirationTime; 24 | dynamic request; 25 | dynamic response; 26 | RpcStatus status; 27 | 28 | Rpc.fromJson(Map json) 29 | : tenantId = TenantId.fromJson(json['tenantId']), 30 | deviceId = DeviceId.fromJson(json['deviceId']), 31 | expirationTime = json['expirationTime'], 32 | request = json['request'], 33 | response = json['response'], 34 | status = rpcStatusFromString(json['status']), 35 | super.fromJson(json); 36 | 37 | @override 38 | TenantId? getTenantId() { 39 | return tenantId; 40 | } 41 | 42 | @override 43 | String toString() { 44 | return 'Rpc{tenantId: $tenantId, deviceId: $deviceId, expirationTime: $expirationTime, request: $request, response: $response, status: $status}'; 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /lib/src/model/rule_node_models.dart: -------------------------------------------------------------------------------- 1 | import 'has_name.dart'; 2 | import 'id/rule_chain_id.dart'; 3 | import 'id/rule_node_id.dart'; 4 | import 'additional_info_based.dart'; 5 | 6 | class RuleNode extends AdditionalInfoBased with HasName { 7 | RuleChainId? ruleChainId; 8 | String type; 9 | String name; 10 | bool debugMode; 11 | bool? singletonMode; 12 | int? configurationVersion; 13 | Map? configuration; 14 | 15 | RuleNode( 16 | {required this.type, 17 | required this.name, 18 | this.debugMode = false, 19 | this.ruleChainId, 20 | this.singletonMode, 21 | this.configurationVersion, 22 | this.configuration}); 23 | 24 | RuleNode.fromJson(Map json) 25 | : ruleChainId = json['ruleChainId'] != null 26 | ? RuleChainId.fromJson(json['ruleChainId']) 27 | : null, 28 | type = json['type'], 29 | name = json['name'], 30 | debugMode = json['debugMode'], 31 | singletonMode = json['singletonMode'], 32 | configurationVersion = json['configurationVersion'], 33 | configuration = json['configuration'], 34 | super.fromJson(json); 35 | 36 | @override 37 | Map toJson() { 38 | var json = super.toJson(); 39 | if (ruleChainId != null) { 40 | json['ruleChainId'] = ruleChainId!.toJson(); 41 | } 42 | json['type'] = type; 43 | json['name'] = name; 44 | json['debugMode'] = debugMode; 45 | json['singletonMode'] = singletonMode; 46 | json['configurationVersion'] = configurationVersion; 47 | if (configuration != null) { 48 | json['configuration'] = configuration; 49 | } 50 | return json; 51 | } 52 | 53 | @override 54 | String getName() { 55 | return name; 56 | } 57 | 58 | @override 59 | String toString() { 60 | return 'RuleNode{${additionalInfoBasedString('ruleChainId: $ruleChainId, type: $type, name: $name, ' 61 | 'debugMode: $debugMode, singletonMode: $singletonMode, ' 62 | 'configurationVersion: $configurationVersion, configuration: $configuration')}}'; 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /lib/src/model/thingsboard_error.dart: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /lib/src/model/user_models.dart: -------------------------------------------------------------------------------- 1 | import 'package:thingsboard_client/thingsboard_client.dart'; 2 | 3 | class AuthUser { 4 | late String sub; 5 | late List scopes; 6 | late String? userId; 7 | late String? firstName; 8 | late String? lastName; 9 | late bool? enabled; 10 | late String tenantId; 11 | late String? customerId; 12 | late bool? isPublic; 13 | late Authority authority; 14 | late Map additionalData; 15 | 16 | AuthUser.fromJson(Map json) { 17 | var claims = Map.of(json); 18 | sub = claims.remove('sub'); 19 | scopes = (claims.remove('scopes') as List).cast(); 20 | userId = claims.remove('userId'); 21 | firstName = claims.remove('firstName'); 22 | lastName = claims.remove('lastName'); 23 | enabled = claims.remove('enabled'); 24 | tenantId = claims.remove('tenantId'); 25 | customerId = claims.remove('customerId'); 26 | isPublic = claims.remove('isPublic'); 27 | authority = scopes.isNotEmpty 28 | ? authorityFromString(scopes[0]) 29 | : Authority.ANONYMOUS; 30 | additionalData = claims; 31 | } 32 | 33 | bool isSystemAdmin() { 34 | return authority == Authority.SYS_ADMIN; 35 | } 36 | 37 | bool isTenantAdmin() { 38 | return authority == Authority.TENANT_ADMIN; 39 | } 40 | 41 | bool isCustomerUser() { 42 | return authority == Authority.CUSTOMER_USER; 43 | } 44 | 45 | bool isPreVerificationToken() { 46 | return authority == Authority.PRE_VERIFICATION_TOKEN; 47 | } 48 | 49 | @override 50 | String toString() { 51 | return 'AuthUser{sub: $sub, scopes: $scopes, userId: $userId, firstName: $firstName, lastName: $lastName, enabled: $enabled, ' 52 | 'tenantId: $tenantId, customerId: $customerId, isPublic: $isPublic, authority: ${authority.toShortString()}, additionalData: $additionalData'; 53 | } 54 | } 55 | 56 | class User extends AdditionalInfoBased 57 | with HasName, HasTenantId, HasCustomerId { 58 | TenantId? tenantId; 59 | CustomerId? customerId; 60 | String email; 61 | Authority authority; 62 | String? firstName; 63 | String? lastName; 64 | String? phone; 65 | 66 | User(this.email, this.authority); 67 | 68 | User.fromJson(Map json) 69 | : tenantId = json['tenantId'] != null 70 | ? TenantId.fromJson(json['tenantId']) 71 | : null, 72 | customerId = json['customerId'] != null 73 | ? CustomerId.fromJson(json['customerId']) 74 | : null, 75 | email = json['email'], 76 | authority = authorityFromString(json['authority']), 77 | firstName = json['firstName'], 78 | lastName = json['lastName'], 79 | phone = json['phone'], 80 | super.fromJson(json); 81 | 82 | @override 83 | Map toJson() { 84 | var json = super.toJson(); 85 | if (tenantId != null) { 86 | json['tenantId'] = tenantId!.toJson(); 87 | } 88 | if (customerId != null) { 89 | json['customerId'] = customerId!.toJson(); 90 | } 91 | json['email'] = email; 92 | json['authority'] = authority.toShortString(); 93 | if (firstName != null) { 94 | json['firstName'] = firstName; 95 | } 96 | if (lastName != null) { 97 | json['lastName'] = lastName; 98 | } 99 | if (phone != null) { 100 | json['phone'] = phone; 101 | } 102 | return json; 103 | } 104 | 105 | @override 106 | String getName() { 107 | return email; 108 | } 109 | 110 | @override 111 | TenantId? getTenantId() { 112 | return tenantId; 113 | } 114 | 115 | @override 116 | CustomerId? getCustomerId() { 117 | return customerId; 118 | } 119 | 120 | bool isSystemAdmin() { 121 | return authority == Authority.SYS_ADMIN; 122 | } 123 | 124 | bool isTenantAdmin() { 125 | return authority == Authority.TENANT_ADMIN; 126 | } 127 | 128 | bool isCustomerUser() { 129 | return authority == Authority.CUSTOMER_USER; 130 | } 131 | 132 | @override 133 | String toString() { 134 | return 'User{${additionalInfoBasedString('tenantId: $tenantId, customerId: $customerId, email: $email, ' 135 | 'authority: ${authority.toShortString()}, firstName: $firstName, lastName: $lastName, phone: $phone')}}'; 136 | } 137 | } 138 | 139 | class UserInfo { 140 | UserInfo( 141 | this.id, { 142 | required this.email, 143 | this.firstName, 144 | this.lastName, 145 | }); 146 | 147 | final UserId id; 148 | String email; 149 | String? firstName; 150 | String? lastName; 151 | 152 | UserInfo.fromJson(Map json) 153 | : id = UserId.fromJson(json['id']), 154 | email = json['email'], 155 | firstName = json['firstName'], 156 | lastName = json['lastName']; 157 | } 158 | 159 | class UsersAssignQuery { 160 | const UsersAssignQuery({ 161 | required this.pageLink, 162 | required this.id, 163 | }); 164 | 165 | final PageLink pageLink; 166 | final AlarmId id; 167 | 168 | Map toQueryParameters() { 169 | return pageLink.toQueryParameters(); 170 | } 171 | } 172 | -------------------------------------------------------------------------------- /lib/src/model/version.dart: -------------------------------------------------------------------------------- 1 | class PlatformVersionMatcher { 2 | static const int minPlatformVersionInt = 3900; 3 | 4 | static bool isSupportedPlatformVersion( 5 | PlatformVersion platformVersion, { 6 | required String type, 7 | }) { 8 | if (type != 'CE') { 9 | return false; 10 | } 11 | 12 | try { 13 | if (platformVersion.versionInt() < minPlatformVersionInt) { 14 | return false; 15 | } 16 | } catch (e) { 17 | return false; 18 | } 19 | return true; 20 | } 21 | } 22 | 23 | class PlatformVersion { 24 | static RegExp versionRegExp = new RegExp(r"([\d|.]+)([A-Z]*)(-SNAPSHOT)?"); 25 | 26 | int major; 27 | int minor; 28 | int patch; 29 | int? minorPatch; 30 | String? versionCode; 31 | bool isSnapshot; 32 | 33 | PlatformVersion( 34 | {required this.major, 35 | required this.minor, 36 | required this.patch, 37 | this.minorPatch, 38 | this.versionCode, 39 | this.isSnapshot = false}); 40 | 41 | factory PlatformVersion.fromString(String version) { 42 | RegExpMatch? match = versionRegExp.firstMatch(version); 43 | if (match != null) { 44 | String? versionStr = match.group(1); 45 | if (versionStr != null) { 46 | List versionParts = versionStr.split("."); 47 | if (versionParts.length >= 3) { 48 | int major = int.parse(versionParts[0]); 49 | int minor = int.parse(versionParts[1]); 50 | int patch = int.parse(versionParts[2]); 51 | int? minorPatch; 52 | if (versionParts.length > 3) { 53 | minorPatch = int.parse(versionParts[3]); 54 | } 55 | String? versionCode = match.group(2); 56 | bool isSnapshot = match.group(3) != null; 57 | return PlatformVersion( 58 | major: major, 59 | minor: minor, 60 | patch: patch, 61 | minorPatch: minorPatch, 62 | versionCode: versionCode, 63 | isSnapshot: isSnapshot); 64 | } 65 | } 66 | } 67 | throw ArgumentError("Invalid platform version string: $version"); 68 | } 69 | 70 | int versionInt() { 71 | return this.major * 1000 + 72 | this.minor * 100 + 73 | this.patch * 10 + 74 | (this.minorPatch != null ? this.minorPatch! : 0); 75 | } 76 | 77 | String versionString() { 78 | String version = "$major.$minor.$patch"; 79 | if (this.minorPatch != null) { 80 | version += ".$minorPatch"; 81 | } 82 | if (versionCode != null && versionCode!.isNotEmpty) { 83 | version += "$versionCode"; 84 | } 85 | if (isSnapshot) { 86 | version += "-SNAPSHOT"; 87 | } 88 | return version; 89 | } 90 | 91 | @override 92 | String toString() { 93 | return versionString(); 94 | } 95 | } 96 | -------------------------------------------------------------------------------- /lib/src/model/widget_models.dart: -------------------------------------------------------------------------------- 1 | import 'dart:math'; 2 | 3 | import 'base_data.dart'; 4 | import 'has_tenant_id.dart'; 5 | import 'id/tenant_id.dart'; 6 | import 'id/widget_type_id.dart'; 7 | 8 | class BaseWidgetType extends BaseData with HasTenantId { 9 | TenantId? tenantId; 10 | String name; 11 | String fqn; 12 | bool? deprecated; 13 | 14 | BaseWidgetType(this.name, this.fqn); 15 | 16 | BaseWidgetType.fromJson(Map json) 17 | : tenantId = json['tenantId'] != null 18 | ? TenantId.fromJson(json['tenantId']) 19 | : null, 20 | name = json['name'], 21 | fqn = json['fqn'], 22 | deprecated = json['deprecated'], 23 | super.fromJson(json); 24 | 25 | @override 26 | Map toJson() { 27 | var json = super.toJson(); 28 | json['name'] = name; 29 | json['fqn'] = fqn; 30 | if (tenantId != null) { 31 | json['tenantId'] = tenantId!.toJson(); 32 | } 33 | if (deprecated != null) { 34 | json['deprecated'] = deprecated; 35 | } 36 | return json; 37 | } 38 | 39 | @override 40 | TenantId? getTenantId() { 41 | return tenantId; 42 | } 43 | 44 | @override 45 | String toString() { 46 | return 'BaseWidgetType{${baseWidgetTypeString()}}'; 47 | } 48 | 49 | String baseWidgetTypeString([String? toStringBody]) { 50 | return '${baseDataString('tenantId: $tenantId, name: $name, fqn: $fqn, deprecated: $deprecated, ${toStringBody != null ? ', ' + toStringBody : ''}')}'; 51 | } 52 | } 53 | 54 | class WidgetTypeInfo extends BaseWidgetType { 55 | String? image; 56 | String? description; 57 | String widgetType; 58 | 59 | WidgetTypeInfo(String name, String fqn, this.widgetType) : super(name, fqn); 60 | 61 | WidgetTypeInfo.fromJson(Map json) 62 | : image = json['image'], 63 | description = json['description'], 64 | widgetType = json['widgetType'], 65 | super.fromJson(json); 66 | 67 | @override 68 | String toString() { 69 | return 'WidgetTypeInfo{${baseWidgetTypeString('widgetType: $widgetType, image: ${image != null ? '[' + image!.substring(0, min(30, image!.length)) + '...]' : 'null'}, description: $description')}}'; 70 | } 71 | } 72 | 73 | class WidgetType extends BaseWidgetType { 74 | Map descriptor; 75 | 76 | WidgetType(String name, String fqn, this.descriptor) : super(name, fqn); 77 | 78 | WidgetType.fromJson(Map json) 79 | : descriptor = json['descriptor'], 80 | super.fromJson(json); 81 | 82 | @override 83 | Map toJson() { 84 | var json = super.toJson(); 85 | json['descriptor'] = descriptor; 86 | return json; 87 | } 88 | 89 | @override 90 | String toString() { 91 | return 'WidgetType{${widgetTypeString()}}'; 92 | } 93 | 94 | String widgetTypeString([String? toStringBody]) { 95 | return '${baseWidgetTypeString('descriptor: $descriptor${toStringBody != null ? ', ' + toStringBody : ''}')}'; 96 | } 97 | } 98 | 99 | class WidgetTypeDetails extends WidgetType { 100 | String? image; 101 | String? description; 102 | WidgetTypeId? externalId; 103 | 104 | WidgetTypeDetails(String name, String fqn, Map descriptor) 105 | : super(name, fqn, descriptor); 106 | 107 | WidgetTypeDetails.fromJson(Map json) 108 | : image = json['image'], 109 | description = json['description'], 110 | externalId = json['externalId'], 111 | super.fromJson(json); 112 | 113 | @override 114 | Map toJson() { 115 | var json = super.toJson(); 116 | if (image != null) { 117 | json['image'] = image; 118 | } 119 | if (description != null) { 120 | json['description'] = description; 121 | } 122 | if (externalId != null) { 123 | json['externalId'] = externalId; 124 | } 125 | return json; 126 | } 127 | 128 | @override 129 | String toString() { 130 | return 'WidgetTypeDetails{${widgetTypeString('image: ${image != null ? '[' + image!.substring(0, min(30, image!.length)) + '...]' : 'null'}, ' 131 | 'description: $description, externalId: $externalId')}}'; 132 | } 133 | } 134 | -------------------------------------------------------------------------------- /lib/src/model/widgets_bundle_model.dart: -------------------------------------------------------------------------------- 1 | import 'dart:math'; 2 | 3 | import 'base_data.dart'; 4 | import 'exportable_entity.dart'; 5 | import 'has_tenant_id.dart'; 6 | import 'id/tenant_id.dart'; 7 | import 'id/widgets_bundle_id.dart'; 8 | 9 | class WidgetsBundle extends BaseData 10 | with HasTenantId, ExportableEntity { 11 | TenantId? tenantId; 12 | String? alias; 13 | String title; 14 | String? image; 15 | String? description; 16 | WidgetsBundleId? externalId; 17 | 18 | WidgetsBundle(this.title); 19 | 20 | WidgetsBundle.fromJson(Map json) 21 | : tenantId = json['tenantId'] != null 22 | ? TenantId.fromJson(json['tenantId']) 23 | : null, 24 | alias = json['alias'], 25 | title = json['title'], 26 | image = json['image'], 27 | description = json['description'], 28 | externalId = json['externalId'] != null 29 | ? WidgetsBundleId.fromJson(json['externalId']) 30 | : null, 31 | super.fromJson(json); 32 | 33 | @override 34 | Map toJson() { 35 | var json = super.toJson(); 36 | json['title'] = title; 37 | if (tenantId != null) { 38 | json['tenantId'] = tenantId!.toJson(); 39 | } 40 | if (alias != null) { 41 | json['alias'] = alias; 42 | } 43 | if (image != null) { 44 | json['image'] = image; 45 | } 46 | if (description != null) { 47 | json['description'] = description; 48 | } 49 | if (externalId != null) { 50 | json['externalId'] = externalId!.toJson(); 51 | } 52 | return json; 53 | } 54 | 55 | @override 56 | String getName() { 57 | return title; 58 | } 59 | 60 | @override 61 | TenantId? getTenantId() { 62 | return tenantId; 63 | } 64 | 65 | @override 66 | void setTenantId(TenantId? tenantId) { 67 | this.tenantId = tenantId; 68 | } 69 | 70 | @override 71 | WidgetsBundleId? getExternalId() { 72 | return externalId; 73 | } 74 | 75 | @override 76 | void setExternalId(WidgetsBundleId? externalId) { 77 | this.externalId = externalId; 78 | } 79 | 80 | @override 81 | String toString() { 82 | return 'WidgetsBundle{${baseDataString('tenantId: $tenantId, alias: $alias, title: $title, image: ${image != null ? '[' + image!.substring(0, min(30, image!.length)) + '...]' : 'null'}, ' 83 | 'description: $description, externalId: $externalId')}}'; 84 | } 85 | } 86 | -------------------------------------------------------------------------------- /lib/src/service/asset_profile_service.dart: -------------------------------------------------------------------------------- 1 | import 'dart:convert'; 2 | 3 | import '../http/http_utils.dart'; 4 | import '../model/asset_models.dart'; 5 | import '../model/page/page_data.dart'; 6 | import '../model/page/page_link.dart'; 7 | import '../thingsboard_client_base.dart'; 8 | 9 | PageData parseAssetProfilePageData(Map json) { 10 | return PageData.fromJson(json, (json) => AssetProfile.fromJson(json)); 11 | } 12 | 13 | PageData parseAssetProfileInfoPageData( 14 | Map json) { 15 | return PageData.fromJson(json, (json) => AssetProfileInfo.fromJson(json)); 16 | } 17 | 18 | class AssetProfileService { 19 | final ThingsboardClient _tbClient; 20 | 21 | factory AssetProfileService(ThingsboardClient tbClient) { 22 | return AssetProfileService._internal(tbClient); 23 | } 24 | 25 | AssetProfileService._internal(this._tbClient); 26 | 27 | Future> getAssetProfiles(PageLink pageLink, 28 | {RequestConfig? requestConfig}) async { 29 | var response = await _tbClient.get>( 30 | '/api/assetProfiles', 31 | queryParameters: pageLink.toQueryParameters(), 32 | options: defaultHttpOptionsFromConfig(requestConfig)); 33 | return _tbClient.compute(parseAssetProfilePageData, response.data!); 34 | } 35 | 36 | Future getAssetProfile(String assetProfileId, 37 | {RequestConfig? requestConfig}) async { 38 | return nullIfNotFound( 39 | (RequestConfig requestConfig) async { 40 | var response = await _tbClient.get>( 41 | '/api/assetProfile/$assetProfileId', 42 | options: defaultHttpOptionsFromConfig(requestConfig)); 43 | return response.data != null 44 | ? AssetProfile.fromJson(response.data!) 45 | : null; 46 | }, 47 | requestConfig: requestConfig, 48 | ); 49 | } 50 | 51 | Future saveAssetProfile(AssetProfile assetProfile, 52 | {RequestConfig? requestConfig}) async { 53 | var response = await _tbClient.post>( 54 | '/api/assetProfile', 55 | data: jsonEncode(assetProfile), 56 | options: defaultHttpOptionsFromConfig(requestConfig)); 57 | return AssetProfile.fromJson(response.data!); 58 | } 59 | 60 | Future deleteAssetProfile(String assetProfileId, 61 | {RequestConfig? requestConfig}) async { 62 | await _tbClient.delete('/api/assetProfile/$assetProfileId', 63 | options: defaultHttpOptionsFromConfig(requestConfig)); 64 | } 65 | 66 | Future setDefaultAssetProfile(String assetProfileId, 67 | {RequestConfig? requestConfig}) async { 68 | var response = await _tbClient.post>( 69 | '/api/assetProfile/$assetProfileId/default', 70 | options: defaultHttpOptionsFromConfig(requestConfig)); 71 | return AssetProfile.fromJson(response.data!); 72 | } 73 | 74 | Future getDefaultAssetProfileInfo( 75 | {RequestConfig? requestConfig}) async { 76 | var response = await _tbClient.get>( 77 | '/api/assetProfileInfo/default', 78 | options: defaultHttpOptionsFromConfig(requestConfig)); 79 | return AssetProfileInfo.fromJson(response.data!); 80 | } 81 | 82 | Future getAssetProfileInfo(String assetProfileId, 83 | {RequestConfig? requestConfig}) async { 84 | return nullIfNotFound( 85 | (RequestConfig requestConfig) async { 86 | var response = await _tbClient.get>( 87 | '/api/assetProfileInfo/$assetProfileId', 88 | options: defaultHttpOptionsFromConfig(requestConfig)); 89 | return response.data != null 90 | ? AssetProfileInfo.fromJson(response.data!) 91 | : null; 92 | }, 93 | requestConfig: requestConfig, 94 | ); 95 | } 96 | 97 | Future> getAssetProfileInfos(PageLink pageLink, 98 | {RequestConfig? requestConfig}) async { 99 | var response = await _tbClient.get>( 100 | '/api/assetProfileInfos', 101 | queryParameters: pageLink.toQueryParameters(), 102 | options: defaultHttpOptionsFromConfig(requestConfig)); 103 | return _tbClient.compute(parseAssetProfileInfoPageData, response.data!); 104 | } 105 | } 106 | -------------------------------------------------------------------------------- /lib/src/service/audit_log_service.dart: -------------------------------------------------------------------------------- 1 | import '../thingsboard_client_base.dart'; 2 | import '../http/http_utils.dart'; 3 | import '../model/model.dart'; 4 | 5 | PageData parseAuditLogPageData(Map json) { 6 | return PageData.fromJson(json, (json) => AuditLog.fromJson(json)); 7 | } 8 | 9 | class AuditLogService { 10 | final ThingsboardClient _tbClient; 11 | 12 | factory AuditLogService(ThingsboardClient tbClient) { 13 | return AuditLogService._internal(tbClient); 14 | } 15 | 16 | AuditLogService._internal(this._tbClient); 17 | 18 | Future> getAuditLogs(TimePageLink pageLink, 19 | {RequestConfig? requestConfig}) async { 20 | var queryParams = pageLink.toQueryParameters(); 21 | var response = await _tbClient.get>('/api/audit/logs', 22 | queryParameters: queryParams, 23 | options: defaultHttpOptionsFromConfig(requestConfig)); 24 | return _tbClient.compute(parseAuditLogPageData, response.data!); 25 | } 26 | 27 | Future> getAuditLogsByCustomerId( 28 | String customerId, TimePageLink pageLink, 29 | {RequestConfig? requestConfig}) async { 30 | var queryParams = pageLink.toQueryParameters(); 31 | var response = await _tbClient.get>( 32 | '/api/audit/logs/customer/$customerId', 33 | queryParameters: queryParams, 34 | options: defaultHttpOptionsFromConfig(requestConfig)); 35 | return _tbClient.compute(parseAuditLogPageData, response.data!); 36 | } 37 | 38 | Future> getAuditLogsByUserId( 39 | String userId, TimePageLink pageLink, 40 | {RequestConfig? requestConfig}) async { 41 | var queryParams = pageLink.toQueryParameters(); 42 | var response = await _tbClient.get>( 43 | '/api/audit/logs/user/$userId', 44 | queryParameters: queryParams, 45 | options: defaultHttpOptionsFromConfig(requestConfig)); 46 | return _tbClient.compute(parseAuditLogPageData, response.data!); 47 | } 48 | 49 | Future> getAuditLogsByEntityId( 50 | EntityId entityId, TimePageLink pageLink, 51 | {RequestConfig? requestConfig}) async { 52 | var queryParams = pageLink.toQueryParameters(); 53 | var response = await _tbClient.get>( 54 | '/api/audit/logs/entity/${entityId.entityType.toShortString()}/${entityId.id}', 55 | queryParameters: queryParams, 56 | options: defaultHttpOptionsFromConfig(requestConfig)); 57 | return _tbClient.compute(parseAuditLogPageData, response.data!); 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /lib/src/service/component_descriptor_service.dart: -------------------------------------------------------------------------------- 1 | import '../../thingsboard_client.dart'; 2 | 3 | class ComponentDescriptorService { 4 | final ThingsboardClient _tbClient; 5 | 6 | factory ComponentDescriptorService(ThingsboardClient tbClient) { 7 | return ComponentDescriptorService._internal(tbClient); 8 | } 9 | 10 | ComponentDescriptorService._internal(this._tbClient); 11 | 12 | Future getComponentDescriptorByClazz( 13 | String componentDescriptorClazz, 14 | {RequestConfig? requestConfig}) async { 15 | return nullIfNotFound( 16 | (RequestConfig requestConfig) async { 17 | var response = await _tbClient.get>( 18 | '/api/component/$componentDescriptorClazz', 19 | options: defaultHttpOptionsFromConfig(requestConfig)); 20 | return response.data != null 21 | ? ComponentDescriptor.fromJson(response.data!) 22 | : null; 23 | }, 24 | requestConfig: requestConfig, 25 | ); 26 | } 27 | 28 | Future> getComponentDescriptorsByType( 29 | ComponentType componentType, 30 | {RuleChainType ruleChainType = RuleChainType.CORE, 31 | RequestConfig? requestConfig}) async { 32 | var response = await _tbClient.get>( 33 | '/api/components/${componentType.toShortString()}', 34 | queryParameters: {'ruleChainType': ruleChainType.toShortString()}, 35 | options: defaultHttpOptionsFromConfig(requestConfig)); 36 | return response.data!.map((e) => ComponentDescriptor.fromJson(e)).toList(); 37 | } 38 | 39 | Future> getComponentDescriptorsByTypes( 40 | List componentTypes, 41 | {RuleChainType ruleChainType = RuleChainType.CORE, 42 | RequestConfig? requestConfig}) async { 43 | var response = await _tbClient.get>('/api/components', 44 | queryParameters: { 45 | 'componentTypes': 46 | componentTypes.map((e) => e.toShortString()).join(','), 47 | 'ruleChainType': ruleChainType.toShortString() 48 | }, 49 | options: defaultHttpOptionsFromConfig(requestConfig)); 50 | return response.data!.map((e) => ComponentDescriptor.fromJson(e)).toList(); 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /lib/src/service/customer_service.dart: -------------------------------------------------------------------------------- 1 | import 'dart:convert'; 2 | 3 | import 'package:dio/dio.dart'; 4 | 5 | import '../thingsboard_client_base.dart'; 6 | import '../http/http_utils.dart'; 7 | import '../model/model.dart'; 8 | 9 | PageData parseCustomerPageData(Map json) { 10 | return PageData.fromJson(json, (json) => Customer.fromJson(json)); 11 | } 12 | 13 | class CustomerService { 14 | final ThingsboardClient _tbClient; 15 | 16 | factory CustomerService(ThingsboardClient tbClient) { 17 | return CustomerService._internal(tbClient); 18 | } 19 | 20 | CustomerService._internal(this._tbClient); 21 | 22 | Future> getCustomers(PageLink pageLink, 23 | {RequestConfig? requestConfig}) async { 24 | var queryParams = pageLink.toQueryParameters(); 25 | var response = await _tbClient.get>('/api/customers', 26 | queryParameters: queryParams, 27 | options: defaultHttpOptionsFromConfig(requestConfig)); 28 | return _tbClient.compute(parseCustomerPageData, response.data!); 29 | } 30 | 31 | Future getCustomer(String customerId, 32 | {RequestConfig? requestConfig}) async { 33 | return nullIfNotFound( 34 | (RequestConfig requestConfig) async { 35 | var response = await _tbClient.get>( 36 | '/api/customer/$customerId', 37 | options: defaultHttpOptionsFromConfig(requestConfig)); 38 | return response.data != null ? Customer.fromJson(response.data!) : null; 39 | }, 40 | requestConfig: requestConfig, 41 | ); 42 | } 43 | 44 | Future getShortCustomerInfo(String customerId, 45 | {RequestConfig? requestConfig}) async { 46 | return nullIfNotFound( 47 | (RequestConfig requestConfig) async { 48 | var response = await _tbClient.get>( 49 | '/api/customer/$customerId/shortInfo', 50 | options: defaultHttpOptionsFromConfig(requestConfig)); 51 | return response.data != null 52 | ? ShortCustomerInfo.fromJson(response.data!) 53 | : null; 54 | }, 55 | requestConfig: requestConfig, 56 | ); 57 | } 58 | 59 | Future getCustomerTitle(String customerId, 60 | {RequestConfig? requestConfig}) async { 61 | return nullIfNotFound( 62 | (RequestConfig requestConfig) async { 63 | var options = defaultHttpOptionsFromConfig(requestConfig); 64 | options.responseType = ResponseType.plain; 65 | var response = await _tbClient 66 | .get('/api/customer/$customerId/title', options: options); 67 | return response.data; 68 | }, 69 | requestConfig: requestConfig, 70 | ); 71 | } 72 | 73 | Future getTenantCustomer(String customerTitle, 74 | {RequestConfig? requestConfig}) async { 75 | return nullIfNotFound( 76 | (RequestConfig requestConfig) async { 77 | var response = await _tbClient.get>( 78 | '/api/tenant/customers', 79 | queryParameters: {'customerTitle': customerTitle}, 80 | options: defaultHttpOptionsFromConfig(requestConfig)); 81 | return response.data != null ? Customer.fromJson(response.data!) : null; 82 | }, 83 | requestConfig: requestConfig, 84 | ); 85 | } 86 | 87 | Future saveCustomer(Customer customer, 88 | {RequestConfig? requestConfig}) async { 89 | var response = await _tbClient.post>('/api/customer', 90 | data: jsonEncode(customer), 91 | options: defaultHttpOptionsFromConfig(requestConfig)); 92 | return Customer.fromJson(response.data!); 93 | } 94 | 95 | Future deleteCustomer(String customerId, 96 | {RequestConfig? requestConfig}) async { 97 | await _tbClient.delete('/api/customer/$customerId', 98 | options: defaultHttpOptionsFromConfig(requestConfig)); 99 | } 100 | } 101 | -------------------------------------------------------------------------------- /lib/src/service/device_profile_service.dart: -------------------------------------------------------------------------------- 1 | import 'dart:convert'; 2 | 3 | import '../http/http_utils.dart'; 4 | import '../model/page/page_link.dart'; 5 | import '../model/device_models.dart'; 6 | import '../model/page/page_data.dart'; 7 | import '../thingsboard_client_base.dart'; 8 | 9 | PageData parseDeviceProfilePageData(Map json) { 10 | return PageData.fromJson(json, (json) => DeviceProfile.fromJson(json)); 11 | } 12 | 13 | PageData parseDeviceProfileInfoPageData( 14 | Map json) { 15 | return PageData.fromJson(json, (json) => DeviceProfileInfo.fromJson(json)); 16 | } 17 | 18 | class DeviceProfileService { 19 | final ThingsboardClient _tbClient; 20 | 21 | factory DeviceProfileService(ThingsboardClient tbClient) { 22 | return DeviceProfileService._internal(tbClient); 23 | } 24 | 25 | DeviceProfileService._internal(this._tbClient); 26 | 27 | Future> getDeviceProfiles(PageLink pageLink, 28 | {RequestConfig? requestConfig}) async { 29 | var response = await _tbClient.get>( 30 | '/api/deviceProfiles', 31 | queryParameters: pageLink.toQueryParameters(), 32 | options: defaultHttpOptionsFromConfig(requestConfig)); 33 | return _tbClient.compute(parseDeviceProfilePageData, response.data!); 34 | } 35 | 36 | Future getDeviceProfile(String deviceProfileId, 37 | {RequestConfig? requestConfig}) async { 38 | return nullIfNotFound( 39 | (RequestConfig requestConfig) async { 40 | var response = await _tbClient.get>( 41 | '/api/deviceProfile/$deviceProfileId', 42 | options: defaultHttpOptionsFromConfig(requestConfig)); 43 | return response.data != null 44 | ? DeviceProfile.fromJson(response.data!) 45 | : null; 46 | }, 47 | requestConfig: requestConfig, 48 | ); 49 | } 50 | 51 | Future saveDeviceProfile(DeviceProfile deviceProfile, 52 | {RequestConfig? requestConfig}) async { 53 | var response = await _tbClient.post>( 54 | '/api/deviceProfile', 55 | data: jsonEncode(deviceProfile), 56 | options: defaultHttpOptionsFromConfig(requestConfig)); 57 | return DeviceProfile.fromJson(response.data!); 58 | } 59 | 60 | Future deleteDeviceProfile(String deviceProfileId, 61 | {RequestConfig? requestConfig}) async { 62 | await _tbClient.delete('/api/deviceProfile/$deviceProfileId', 63 | options: defaultHttpOptionsFromConfig(requestConfig)); 64 | } 65 | 66 | Future setDefaultDeviceProfile(String deviceProfileId, 67 | {RequestConfig? requestConfig}) async { 68 | var response = await _tbClient.post>( 69 | '/api/deviceProfile/$deviceProfileId/default', 70 | options: defaultHttpOptionsFromConfig(requestConfig)); 71 | return DeviceProfile.fromJson(response.data!); 72 | } 73 | 74 | Future getDefaultDeviceProfileInfo( 75 | {RequestConfig? requestConfig}) async { 76 | var response = await _tbClient.get>( 77 | '/api/deviceProfileInfo/default', 78 | options: defaultHttpOptionsFromConfig(requestConfig)); 79 | return DeviceProfileInfo.fromJson(response.data!); 80 | } 81 | 82 | Future getDeviceProfileInfo(String deviceProfileId, 83 | {RequestConfig? requestConfig}) async { 84 | return nullIfNotFound( 85 | (RequestConfig requestConfig) async { 86 | var response = await _tbClient.get>( 87 | '/api/deviceProfileInfo/$deviceProfileId', 88 | options: defaultHttpOptionsFromConfig(requestConfig)); 89 | return response.data != null 90 | ? DeviceProfileInfo.fromJson(response.data!) 91 | : null; 92 | }, 93 | requestConfig: requestConfig, 94 | ); 95 | } 96 | 97 | Future> getDeviceProfileInfos(PageLink pageLink, 98 | {DeviceTransportType? transportType, 99 | RequestConfig? requestConfig}) async { 100 | var queryParams = pageLink.toQueryParameters(); 101 | if (transportType != null) { 102 | queryParams['transportType'] = transportType.toShortString(); 103 | } 104 | var response = await _tbClient.get>( 105 | '/api/deviceProfileInfos', 106 | queryParameters: queryParams, 107 | options: defaultHttpOptionsFromConfig(requestConfig)); 108 | return _tbClient.compute(parseDeviceProfileInfoPageData, response.data!); 109 | } 110 | 111 | Future> getDeviceProfileDevicesAttributesKeys( 112 | {String? deviceProfileId, RequestConfig? requestConfig}) async { 113 | var queryParams = {}; 114 | if (deviceProfileId != null) { 115 | queryParams['deviceProfileId'] = deviceProfileId; 116 | } 117 | var response = await _tbClient.get>( 118 | '/api/deviceProfile/devices/keys/attributes', 119 | queryParameters: queryParams, 120 | options: defaultHttpOptionsFromConfig(requestConfig)); 121 | return response.data!; 122 | } 123 | 124 | Future> getDeviceProfileDevicesTimeseriesKeys( 125 | {String? deviceProfileId, RequestConfig? requestConfig}) async { 126 | var queryParams = {}; 127 | if (deviceProfileId != null) { 128 | queryParams['deviceProfileId'] = deviceProfileId; 129 | } 130 | var response = await _tbClient.get>( 131 | '/api/deviceProfile/devices/keys/timeseries', 132 | queryParameters: queryParams, 133 | options: defaultHttpOptionsFromConfig(requestConfig)); 134 | return response.data!; 135 | } 136 | } 137 | -------------------------------------------------------------------------------- /lib/src/service/entities_version_control_service.dart: -------------------------------------------------------------------------------- 1 | import 'dart:convert'; 2 | import '../thingsboard_client_base.dart'; 3 | import '../model/model.dart'; 4 | import '../http/http_utils.dart'; 5 | 6 | PageData parseEntityVersionPageData(Map json) { 7 | return PageData.fromJson(json, (json) => EntityVersion.fromJson(json)); 8 | } 9 | 10 | class EntitiesVersionControlService { 11 | final ThingsboardClient _tbClient; 12 | 13 | factory EntitiesVersionControlService(ThingsboardClient tbClient) { 14 | return EntitiesVersionControlService._internal(tbClient); 15 | } 16 | 17 | EntitiesVersionControlService._internal(this._tbClient); 18 | 19 | Future saveEntitiesVersion(VersionCreateRequest request, 20 | {RequestConfig? requestConfig}) async { 21 | var response = await _tbClient.post('/api/entities/vc/version', 22 | data: jsonEncode(request), 23 | options: defaultHttpOptionsFromConfig(requestConfig)); 24 | return response.data!; 25 | } 26 | 27 | Future getVersionCreateRequestStatus(String requestId, 28 | {RequestConfig? requestConfig}) async { 29 | return nullIfNotFound( 30 | (RequestConfig requestConfig) async { 31 | var response = await _tbClient.get>( 32 | '/api/entities/vc/version/$requestId/status', 33 | options: defaultHttpOptionsFromConfig(requestConfig)); 34 | return response.data != null 35 | ? VersionCreationResult.fromJson(response.data!) 36 | : null; 37 | }, 38 | requestConfig: requestConfig, 39 | ); 40 | } 41 | 42 | Future> listEntityVersions( 43 | PageLink pageLink, String branch, EntityId externalEntityId, 44 | {RequestConfig? requestConfig}) async { 45 | var queryParams = pageLink.toQueryParameters(); 46 | queryParams['branch'] = branch; 47 | var response = await _tbClient.get>( 48 | '/api/entities/vc/version/${externalEntityId.entityType.toShortString()}/${externalEntityId.id}', 49 | queryParameters: queryParams, 50 | options: defaultHttpOptionsFromConfig(requestConfig)); 51 | return _tbClient.compute(parseEntityVersionPageData, response.data!); 52 | } 53 | 54 | Future> listEntityTypeVersions( 55 | PageLink pageLink, String branch, EntityType entityType, 56 | {RequestConfig? requestConfig}) async { 57 | var queryParams = pageLink.toQueryParameters(); 58 | queryParams['branch'] = branch; 59 | var response = await _tbClient.get>( 60 | '/api/entities/vc/version/${entityType.toShortString()}', 61 | queryParameters: queryParams, 62 | options: defaultHttpOptionsFromConfig(requestConfig)); 63 | return _tbClient.compute(parseEntityVersionPageData, response.data!); 64 | } 65 | 66 | Future> listVersions(PageLink pageLink, String branch, 67 | {RequestConfig? requestConfig}) async { 68 | var queryParams = pageLink.toQueryParameters(); 69 | queryParams['branch'] = branch; 70 | var response = await _tbClient.get>( 71 | '/api/entities/vc/version', 72 | queryParameters: queryParams, 73 | options: defaultHttpOptionsFromConfig(requestConfig)); 74 | return _tbClient.compute(parseEntityVersionPageData, response.data!); 75 | } 76 | 77 | Future getEntityDataInfo( 78 | EntityId externalEntityId, String versionId, 79 | {RequestConfig? requestConfig}) async { 80 | return nullIfNotFound( 81 | (RequestConfig requestConfig) async { 82 | var response = await _tbClient.get>( 83 | '/api/entities/vc/info/$versionId/${externalEntityId.entityType.toShortString()}/${externalEntityId.id}', 84 | options: defaultHttpOptionsFromConfig(requestConfig)); 85 | return response.data != null 86 | ? EntityDataInfo.fromJson(response.data!) 87 | : null; 88 | }, 89 | requestConfig: requestConfig, 90 | ); 91 | } 92 | 93 | Future compareEntityDataToVersion( 94 | EntityId entityId, String versionId, 95 | {RequestConfig? requestConfig}) async { 96 | return nullIfNotFound( 97 | (RequestConfig requestConfig) async { 98 | var response = await _tbClient.get>( 99 | '/api/entities/vc/diff/${entityId.entityType.toShortString()}/${entityId.id}', 100 | queryParameters: {'versionId': versionId}, 101 | options: defaultHttpOptionsFromConfig(requestConfig)); 102 | return response.data != null 103 | ? EntityDataDiff.fromJson(response.data!) 104 | : null; 105 | }, 106 | requestConfig: requestConfig, 107 | ); 108 | } 109 | 110 | Future loadEntitiesVersion(VersionLoadRequest request, 111 | {RequestConfig? requestConfig}) async { 112 | var response = await _tbClient.post('/api/entities/vc/entity', 113 | data: jsonEncode(request), 114 | options: defaultHttpOptionsFromConfig(requestConfig)); 115 | return response.data!; 116 | } 117 | 118 | Future getVersionLoadRequestStatus(String requestId, 119 | {RequestConfig? requestConfig}) async { 120 | return nullIfNotFound( 121 | (RequestConfig requestConfig) async { 122 | var response = await _tbClient.get>( 123 | '/api/entities/vc/entity/$requestId/status', 124 | options: defaultHttpOptionsFromConfig(requestConfig)); 125 | return response.data != null 126 | ? VersionLoadResult.fromJson(response.data!) 127 | : null; 128 | }, 129 | requestConfig: requestConfig, 130 | ); 131 | } 132 | 133 | Future> listBranches({RequestConfig? requestConfig}) async { 134 | var response = await _tbClient.get>( 135 | '/api/entities/vc/branches', 136 | options: defaultHttpOptionsFromConfig(requestConfig)); 137 | return response.data!.map((e) => BranchInfo.fromJson(e)).toList(); 138 | } 139 | } 140 | -------------------------------------------------------------------------------- /lib/src/service/entity_query_service.dart: -------------------------------------------------------------------------------- 1 | import 'dart:convert'; 2 | 3 | import '../http/http_utils.dart'; 4 | import '../model/page/page_data.dart'; 5 | import '../model/query/query_models.dart'; 6 | 7 | import '../thingsboard_client_base.dart'; 8 | 9 | PageData parseEntityDataPageData(Map json) { 10 | return PageData.fromJson(json, (json) => EntityData.fromJson(json)); 11 | } 12 | 13 | PageData parseAlarmDataPageData(Map json) { 14 | return PageData.fromJson(json, (json) => AlarmData.fromJson(json)); 15 | } 16 | 17 | class EntityQueryService { 18 | final ThingsboardClient _tbClient; 19 | 20 | factory EntityQueryService(ThingsboardClient tbClient) { 21 | return EntityQueryService._internal(tbClient); 22 | } 23 | 24 | EntityQueryService._internal(this._tbClient); 25 | 26 | Future countEntitiesByQuery(EntityCountQuery query, 27 | {RequestConfig? requestConfig}) async { 28 | var response = await _tbClient.post('/api/entitiesQuery/count', 29 | data: jsonEncode(query), 30 | options: defaultHttpOptionsFromConfig(requestConfig)); 31 | return response.data!; 32 | } 33 | 34 | Future> findEntityDataByQuery(EntityDataQuery query, 35 | {RequestConfig? requestConfig}) async { 36 | var response = await _tbClient.post>( 37 | '/api/entitiesQuery/find', 38 | data: jsonEncode(query), 39 | options: defaultHttpOptionsFromConfig(requestConfig)); 40 | return _tbClient.compute(parseEntityDataPageData, response.data!); 41 | } 42 | 43 | Future> findAlarmDataByQuery(AlarmDataQuery query, 44 | {RequestConfig? requestConfig}) async { 45 | var response = await _tbClient.post>( 46 | '/api/alarmsQuery/find', 47 | data: jsonEncode(query), 48 | options: defaultHttpOptionsFromConfig(requestConfig)); 49 | return _tbClient.compute(parseAlarmDataPageData, response.data!); 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /lib/src/service/event_service.dart: -------------------------------------------------------------------------------- 1 | import '../thingsboard_client_base.dart'; 2 | import '../http/http_utils.dart'; 3 | import '../model/model.dart'; 4 | 5 | PageData parseEventPageData(Map json) { 6 | return PageData.fromJson(json, (json) => Event.fromJson(json)); 7 | } 8 | 9 | class EventService { 10 | final ThingsboardClient _tbClient; 11 | 12 | factory EventService(ThingsboardClient tbClient) { 13 | return EventService._internal(tbClient); 14 | } 15 | 16 | EventService._internal(this._tbClient); 17 | 18 | Future> getEvents( 19 | EntityId entityId, String tenantId, TimePageLink pageLink, 20 | {String? eventType, RequestConfig? requestConfig}) async { 21 | var url = 22 | '/api/events/${entityId.entityType.toShortString()}/${entityId.id}'; 23 | if (eventType != null) { 24 | url += '/$eventType'; 25 | } 26 | var queryParams = pageLink.toQueryParameters(); 27 | queryParams['tenantId'] = tenantId; 28 | var response = await _tbClient.get>(url, 29 | queryParameters: queryParams, 30 | options: defaultHttpOptionsFromConfig(requestConfig)); 31 | return _tbClient.compute(parseEventPageData, response.data!); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /lib/src/service/mobile_service.dart: -------------------------------------------------------------------------------- 1 | import 'package:thingsboard_client/thingsboard_client.dart'; 2 | 3 | class MobileService { 4 | MobileService._internal(this._tbClient); 5 | 6 | factory MobileService(ThingsboardClient tbClient) => 7 | MobileService._internal(tbClient); 8 | 9 | final ThingsboardClient _tbClient; 10 | 11 | Future getUserMobileInfo( 12 | MobileInfoQuery query, { 13 | RequestConfig? requestConfig, 14 | }) async { 15 | final queryParams = query.toQueryParameters(); 16 | final response = await _tbClient.get>( 17 | '/api/mobile', 18 | queryParameters: queryParams, 19 | options: defaultHttpOptionsFromConfig(requestConfig), 20 | ); 21 | 22 | return response.data != null 23 | ? MobileBasicInfo.fromJson(response.data!) 24 | : null; 25 | } 26 | 27 | Future getLoginMobileInfo( 28 | MobileInfoQuery query, { 29 | RequestConfig? requestConfig, 30 | }) async { 31 | final queryParams = query.toQueryParameters(); 32 | final response = await _tbClient.get>( 33 | '/api/noauth/mobile', 34 | queryParameters: queryParams, 35 | options: defaultHttpOptionsFromConfig(requestConfig), 36 | ); 37 | 38 | return response.data != null 39 | ? LoginMobileInfo.fromJson(response.data!) 40 | : null; 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /lib/src/service/notifications_service.dart: -------------------------------------------------------------------------------- 1 | import 'package:thingsboard_client/thingsboard_client.dart'; 2 | 3 | PageData parseNotificationPageData( 4 | Map json) { 5 | return PageData.fromJson(json, (json) => PushNotification.fromJson(json)); 6 | } 7 | 8 | class NotificationsService { 9 | const NotificationsService._internal(this._tbClient); 10 | 11 | factory NotificationsService(ThingsboardClient tbClient) { 12 | return NotificationsService._internal(tbClient); 13 | } 14 | 15 | final ThingsboardClient _tbClient; 16 | 17 | Future> getNotifications( 18 | PushNotificationQuery query, { 19 | RequestConfig? requestConfig, 20 | }) async { 21 | final queryParams = query.toQueryParameters(); 22 | final response = await _tbClient.get>( 23 | '/api/notifications', 24 | queryParameters: queryParams, 25 | options: defaultHttpOptionsFromConfig(requestConfig), 26 | ); 27 | 28 | return _tbClient.compute(parseNotificationPageData, response.data!); 29 | } 30 | 31 | Future markAllNotificationsAsRead( 32 | String deliveryMethod, { 33 | RequestConfig? requestConfig, 34 | }) async { 35 | final response = await _tbClient.put>( 36 | '/api/notifications/read', 37 | queryParameters: {'deliveryMethod': deliveryMethod}, 38 | options: defaultHttpOptionsFromConfig(requestConfig), 39 | ); 40 | 41 | return response.statusCode!; 42 | } 43 | 44 | Future deleteNotification( 45 | String id, { 46 | RequestConfig? requestConfig, 47 | }) async { 48 | final response = await _tbClient.delete( 49 | '/api/notification/$id', 50 | options: defaultHttpOptionsFromConfig(requestConfig), 51 | ); 52 | 53 | return response.statusCode!; 54 | } 55 | 56 | Future markNotificationAsRead( 57 | String id, { 58 | RequestConfig? requestConfig, 59 | }) async { 60 | final response = await _tbClient.put( 61 | '/api/notification/$id/read', 62 | options: defaultHttpOptionsFromConfig(requestConfig), 63 | ); 64 | 65 | return response.statusCode!; 66 | } 67 | 68 | Future getUnreadNotificationsCount( 69 | String deliveryMethod, { 70 | RequestConfig? requestConfig, 71 | }) async { 72 | final response = await _tbClient.get( 73 | '/api/notifications/unread/count', 74 | queryParameters: {'deliveryMethod': deliveryMethod}, 75 | options: defaultHttpOptionsFromConfig(requestConfig), 76 | ); 77 | 78 | return response.data!; 79 | } 80 | 81 | Future getNotificationById( 82 | String id, { 83 | required String deliveryMethod, 84 | RequestConfig? requestConfig, 85 | }) async { 86 | final response = await _tbClient.get>( 87 | 'api/notification/request/$id', 88 | queryParameters: {'deliveryMethod': deliveryMethod}, 89 | options: defaultHttpOptionsFromConfig(requestConfig), 90 | ); 91 | 92 | return PushNotification.fromJson(response.data!); 93 | } 94 | } 95 | -------------------------------------------------------------------------------- /lib/src/service/oauth2_service.dart: -------------------------------------------------------------------------------- 1 | import 'dart:convert'; 2 | 3 | import 'package:dio/dio.dart'; 4 | import 'package:thingsboard_client/src/error/thingsboard_error.dart'; 5 | 6 | import '../http/http_utils.dart'; 7 | import '../model/model.dart'; 8 | import '../thingsboard_client_base.dart'; 9 | 10 | List parseOauth2ClientRegistrationTemplates( 11 | List json) { 12 | return json.map((e) => OAuth2ClientRegistrationTemplate.fromJson(e)).toList(); 13 | } 14 | 15 | class OAuth2Service { 16 | final ThingsboardClient _tbClient; 17 | 18 | factory OAuth2Service(ThingsboardClient tbClient) { 19 | return OAuth2Service._internal(tbClient); 20 | } 21 | 22 | OAuth2Service._internal(this._tbClient); 23 | 24 | Future> getOAuth2Clients( 25 | {String? pkgName, 26 | PlatformType? platform, 27 | RequestConfig? requestConfig}) async { 28 | var queryParams = {}; 29 | if (pkgName != null) { 30 | queryParams['pkgName'] = pkgName; 31 | } 32 | if (platform != null) { 33 | queryParams['platform'] = platform.toShortString(); 34 | } 35 | 36 | Response> response; 37 | try { 38 | response = await _tbClient.post>( 39 | '/api/noauth/oauth2Clients', 40 | queryParameters: queryParams, 41 | options: defaultHttpOptionsFromConfig(requestConfig)); 42 | } on ThingsboardError catch (e) { 43 | if (e.status == 302) { 44 | final redirectUrl = e.error.response.headers['location'].first; 45 | response = await _tbClient.post(redirectUrl); 46 | } else { 47 | rethrow; 48 | } 49 | } 50 | 51 | return response.data!.map((e) => OAuth2ClientInfo.fromJson(e)).toList(); 52 | } 53 | 54 | Future saveClientRegistrationTemplate( 55 | OAuth2ClientRegistrationTemplate clientRegistrationTemplate, 56 | {RequestConfig? requestConfig}) async { 57 | var response = await _tbClient.post>( 58 | '/api/oauth2/config/template', 59 | data: jsonEncode(clientRegistrationTemplate), 60 | options: defaultHttpOptionsFromConfig(requestConfig)); 61 | return OAuth2ClientRegistrationTemplate.fromJson(response.data!); 62 | } 63 | 64 | Future deleteClientRegistrationTemplate( 65 | String oAuth2ClientRegistrationTemplateId, 66 | {RequestConfig? requestConfig}) async { 67 | await _tbClient.delete( 68 | '/api/oauth2/config/template/$oAuth2ClientRegistrationTemplateId', 69 | options: defaultHttpOptionsFromConfig(requestConfig)); 70 | } 71 | 72 | Future> getClientRegistrationTemplates( 73 | {RequestConfig? requestConfig}) async { 74 | var response = await _tbClient.get>( 75 | '/api/oauth2/config/template', 76 | options: defaultHttpOptionsFromConfig(requestConfig)); 77 | return _tbClient.compute( 78 | parseOauth2ClientRegistrationTemplates, response.data!); 79 | } 80 | 81 | Future getCurrentOAuth2Info( 82 | {RequestConfig? requestConfig}) async { 83 | var response = await _tbClient.get>( 84 | '/api/oauth2/config', 85 | options: defaultHttpOptionsFromConfig(requestConfig)); 86 | return OAuth2Info.fromJson(response.data!); 87 | } 88 | 89 | Future saveOAuth2Info(OAuth2Info oAuth2Info, 90 | {RequestConfig? requestConfig}) async { 91 | var response = await _tbClient.post>( 92 | '/api/oauth2/config', 93 | data: jsonEncode(oAuth2Info), 94 | options: defaultHttpOptionsFromConfig(requestConfig)); 95 | return OAuth2Info.fromJson(response.data!); 96 | } 97 | 98 | Future getLoginProcessingUrl({RequestConfig? requestConfig}) async { 99 | var options = defaultHttpOptionsFromConfig(requestConfig); 100 | options.responseType = ResponseType.plain; 101 | var response = await _tbClient.get('/api/oauth2/loginProcessingUrl', 102 | options: options); 103 | return response.data!; 104 | } 105 | } 106 | -------------------------------------------------------------------------------- /lib/src/service/ota_package_service.dart: -------------------------------------------------------------------------------- 1 | import 'dart:convert'; 2 | 3 | import 'package:dio/dio.dart'; 4 | 5 | import '../thingsboard_client_base.dart'; 6 | import '../http/http_utils.dart'; 7 | import '../model/model.dart'; 8 | 9 | PageData parseOtaPackageInfoPageData( 10 | Map json) { 11 | return PageData.fromJson(json, (json) => OtaPackageInfo.fromJson(json)); 12 | } 13 | 14 | class OtaPackageService { 15 | final ThingsboardClient _tbClient; 16 | 17 | factory OtaPackageService(ThingsboardClient tbClient) { 18 | return OtaPackageService._internal(tbClient); 19 | } 20 | 21 | OtaPackageService._internal(this._tbClient); 22 | 23 | Future downloadOtaPackage(String otaPackageId, 24 | {RequestConfig? requestConfig}) async { 25 | return nullIfNotFound( 26 | (RequestConfig requestConfig) async { 27 | var options = defaultHttpOptionsFromConfig(requestConfig); 28 | options.responseType = ResponseType.stream; 29 | var response = await _tbClient.get( 30 | '/api/otaPackage/$otaPackageId/download', 31 | options: options); 32 | return response.data; 33 | }, 34 | requestConfig: requestConfig, 35 | ); 36 | } 37 | 38 | Future getOtaPackage(String otaPackageId, 39 | {RequestConfig? requestConfig}) async { 40 | return nullIfNotFound( 41 | (RequestConfig requestConfig) async { 42 | var response = await _tbClient.get>( 43 | '/api/otaPackage/$otaPackageId', 44 | options: defaultHttpOptionsFromConfig(requestConfig)); 45 | return response.data != null 46 | ? OtaPackage.fromJson(response.data!) 47 | : null; 48 | }, 49 | requestConfig: requestConfig, 50 | ); 51 | } 52 | 53 | Future getOtaPackageInfo(String otaPackageId, 54 | {RequestConfig? requestConfig}) async { 55 | return nullIfNotFound( 56 | (RequestConfig requestConfig) async { 57 | var response = await _tbClient.get>( 58 | '/api/otaPackage/info/$otaPackageId', 59 | options: defaultHttpOptionsFromConfig(requestConfig)); 60 | return response.data != null 61 | ? OtaPackageInfo.fromJson(response.data!) 62 | : null; 63 | }, 64 | requestConfig: requestConfig, 65 | ); 66 | } 67 | 68 | Future saveOtaPackageInfo(OtaPackageInfo otaPackageInfo, 69 | {RequestConfig? requestConfig}) async { 70 | var response = await _tbClient.post>('/api/otaPackage', 71 | data: jsonEncode(otaPackageInfo), 72 | options: defaultHttpOptionsFromConfig(requestConfig)); 73 | return OtaPackageInfo.fromJson(response.data!); 74 | } 75 | 76 | Future saveOtaPackageData( 77 | String otaPackageId, MultipartFile file, 78 | {required ChecksumAlgorithm checksumAlgorithm, 79 | String? checksum, 80 | RequestConfig? requestConfig}) async { 81 | var formData = FormData.fromMap({'file': file}); 82 | var response = await _tbClient.post>( 83 | '/api/otaPackage/$otaPackageId', 84 | queryParameters: { 85 | 'checksumAlgorithm': checksumAlgorithm.toShortString(), 86 | 'checksum': checksum 87 | }, 88 | data: formData, 89 | options: defaultHttpOptionsFromConfig(requestConfig)); 90 | return OtaPackageInfo.fromJson(response.data!); 91 | } 92 | 93 | Future deleteOtaPackage(String otaPackageId, 94 | {RequestConfig? requestConfig}) async { 95 | await _tbClient.delete('/api/otaPackage/$otaPackageId', 96 | options: defaultHttpOptionsFromConfig(requestConfig)); 97 | } 98 | 99 | Future> getOtaPackages(PageLink pageLink, 100 | {RequestConfig? requestConfig}) async { 101 | var response = await _tbClient.get>('/api/otaPackages', 102 | queryParameters: pageLink.toQueryParameters(), 103 | options: defaultHttpOptionsFromConfig(requestConfig)); 104 | return _tbClient.compute(parseOtaPackageInfoPageData, response.data!); 105 | } 106 | 107 | Future> getOtaPackagesByDeviceProfileId( 108 | String deviceProfileId, OtaPackageType type, PageLink pageLink, 109 | {RequestConfig? requestConfig}) async { 110 | var response = await _tbClient.get>( 111 | '/api/otaPackages/$deviceProfileId/${type.toShortString()}', 112 | queryParameters: pageLink.toQueryParameters(), 113 | options: defaultHttpOptionsFromConfig(requestConfig)); 114 | return _tbClient.compute(parseOtaPackageInfoPageData, response.data!); 115 | } 116 | } 117 | -------------------------------------------------------------------------------- /lib/src/service/queue_service.dart: -------------------------------------------------------------------------------- 1 | import 'dart:convert'; 2 | 3 | import '../thingsboard_client_base.dart'; 4 | import '../http/http_utils.dart'; 5 | import '../model/model.dart'; 6 | 7 | PageData parseQueuePageData(Map json) { 8 | return PageData.fromJson(json, (json) => Queue.fromJson(json)); 9 | } 10 | 11 | class QueueService { 12 | final ThingsboardClient _tbClient; 13 | 14 | factory QueueService(ThingsboardClient tbClient) { 15 | return QueueService._internal(tbClient); 16 | } 17 | 18 | QueueService._internal(this._tbClient); 19 | 20 | Future getQueue(String queueId, 21 | {RequestConfig? requestConfig}) async { 22 | return nullIfNotFound( 23 | (RequestConfig requestConfig) async { 24 | var response = await _tbClient.get>( 25 | '/api/queues/$queueId', 26 | options: defaultHttpOptionsFromConfig(requestConfig)); 27 | return response.data != null ? Queue.fromJson(response.data!) : null; 28 | }, 29 | requestConfig: requestConfig, 30 | ); 31 | } 32 | 33 | Future getQueueByName(String queueName, 34 | {RequestConfig? requestConfig}) async { 35 | return nullIfNotFound( 36 | (RequestConfig requestConfig) async { 37 | var response = await _tbClient.get>( 38 | '/api/queues/name/$queueName', 39 | options: defaultHttpOptionsFromConfig(requestConfig)); 40 | return response.data != null ? Queue.fromJson(response.data!) : null; 41 | }, 42 | requestConfig: requestConfig, 43 | ); 44 | } 45 | 46 | Future saveQueue(Queue queue, ServiceType serviceType, 47 | {RequestConfig? requestConfig}) async { 48 | var queryParams = { 49 | 'serviceType': serviceType.toShortString() 50 | }; 51 | var response = await _tbClient.post>('/api/queues', 52 | queryParameters: queryParams, 53 | data: jsonEncode(queue), 54 | options: defaultHttpOptionsFromConfig(requestConfig)); 55 | return Queue.fromJson(response.data!); 56 | } 57 | 58 | Future deleteQueue(String queueId, 59 | {RequestConfig? requestConfig}) async { 60 | await _tbClient.delete('/api/queues/$queueId', 61 | options: defaultHttpOptionsFromConfig(requestConfig)); 62 | } 63 | 64 | Future> getTenantQueuesByServiceType( 65 | PageLink pageLink, ServiceType serviceType, 66 | {RequestConfig? requestConfig}) async { 67 | var queryParams = pageLink.toQueryParameters(); 68 | queryParams['serviceType'] = serviceType.toShortString(); 69 | var response = await _tbClient.get>('/api/queues', 70 | queryParameters: queryParams, 71 | options: defaultHttpOptionsFromConfig(requestConfig)); 72 | return _tbClient.compute(parseQueuePageData, response.data!); 73 | } 74 | } 75 | -------------------------------------------------------------------------------- /lib/src/service/resource_service.dart: -------------------------------------------------------------------------------- 1 | import 'dart:convert'; 2 | 3 | import 'package:dio/dio.dart'; 4 | 5 | import '../thingsboard_client_base.dart'; 6 | import '../http/http_utils.dart'; 7 | import '../model/model.dart'; 8 | 9 | PageData parseResourceInfoPageData(Map json) { 10 | return PageData.fromJson(json, (json) => TbResourceInfo.fromJson(json)); 11 | } 12 | 13 | class ResourceService { 14 | final ThingsboardClient _tbClient; 15 | 16 | factory ResourceService(ThingsboardClient tbClient) { 17 | return ResourceService._internal(tbClient); 18 | } 19 | 20 | ResourceService._internal(this._tbClient); 21 | 22 | Future downloadResource(String resourceId, 23 | {RequestConfig? requestConfig}) async { 24 | return nullIfNotFound( 25 | (RequestConfig requestConfig) async { 26 | var options = defaultHttpOptionsFromConfig(requestConfig); 27 | options.responseType = ResponseType.stream; 28 | var response = await _tbClient.get( 29 | '/api/resource/$resourceId/download', 30 | options: options); 31 | return response.data; 32 | }, 33 | requestConfig: requestConfig, 34 | ); 35 | } 36 | 37 | Future getResource(String resourceId, 38 | {RequestConfig? requestConfig}) async { 39 | return nullIfNotFound( 40 | (RequestConfig requestConfig) async { 41 | var response = await _tbClient.get>( 42 | '/api/resource/$resourceId', 43 | options: defaultHttpOptionsFromConfig(requestConfig)); 44 | return response.data != null 45 | ? TbResource.fromJson(response.data!) 46 | : null; 47 | }, 48 | requestConfig: requestConfig, 49 | ); 50 | } 51 | 52 | Future getResourceInfo(String resourceId, 53 | {RequestConfig? requestConfig}) async { 54 | return nullIfNotFound( 55 | (RequestConfig requestConfig) async { 56 | var response = await _tbClient.get>( 57 | '/api/resource/info/$resourceId', 58 | options: defaultHttpOptionsFromConfig(requestConfig)); 59 | return response.data != null 60 | ? TbResourceInfo.fromJson(response.data!) 61 | : null; 62 | }, 63 | requestConfig: requestConfig, 64 | ); 65 | } 66 | 67 | Future saveResource(TbResource resource, 68 | {RequestConfig? requestConfig}) async { 69 | var response = await _tbClient.post>('/api/resource', 70 | data: jsonEncode(resource), 71 | options: defaultHttpOptionsFromConfig(requestConfig)); 72 | return TbResource.fromJson(response.data!); 73 | } 74 | 75 | Future deleteResource(String resourceId, 76 | {RequestConfig? requestConfig}) async { 77 | await _tbClient.delete('/api/resource/$resourceId', 78 | options: defaultHttpOptionsFromConfig(requestConfig)); 79 | } 80 | 81 | Future> getResources(PageLink pageLink, 82 | {RequestConfig? requestConfig}) async { 83 | var response = await _tbClient.get>('/api/resource', 84 | queryParameters: pageLink.toQueryParameters(), 85 | options: defaultHttpOptionsFromConfig(requestConfig)); 86 | return _tbClient.compute(parseResourceInfoPageData, response.data!); 87 | } 88 | } 89 | -------------------------------------------------------------------------------- /lib/src/service/service.dart: -------------------------------------------------------------------------------- 1 | export 'admin_service.dart'; 2 | export 'alarm_service.dart'; 3 | export 'asset_profile_service.dart'; 4 | export 'asset_service.dart'; 5 | export 'attribute_service.dart'; 6 | export 'audit_log_service.dart'; 7 | export 'component_descriptor_service.dart'; 8 | export 'customer_service.dart'; 9 | export 'dashboard_service.dart'; 10 | export 'device_profile_service.dart'; 11 | export 'device_service.dart'; 12 | export 'edge_service.dart'; 13 | export 'entities_version_control_service.dart'; 14 | export 'entity_query_service.dart'; 15 | export 'entity_relation_service.dart'; 16 | export 'entity_view_service.dart'; 17 | export 'notifications_service.dart'; 18 | export 'oauth2_service.dart'; 19 | export 'ota_package_service.dart'; 20 | export 'queue_service.dart'; 21 | export 'resource_service.dart'; 22 | export 'rule_chain_service.dart'; 23 | export 'telemetry_websocket_service.dart'; 24 | export 'tenant_profile_service.dart'; 25 | export 'tenant_service.dart'; 26 | export 'two_factor_auth_service.dart'; 27 | export 'user_service.dart'; 28 | export 'widget_service.dart'; 29 | -------------------------------------------------------------------------------- /lib/src/service/tenant_profile_service.dart: -------------------------------------------------------------------------------- 1 | import 'dart:convert'; 2 | 3 | import '../http/http_utils.dart'; 4 | import '../model/entity_models.dart'; 5 | import '../model/page/page_data.dart'; 6 | import '../model/page/page_link.dart'; 7 | import '../model/tenant_models.dart'; 8 | import '../thingsboard_client_base.dart'; 9 | 10 | PageData parseTenantProfilePageData(Map json) { 11 | return PageData.fromJson(json, (json) => TenantProfile.fromJson(json)); 12 | } 13 | 14 | PageData parseTenantProfileInfoPageData(Map json) { 15 | return PageData.fromJson(json, (json) => EntityInfo.fromJson(json)); 16 | } 17 | 18 | class TenantProfileService { 19 | final ThingsboardClient _tbClient; 20 | 21 | factory TenantProfileService(ThingsboardClient tbClient) { 22 | return TenantProfileService._internal(tbClient); 23 | } 24 | 25 | TenantProfileService._internal(this._tbClient); 26 | 27 | Future getTenantProfile(String tenantProfileId, 28 | {RequestConfig? requestConfig}) async { 29 | return nullIfNotFound( 30 | (RequestConfig requestConfig) async { 31 | var response = await _tbClient.get>( 32 | '/api/tenantProfile/$tenantProfileId', 33 | options: defaultHttpOptionsFromConfig(requestConfig)); 34 | return response.data != null 35 | ? TenantProfile.fromJson(response.data!) 36 | : null; 37 | }, 38 | requestConfig: requestConfig, 39 | ); 40 | } 41 | 42 | Future getTenantProfileInfo(String tenantProfileId, 43 | {RequestConfig? requestConfig}) async { 44 | return nullIfNotFound( 45 | (RequestConfig requestConfig) async { 46 | var response = await _tbClient.get>( 47 | '/api/tenantProfileInfo/$tenantProfileId', 48 | options: defaultHttpOptionsFromConfig(requestConfig)); 49 | return response.data != null 50 | ? EntityInfo.fromJson(response.data!) 51 | : null; 52 | }, 53 | requestConfig: requestConfig, 54 | ); 55 | } 56 | 57 | Future getDefaultTenantProfileInfo( 58 | {RequestConfig? requestConfig}) async { 59 | var response = await _tbClient.get>( 60 | '/api/tenantProfileInfo/default', 61 | options: defaultHttpOptionsFromConfig(requestConfig)); 62 | return EntityInfo.fromJson(response.data!); 63 | } 64 | 65 | Future saveTenantProfile(TenantProfile tenantProfile, 66 | {RequestConfig? requestConfig}) async { 67 | var response = await _tbClient.post>( 68 | '/api/tenantProfile', 69 | data: jsonEncode(tenantProfile), 70 | options: defaultHttpOptionsFromConfig(requestConfig)); 71 | return TenantProfile.fromJson(response.data!); 72 | } 73 | 74 | Future deleteTenantProfile(String tenantProfileId, 75 | {RequestConfig? requestConfig}) async { 76 | await _tbClient.delete('/api/tenantProfile/$tenantProfileId', 77 | options: defaultHttpOptionsFromConfig(requestConfig)); 78 | } 79 | 80 | Future setDefaultTenantProfile(String tenantProfileId, 81 | {RequestConfig? requestConfig}) async { 82 | var response = await _tbClient.post>( 83 | '/api/tenantProfile/$tenantProfileId/default', 84 | options: defaultHttpOptionsFromConfig(requestConfig)); 85 | return TenantProfile.fromJson(response.data!); 86 | } 87 | 88 | Future> getTenantProfiles(PageLink pageLink, 89 | {RequestConfig? requestConfig}) async { 90 | var response = await _tbClient.get>( 91 | '/api/tenantProfiles', 92 | queryParameters: pageLink.toQueryParameters(), 93 | options: defaultHttpOptionsFromConfig(requestConfig)); 94 | return _tbClient.compute(parseTenantProfilePageData, response.data!); 95 | } 96 | 97 | Future> getTenantProfileInfos(PageLink pageLink, 98 | {RequestConfig? requestConfig}) async { 99 | var response = await _tbClient.get>( 100 | '/api/tenantProfileInfos', 101 | queryParameters: pageLink.toQueryParameters(), 102 | options: defaultHttpOptionsFromConfig(requestConfig)); 103 | return _tbClient.compute(parseTenantProfileInfoPageData, response.data!); 104 | } 105 | } 106 | -------------------------------------------------------------------------------- /lib/src/service/tenant_service.dart: -------------------------------------------------------------------------------- 1 | import 'dart:convert'; 2 | 3 | import '../thingsboard_client_base.dart'; 4 | import '../http/http_utils.dart'; 5 | import '../model/model.dart'; 6 | 7 | PageData parseTenantPageData(Map json) { 8 | return PageData.fromJson(json, (json) => Tenant.fromJson(json)); 9 | } 10 | 11 | PageData parseTenantInfoPageData(Map json) { 12 | return PageData.fromJson(json, (json) => TenantInfo.fromJson(json)); 13 | } 14 | 15 | class TenantService { 16 | final ThingsboardClient _tbClient; 17 | 18 | factory TenantService(ThingsboardClient tbClient) { 19 | return TenantService._internal(tbClient); 20 | } 21 | 22 | TenantService._internal(this._tbClient); 23 | 24 | Future getTenant(String tenantId, 25 | {RequestConfig? requestConfig}) async { 26 | return nullIfNotFound( 27 | (RequestConfig requestConfig) async { 28 | var response = await _tbClient.get>( 29 | '/api/tenant/$tenantId', 30 | options: defaultHttpOptionsFromConfig(requestConfig)); 31 | return response.data != null ? Tenant.fromJson(response.data!) : null; 32 | }, 33 | requestConfig: requestConfig, 34 | ); 35 | } 36 | 37 | Future getTenantInfo(String tenantId, 38 | {RequestConfig? requestConfig}) async { 39 | return nullIfNotFound( 40 | (RequestConfig requestConfig) async { 41 | var response = await _tbClient.get>( 42 | '/api/tenant/info/$tenantId', 43 | options: defaultHttpOptionsFromConfig(requestConfig)); 44 | return response.data != null 45 | ? TenantInfo.fromJson(response.data!) 46 | : null; 47 | }, 48 | requestConfig: requestConfig, 49 | ); 50 | } 51 | 52 | Future saveTenant(Tenant tenant, 53 | {RequestConfig? requestConfig}) async { 54 | var response = await _tbClient.post>('/api/tenant', 55 | data: jsonEncode(tenant), 56 | options: defaultHttpOptionsFromConfig(requestConfig)); 57 | return Tenant.fromJson(response.data!); 58 | } 59 | 60 | Future deleteTenant(String tenantId, 61 | {RequestConfig? requestConfig}) async { 62 | await _tbClient.delete('/api/tenant/$tenantId', 63 | options: defaultHttpOptionsFromConfig(requestConfig)); 64 | } 65 | 66 | Future> getTenants(PageLink pageLink, 67 | {RequestConfig? requestConfig}) async { 68 | var queryParams = pageLink.toQueryParameters(); 69 | var response = await _tbClient.get>('/api/tenants', 70 | queryParameters: queryParams, 71 | options: defaultHttpOptionsFromConfig(requestConfig)); 72 | return _tbClient.compute(parseTenantPageData, response.data!); 73 | } 74 | 75 | Future> getTenantInfos(PageLink pageLink, 76 | {RequestConfig? requestConfig}) async { 77 | var queryParams = pageLink.toQueryParameters(); 78 | var response = await _tbClient.get>('/api/tenantInfos', 79 | queryParameters: queryParams, 80 | options: defaultHttpOptionsFromConfig(requestConfig)); 81 | return _tbClient.compute(parseTenantInfoPageData, response.data!); 82 | } 83 | } 84 | -------------------------------------------------------------------------------- /lib/src/service/two_factor_auth_service.dart: -------------------------------------------------------------------------------- 1 | import 'dart:convert'; 2 | import '../thingsboard_client_base.dart'; 3 | import '../model/model.dart'; 4 | import '../http/http_utils.dart'; 5 | 6 | class TwoFactorAuthService { 7 | final ThingsboardClient _tbClient; 8 | 9 | factory TwoFactorAuthService(ThingsboardClient tbClient) { 10 | return TwoFactorAuthService._internal(tbClient); 11 | } 12 | 13 | TwoFactorAuthService._internal(this._tbClient); 14 | 15 | Future getPlatformTwoFaSettings( 16 | {RequestConfig? requestConfig}) async { 17 | return nullIfNotFound( 18 | (RequestConfig requestConfig) async { 19 | var response = await _tbClient.get('/api/2fa/settings', 20 | options: defaultHttpOptionsFromConfig(requestConfig)); 21 | return response.data != null && response.data != "" 22 | ? PlatformTwoFaSettings.fromJson(response.data!) 23 | : null; 24 | }, 25 | requestConfig: requestConfig, 26 | ); 27 | } 28 | 29 | Future savePlatformTwoFaSettings( 30 | PlatformTwoFaSettings platformTwoFaSettings, 31 | {RequestConfig? requestConfig}) async { 32 | var response = await _tbClient.post>( 33 | '/api/2fa/settings', 34 | data: jsonEncode(platformTwoFaSettings), 35 | options: defaultHttpOptionsFromConfig(requestConfig)); 36 | return PlatformTwoFaSettings.fromJson(response.data!); 37 | } 38 | 39 | Future> getAvailableTwoFaProviders( 40 | {RequestConfig? requestConfig}) async { 41 | var response = await _tbClient.get>('/api/2fa/providers', 42 | options: defaultHttpOptionsFromConfig(requestConfig)); 43 | return response.data!.map((e) => twoFaProviderTypeFromString(e)).toList(); 44 | } 45 | 46 | Future> getAvailableLoginTwoFaProviders( 47 | {RequestConfig? requestConfig}) async { 48 | var response = await _tbClient.get>('/api/auth/2fa/providers', 49 | options: defaultHttpOptionsFromConfig(requestConfig)); 50 | return response.data!.map((e) => TwoFaProviderInfo.fromJson(e)).toList(); 51 | } 52 | 53 | Future generateTwoFaAccountConfig( 54 | TwoFaProviderType providerType, 55 | {RequestConfig? requestConfig}) async { 56 | var response = await _tbClient.post>( 57 | '/api/2fa/account/config/generate', 58 | queryParameters: {'providerType': providerType.toShortString()}, 59 | options: defaultHttpOptionsFromConfig(requestConfig)); 60 | return TwoFaAccountConfig.fromJson(response.data!); 61 | } 62 | 63 | Future getAccountTwoFaSettings( 64 | {RequestConfig? requestConfig}) async { 65 | return nullIfNotFound( 66 | (RequestConfig requestConfig) async { 67 | var response = await _tbClient.get('/api/2fa/account/settings', 68 | options: defaultHttpOptionsFromConfig(requestConfig)); 69 | return response.data != null && response.data != "" 70 | ? AccountTwoFaSettings.fromJson(response.data!) 71 | : null; 72 | }, 73 | requestConfig: requestConfig, 74 | ); 75 | } 76 | 77 | Future updateTwoFaAccountConfig( 78 | TwoFaProviderType providerType, bool useByDefault, 79 | {RequestConfig? requestConfig}) async { 80 | var response = await _tbClient.post>( 81 | '/api/2fa/account/config', 82 | queryParameters: {'providerType': providerType.toShortString()}, 83 | data: jsonEncode({'useByDefault': useByDefault}), 84 | options: defaultHttpOptionsFromConfig(requestConfig)); 85 | return AccountTwoFaSettings.fromJson(response.data!); 86 | } 87 | 88 | Future submitTwoFaAccountConfig(TwoFaAccountConfig accountConfig, 89 | {RequestConfig? requestConfig}) async { 90 | await _tbClient.post('/api/2fa/account/config/submit', 91 | data: jsonEncode(accountConfig), 92 | options: defaultHttpOptionsFromConfig(requestConfig)); 93 | } 94 | 95 | Future verifyAndSaveTwoFaAccountConfig( 96 | TwoFaAccountConfig accountConfig, 97 | {String? verificationCode, 98 | RequestConfig? requestConfig}) async { 99 | var queryParameters = {}; 100 | if (verificationCode != null) { 101 | queryParameters['verificationCode'] = verificationCode; 102 | } 103 | var response = await _tbClient.post>( 104 | '/api/2fa/account/config', 105 | queryParameters: queryParameters, 106 | data: jsonEncode(accountConfig), 107 | options: defaultHttpOptionsFromConfig(requestConfig)); 108 | return AccountTwoFaSettings.fromJson(response.data!); 109 | } 110 | 111 | Future deleteTwoFaAccountConfig( 112 | TwoFaProviderType providerType, 113 | {RequestConfig? requestConfig}) async { 114 | var response = await _tbClient.delete>( 115 | '/api/2fa/account/config', 116 | queryParameters: {'providerType': providerType.toShortString()}, 117 | options: defaultHttpOptionsFromConfig(requestConfig)); 118 | return AccountTwoFaSettings.fromJson(response.data!); 119 | } 120 | 121 | Future requestTwoFaVerificationCode(TwoFaProviderType providerType, 122 | {RequestConfig? requestConfig}) async { 123 | await _tbClient.post('/api/auth/2fa/verification/send', 124 | queryParameters: {'providerType': providerType.toShortString()}, 125 | options: defaultHttpOptionsFromConfig(requestConfig)); 126 | } 127 | } 128 | -------------------------------------------------------------------------------- /lib/src/storage/_local_file_storage.dart: -------------------------------------------------------------------------------- 1 | import 'tb_storage.dart'; 2 | 3 | TbStorage createLocalFileStorage(String fileName, [String? path]) => 4 | throw UnsupportedError(''); 5 | -------------------------------------------------------------------------------- /lib/src/storage/_local_file_storage_io.dart: -------------------------------------------------------------------------------- 1 | import 'dart:convert'; 2 | import 'dart:io'; 3 | import 'dart:typed_data'; 4 | 5 | import 'tb_storage.dart'; 6 | 7 | TbStorage createLocalFileStorage(String fileName, [String? path]) => 8 | LocalFileStorage(fileName, path); 9 | 10 | class LocalFileStorage implements TbStorage { 11 | late Future ready; 12 | 13 | LocalFileStorage(this.fileName, [this.path]) { 14 | ready = Future(() async { 15 | await _init(); 16 | return true; 17 | }); 18 | } 19 | 20 | final String? path; 21 | final String fileName; 22 | 23 | Map _data = {}; 24 | 25 | RandomAccessFile? _file; 26 | 27 | Future _init() async { 28 | _data = {}; 29 | 30 | final f = await _getFile(); 31 | final length = await f.length(); 32 | 33 | if (length == 0) { 34 | return _flush({}); 35 | } else { 36 | await _readFile(); 37 | } 38 | } 39 | 40 | @override 41 | Future deleteItem(String key) async { 42 | await ready; 43 | _data.remove(key); 44 | return _flush(); 45 | } 46 | 47 | @override 48 | Future getItem(String key, {dynamic defaultValue}) async { 49 | await ready; 50 | return _data[key]; 51 | } 52 | 53 | @override 54 | Future setItem(String key, dynamic value) async { 55 | await ready; 56 | _data[key] = value; 57 | return _flush(); 58 | } 59 | 60 | Future _flush([dynamic data]) async { 61 | final serialized = json.encode(data ?? _data); 62 | final buffer = utf8.encode(serialized); 63 | 64 | _file = await _file?.lock(); 65 | _file = await _file?.setPosition(0); 66 | _file = await _file?.writeFrom(buffer); 67 | _file = await _file?.truncate(buffer.length); 68 | await _file?.unlock(); 69 | } 70 | 71 | Future _readFile() async { 72 | var _file = await _getFile(); 73 | final length = await _file.length(); 74 | _file = await _file.setPosition(0); 75 | final buffer = Uint8List(length); 76 | await _file.readInto(buffer); 77 | final contentText = utf8.decode(buffer); 78 | 79 | _data = json.decode(contentText) as Map; 80 | } 81 | 82 | Future _getFile() async { 83 | if (_file != null) { 84 | return _file!; 85 | } 86 | 87 | final _path = path ?? _getDocumentDir().path; 88 | final file = File('$_path/$fileName'); 89 | 90 | if (await file.exists()) { 91 | _file = await file.open(mode: FileMode.append); 92 | } else { 93 | await file.create(); 94 | _file = await file.open(mode: FileMode.append); 95 | } 96 | 97 | return _file!; 98 | } 99 | 100 | Directory _getDocumentDir() { 101 | try { 102 | return Directory.current; 103 | } catch (err) { 104 | rethrow; 105 | } 106 | } 107 | 108 | @override 109 | Future containsKey(key) async { 110 | return _data.containsKey(key); 111 | } 112 | } 113 | -------------------------------------------------------------------------------- /lib/src/storage/in_memory_storage.dart: -------------------------------------------------------------------------------- 1 | import 'tb_storage.dart'; 2 | 3 | class InMemoryStorage implements TbStorage { 4 | final storageMap = {}; 5 | 6 | @override 7 | Future containsKey(String key) async { 8 | return storageMap.containsKey(key); 9 | } 10 | 11 | @override 12 | Future deleteItem(String key) async { 13 | storageMap.remove(key); 14 | } 15 | 16 | @override 17 | getItem(String key, {defaultValue}) async { 18 | return storageMap[key] ?? defaultValue; 19 | } 20 | 21 | @override 22 | Future setItem(String key, value) async { 23 | storageMap[key] = value; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /lib/src/storage/local_file_storage.dart: -------------------------------------------------------------------------------- 1 | export '_local_file_storage.dart' 2 | if (dart.library.io) '_local_file_storage_io.dart' 3 | if (dart.library.html) '_local_file_storage.dart'; 4 | -------------------------------------------------------------------------------- /lib/src/storage/storage.dart: -------------------------------------------------------------------------------- 1 | export 'tb_storage.dart'; 2 | export 'in_memory_storage.dart'; 3 | export 'local_file_storage.dart'; 4 | -------------------------------------------------------------------------------- /lib/src/storage/tb_storage.dart: -------------------------------------------------------------------------------- 1 | abstract class TbStorage { 2 | /// Saves the [key] - [value] pair. 3 | Future setItem(String key, E value); 4 | 5 | /// Deletes the given [key] from the storage. 6 | /// 7 | /// If it does not exist, nothing happens. 8 | Future deleteItem(String key); 9 | 10 | /// Returns the value associated with the given [key]. If the key does not 11 | /// exist, `null` is returned. 12 | /// 13 | /// If [defaultValue] is specified, it is returned in case the key does not 14 | /// exist. 15 | Future? getItem(String key, {E? defaultValue}); 16 | 17 | /// Checks whether the storage contains the [key]. 18 | Future containsKey(String key); 19 | } 20 | -------------------------------------------------------------------------------- /lib/thingsboard_client.dart: -------------------------------------------------------------------------------- 1 | /// Dart implementation of ThingsBoard API client. 2 | library thingsboard_client; 3 | 4 | export 'src/thingsboard_client_base.dart'; 5 | export 'src/model/model.dart'; 6 | export 'src/storage/storage.dart'; 7 | export 'src/http/http_utils.dart'; 8 | export 'src/error/thingsboard_error.dart'; 9 | export 'src/service/service.dart'; 10 | -------------------------------------------------------------------------------- /pubspec.yaml: -------------------------------------------------------------------------------- 1 | name: thingsboard_client 2 | description: Dart implementation of ThingsBoard API client. Provides model objects and services to communicate with ThingsBoard platform using RESTful APIs and WebSocket protocol. 3 | version: 4.0.0 4 | homepage: https://thingsboard.io 5 | repository: https://github.com/thingsboard/dart_thingsboard_client.git 6 | issue_tracker: https://github.com/thingsboard/dart_thingsboard_client/issues 7 | 8 | environment: 9 | sdk: '>=3.2.0 <4.0.0' 10 | 11 | dependencies: 12 | collection: ^1.18.0 13 | dio: ^5.3.4 14 | jwt_decoder: ^2.0.1 15 | web_socket_channel: ^2.4.0 16 | pretty_dio_logger: ^1.4.0 17 | 18 | dev_dependencies: 19 | lints: ^3.0.0 20 | pedantic: ^1.11.1 21 | test: ^1.24.9 22 | -------------------------------------------------------------------------------- /test/thingsboard_client_test.dart: -------------------------------------------------------------------------------- 1 | import 'package:thingsboard_client/thingsboard_client.dart'; 2 | import 'package:test/test.dart'; 3 | 4 | void main() { 5 | group('A group of tests', () { 6 | ThingsboardClient? tbClient; 7 | 8 | setUp(() async { 9 | tbClient = ThingsboardClient('http://localhost:8080'); 10 | await tbClient!.init(); 11 | }); 12 | 13 | test('First Test', () { 14 | expect(tbClient!.getDeviceService(), isNot(null)); 15 | }); 16 | }); 17 | } 18 | --------------------------------------------------------------------------------