thingsboard_client and mqtt_client connection and device data retrieving

42 Views Asked by At

I'm using flutter thingsboard_client: ^1.0.8 and mqtt_client: ^10.0.3 to get data of devices from thingsboard , so can I get the scopes and attributes value using mqtt_client? if not how to get the scopes and attributes value data of devices only by using thingsboard_client

this what I tried

import 'dart:async';

import 'package:evcs/Thingsboard/src/model/model.dart';
// import 'package:evcs/data/base_api_service.dart';
// import 'package:evcs/data/network/network_api_service.dart';
import 'package:mqtt_client/mqtt_client.dart';

import 'package:mqtt_client/mqtt_server_client.dart';

import 'package:evcs/models/charging_info_model.dart';
import 'package:evcs/utils/routes/route_name.dart';
import 'package:evcs/utils/util.dart';
import 'package:flutter/material.dart';
import 'package:evcs/Thingsboard/src/thingsboard_client_base.dart';

class LoginViewModal extends ChangeNotifier {
  TextEditingController userName = TextEditingController();
  List<Map<String, dynamic>> deviceId = [];
  TextEditingController pass = TextEditingController();
  List<dynamic> portData = [];
  List<ChargingInfo>? portInfos = [];

  List<String> portList = [
    '19388722-64fe-4f59-40cb-9ffc789ebad2',
    '1ab5d736-40a5-6f3a-9775-8ec1ed27f66d',
    '8e337fcc-b94c-7a3e-f248-0410208a7efe'
  ];

  var tbClient = ThingsboardClient('http://phyclouds.com:8080');

  validateLogin(BuildContext context) async {
    if (userName.text != '' || pass.text != '') {
      try {
        await tbClient
            .login(LoginRequest(userName.text, pass.text))
            .then((value) {
          Navigator.pushNamed(context, RouteName.home);
        }).onError((error, stackTrace) {
          Util.showAlert(context, 'error', 'Incorrect username or password',
              'Invalid credentials');
        });

        var currentUserDetails = await tbClient.getUserService().getUser();
        print('currentUserDetails: $currentUserDetails');
        var pageLink = PageLink(10);

        PageData<DeviceInfo> devicess;
        do {
          // Fetch tenant devices using current page link
          devicess =
              await tbClient.getDeviceService().getTenantDeviceInfos(pageLink);
          for (int i = 0; i < devicess.data.length; i++) {
            deviceId.add({
              'name': devicess.data[i].getName(),
              'id': devicess.data[i].deviceProfileId!.id
            });
          }

          // tbClient
          //     .getDeviceService()
          //     .( pageLink)
          //     .then((value) {
          //   print('getCustomerDeviceInfos ${value.data}');
          // });

          var dashboardId = await tbClient
              .getDashboardService()
              .getDashboard('3db0ee60-8854-11ee-ae74-db5ae19db63f');
          print(
              'ext id${dashboardId?.configuration['states']['port_a']['name']}');
          portInfos?.add(
            ChargingInfo(
              portName: dashboardId?.configuration['states']['port_a']['name'],
              chargingStatus: 'charging',
              voltage: 40,
              isActive: true,
              chargingType: 'normal',
            ),
          );

          tbClient.getAssetService().getAssetsByIds([
            '574552b0-8856-11ee-ae74-db5ae19db63f',
            '68a40a10-8856-11ee-ae74-db5ae19db63f',
            '6fd32e60-8856-11ee-ae74-db5ae19db63f'
          ]).then((value) {
            print('.........................$value');
          });
          portInfos?.add(
            ChargingInfo(
              portName: dashboardId?.configuration['states']['port_b']['name'],
              chargingStatus: 'charging',
              voltage: 40,
              isActive: true,
              chargingType: 'normal',
            ),
          );

          portInfos?.add(
            ChargingInfo(
              portName: dashboardId?.configuration['states']['port_c']['name'],
              chargingStatus: 'charging',
              voltage: 40,
              isActive: true,
              chargingType: 'normal',
            ),
          );
          notifyListeners();
          connectMqtt();
          tbClient
              .getAssetService()
              .getAsset('574552b0-8856-11ee-ae74-db5ae19db63f')
              .then((value) {
            print('asset $value');
          });
          print('port info ${portInfos}');

          tbClient
              .getDeviceService()
              .getDevice('0367bfc0-8856-11ee-ae74-db5ae19db63f')
              .then((value) {
            print('get device p $value');
          });
          tbClient
              .getDeviceProfileService()
              .getDeviceProfile('cf2a5600-8855-11ee-ae74-db5ae19db63f')
              .then((value) {
            print('device p $value');
          });
          tbClient
              .getAttributeService()
              .getAttributeKeys(EntityId.fromJson(
                  {'id': '52c9fd23-bbfd-96aa-435f-cbdebef51399'}))
              .then((value) {
            print('attr $value');
          });

          pageLink = pageLink.nextPageLink();
        } while (devicess.hasNext);

        // String? custId = currentUserDetails.getCustomerId()?.id;
        // print(tbClient.getDeviceService().assignDeviceToCustomer(
        //     custId!, '245b2010-885a-11ee-ae74-db5ae19db63f'));
      } catch (e, s) {
        print('Error: $e');
        print('Stack: $s');
      }
    } else {
      Util.showToast(context, 'Please enter username and password', 'error');
    }
  }

