getService method

Future<Service?> getService([
  1. Device? device
])

Returns the according service from this description. The provided device gets used to initialize it in the service

Implementation

Future<Service?> getService([Device? device]) async {
  if (scpdUrl == null) {
    throw Exception('Unable to fetch service, no SCPD URL.');
  }

  HttpClientRequest request;
  try {
    request = await UpnpCommon.httpClient
        .getUrl(Uri.parse(scpdUrl!))
        .timeout(const Duration(seconds: 10));
  } on TimeoutException {
    return Future.value(null);
  }

  final response = await request.close();

  if (response.statusCode != 200) {
    return null;
  }

  XmlElement doc;

  try {
    var content =
        await response.cast<List<int>>().transform(utf8.decoder).join();
    content = content.replaceAll('\u00EF\u00BB\u00BF', '');
    doc = XmlDocument.parse(content).rootElement;
  } catch (e) {
    return null;
  }

  final actionList = doc.findElements('actionList');
  final varList = doc.findElements('serviceStateTable');
  final acts = <Action>[];

  if (actionList.isNotEmpty) {
    for (var e in actionList.first.children) {
      if (e is XmlElement) {
        acts.add(Action.fromXml(e));
      }
    }
  }

  final vars = <StateVariable>[];

  if (varList.isNotEmpty) {
    for (var e in varList.first.children) {
      if (e is XmlElement) {
        vars.add(StateVariable.fromXml(e));
      }
    }
  }

  final service =
      Service(device, type, id, controlUrl, eventSubUrl, scpdUrl, acts, vars);

  for (var act in acts) {
    act.service = service;
  }

  for (var v in vars) {
    v.service = service;
  }

  return service;
}