fromJson static method

Future<ScpResponseDiscover> fromJson(
  1. dynamic json,
  2. List<ScpDevice> devices,
  3. bool verifyHmac
)

Returns a ScpResponseDiscover if HMAC valid, otherwise null

Implementation

static  Future<ScpResponseDiscover> fromJson(
    var json, List<ScpDevice> devices, bool verifyHmac) async {
  Scp.getInstance().log('$json');
  if (json['type'] == type) {
    if (json['deviceId'] == null ||
        json['deviceId'] == '' ||
        json['deviceType'] == null ||
        json['deviceType'] == '' ||
        json['controlActions'] == null ||
        json['measureActions'] == null ||
        json['currentPasswordNumber'] == null ||
        json['currentPasswordNumber'] == '' ||
        json['hmac'] == null ||
        json['hmac'] == '') {
      return ScpResponseDiscover();
    }

    ScpResponseDiscover discoverResponse = ScpResponseDiscover(
      deviceId: json['deviceId'],
      deviceType: json['deviceType'],
      deviceName: json['deviceName'] != null ? json['deviceName'] : '',
      controlActions: json['controlActions'] != null
          ? Utils.dynamicListToStringList(json['controlActions'])
          : const [],
      measureActions: json['measureActions'] != null
          ? Utils.dynamicListToStringList(json['measureActions'])
          : const [],
      currentPasswordNumber: int.parse(json['currentPasswordNumber']),
      hmac: json['hmac'],
    );

    String password = '';
    if (devices.length > 0) {
      password = devices
          .firstWhere(
              (element) => element.deviceId == discoverResponse.getDeviceId())
          .knownPassword;
    }

    // Check hmac before additional processing
    if (verifyHmac) {
      String controlActions = '';
      if (discoverResponse.isValid()) {
        for (String s in discoverResponse.getControlActions()) {
          controlActions += '"$s"';
        }
      }
      String measureActions = '';
      if (discoverResponse.isValid()) {
        for (String s in discoverResponse.getMeasureActions()) {
          measureActions += '"$s"';
        }
      }
      String verifyString =
          '${ScpResponseDiscover.type}${discoverResponse.getDeviceId()}${discoverResponse.getDeviceType()}${discoverResponse.getDeviceName()}${controlActions}${measureActions}${discoverResponse.getCurrentPasswordNumber()}';
      Scp.getInstance().log('verify string:');
      Scp.getInstance().log(verifyString);
      if (await ScpCrypto()
          .verifyHMAC(verifyString, discoverResponse.getHmac(), password)) {
        return discoverResponse;
      }
    } else {
      return discoverResponse;
    }
  }
  return ScpResponseDiscover();
}