doDiscoverThenDoProvisioning method

Future<ScpStatus> doDiscoverThenDoProvisioning(
  1. String subnet,
  2. String mask,
  3. String ssid,
  4. String wifiPassword,
  5. String jsonPath,
)

Implementation

Future<ScpStatus> doDiscoverThenDoProvisioning(String subnet, String mask,
    String ssid, String wifiPassword, String jsonPath) async {
  newDevices = List<ScpDevice>.empty(growable: true);
  // Get a list with all relevant IP addresses
  IPRange range = IPRange(subnet, int.parse(mask));
  List<String> allIPs = range.getAllIpAddressesInRange();

  List<Future> requests = List<Future>.empty(growable: true);

  allIPs.forEach((ip) {
    requests.add(ScpMessageSender.sendDiscoverHello(ip));
  });

  Future.wait(requests).then(
    (List responses) => responses.forEach((response) async {
      if (response != null && response.bodyBytes != null) {
        if (response.statusCode == 200) {
          log('Received discover response.');
          ScpResponseDiscover parsedResponse =
              await ScpResponseParser.parseDiscoverResponse(
                  response, const []);
          if (parsedResponse.isValid()) {
            // create device
            ScpDevice dev = ScpDevice(
                deviceId: parsedResponse.getDeviceId(),
                deviceType: parsedResponse.getDeviceType(),
                currentPasswordNumber:
                    parsedResponse.getCurrentPasswordNumber(),
                ipAddress: allIPs
                    .firstWhere((ip) => response.request.url.host == ip),
                isDefaultPasswordSet:
                    parsedResponse.getCurrentPasswordNumber() == 0
                        ? true
                        : false,
                knownPassword: parsedResponse.getCurrentPasswordNumber() == 0
                    ? "01234567890123456789012345678901"
                    : "");
            log('Found device: ${dev.toString()}');

            if (dev.isDefaultPasswordSet) {
              log('default password set, adding to new devices.');
              newDevices.add(dev);
            } else {
              log('default password not set.');
              if (knownDevices
                  .contains((element) => element.deviceId == dev.deviceId)) {
                log('Device ${dev.deviceId} already known.');
              } else {
                log('Device ${dev.deviceId} not known, adding to known devices.');
                knownDevices.add(dev);
              }
            }
            await doProvisioning(dev, ssid, wifiPassword, jsonPath);
          }
        }
      }
    }),
  );

  return ScpStatus(status: ScpStatus.RESULT_SUCCESS);
}