/// <summary> /// Provisions the device with the data entered. /// </summary> public void ProvisionDevice() { Task.Run(async() => { ShowLoadingDialog("Provisioning device..."); string devName = DeviceId; // If the device is an irrigation station, format its device ID. if (!isController) { devName = string.Format(STATION_IDENTIFIER, DeviceId); } // Generate the provisioning JSON and send it to the device. JObject json = JObject.Parse(@"{" + "'" + JsonConstants.ITEM_OP + "': '" + JsonConstants.OP_WRITE + "'," + "'" + JsonConstants.ITEM_PROP + "': {" + "'" + JsonConstants.PROP_NAME + "': '" + devName + "'," + (isController && isMainController ? "'" + JsonConstants.PROP_MAIN_CONTROLLER + "': 'true'," : "") + "'" + JsonConstants.PROP_LATITUDE + "': '" + FormatLocation(Location.Latitude) + "'," + "'" + JsonConstants.PROP_LONGITUDE + "': '" + FormatLocation(Location.Longitude) + "'," + (Location.Altitude.HasValue ? "'" + JsonConstants.PROP_ALTITUDE + "': '" + FormatLocation(Math.Round(Location.Altitude.Value)) + "'," : "") + "'" + JsonConstants.PROP_PAN_ID + "': '" + NetworkId + "'," + (!string.IsNullOrEmpty(NetworkPassword) ? "'" + JsonConstants.PROP_PASS + "': '" + NetworkPassword + "'" : "") + "}" + "}"); string response = SendData(json, JsonConstants.OP_WRITE, true); if (response == null || !response.Equals("")) { await ShowProvisioningError("Could not provision the device" + (response != null ? ": " + response : "") + "."); return; } // If the device is a controller, store the newtork ID and register it in Digi Remote Manager. if (isController) { AppPreferences.AddNetworkId(NetworkId); try { RegisterDeviceDRM(); } catch (Exception e) { await ShowProvisioningError(string.Format("Could not register the device in Digi Remote Manager: {0}", e.Message)); return; } } // If the device is a station, wait until it is joined to the network. else { HideLoadingDialog(); ShowLoadingDialog("Waiting for device to join the network..."); long deadline = Environment.TickCount + ASSOCIATION_TIMEOUT; int ai = -1; // Wait until the device is associated or the timeout elapses. while (Environment.TickCount < deadline && ai != 0) { ai = int.Parse(HexUtils.ByteArrayToHexString(bleDevice.XBeeDevice.GetParameter(AT_ASSOCIATION)), System.Globalization.NumberStyles.HexNumber); await Task.Delay(1000); } if (ai != 0) { await ShowProvisioningError(string.Format("The device could not associate to the configured network. " + "Please make sure the irrigation controller with network ID '{0}' is powered on.", NetworkId)); return; } } FinishProvisioning(); HideLoadingDialog(); await DisplayAlert("Provisioning finished", "The device has been provisioned successfully."); // Go to the root page. Device.BeginInvokeOnMainThread(async() => { await Application.Current.MainPage.Navigation.PopToRootAsync(); }); }); }