  var pongCount = 0;
  connectMqtt() async {
    // final NetworkAPiService _apiServices = NetworkAPiService();
    //  '' \
    // _apiServices
    //     .getGetNoParamApiRespone(
    //         'http://phyclouds.com:8080//api/plugins/telemetry/DEVICE/0367bfc0-8856-11ee-ae74-db5ae19db63f/values/attributes/CLIENT_SCOPE',
    //         'sDddcjXlWMcBhNussL6M')
    //     .then((val) {
    //   print(val);
    // });
    const broker = 'phyclouds.com';
    const port = 1884; // Change this to 8883 if using secure connection
    const clientId = 'your-client-id';
    const accesstoken = 'sDddcjXlWMcBhNussL6M';
    const password = '';
    final MqttServerClient client = MqttServerClient(broker, clientId);
    client.port = port;
    client.logging(on: true);
    client.secure = false;
    client.onBadCertificate = (dynamic a) => true;
    client.setProtocolV311();

    client.keepAlivePeriod = 20;

    client.onConnected = () {};

    client.keepAlivePeriod = 20;

    final connMessage = MqttConnectMessage()
        .withClientIdentifier(clientId)
        .withWillTopic('will-topic')
        .withWillMessage('Connection lost')
        .authenticateAs(accesstoken, password)
        .startClean()
        .withWillQos(MqttQos.atMostOnce);
    client.connectionMessage = connMessage;

    print('jjk$connMessage.................');
    try {
      await client.connect(accesstoken, password);
      print('............Connected to broker..........');

      // Subscribe to a topic
      client.subscribe(
          'v1/devices/me/attributes/response/+', MqttQos.atLeastOnce);
      try {
        print('............Connected to broker..........');
        client.updates!.listen((messageList) {
          print('entereddd...........................');
          final recMess = messageList[0];
          if (recMess is! MqttReceivedMessage<MqttPublishMessage>) return;
          final pubMess = recMess.payload;
          final pt =
              MqttPublishPayload.bytesToStringAsString(pubMess.payload.message);
          print(
              'EXAMPLE::Change notification:: topic is <${recMess.topic}>, payload is <-- $pt -->');

          print(
              'EXAMPLE::Manually Acknowledging message id ${pubMess.variableHeader?.messageIdentifier}');
          final ackRes = client.acknowledgeQos1Message(pubMess);
          ackRes!
              ? print('EXAMPLE::Manual acknowledge succeeded')
              : print('EXAMPLE::No Manual acknowledge');
          print(
              'EXAMPLE::Outstanding manual acknowledge message count is ${client.messagesAwaitingManualAcknowledge}');
        });
      } catch (e, s) {
        print(s);
      }

      final builder = MqttClientPayloadBuilder();

      builder.addString('Hello from Dart!');

      client.publishMessage('v1/devices/me/attributes/response',
          MqttQos.atMostOnce, builder.payload!);
      print('EXAMPLE::Sleeping....');
      await MqttUtilities.asyncSleep(60);
    } catch (e) {
      print('Exception: $e');
      print('error occured');
      client.disconnect();
    }
  }
}

I tried both from things board and mqqt server to get the data like I want readings of charger ports and I also want to operate those port.

0

There are 0 best solutions below