/// <summary> /// Device Update for IoT Hub Sample: Get device /// </summary> /// <param name="device">Device identifier.</param> static async Task Main(string device) { Console.WriteLine("Device Update for IoT Hub Sample: Get device"); Console.WriteLine(); if (string.IsNullOrWhiteSpace(device)) { throw new ArgumentException("You have to provider a valid device identifier."); } var credentials = new InteractiveBrowserCredential(Constant.TenantId, Constant.ClientId); var client = new DeviceManagementClient(Constant.AccountEndpoint, Constant.Instance, credentials); Console.WriteLine("Retrieve device information:"); Console.WriteLine($" Device: {device}"); Console.WriteLine(); Console.WriteLine("Information:"); try { var response = await client.GetDeviceAsync(device); Console.WriteLine(response.Content.ToString()); } catch (RequestFailedException e) { Console.WriteLine(e); throw; } }
public async void Run(IBackgroundTaskInstance taskInstance) { _deferral = taskInstance.GetDeferral(); var device = new TpmDevice(0); try { string deviceConnectionString = await device.GetConnectionStringAsync(); // Create DeviceClient. Application uses DeviceClient for telemetry messages, device twin // as well as device management DeviceClient deviceClient = DeviceClient.CreateFromConnectionString(deviceConnectionString, TransportType.Mqtt); // IDeviceTwin abstracts away communication with the back-end. // AzureIoTHubDeviceTwinProxy is an implementation of Azure IoT Hub IDeviceTwin deviceTwinProxy = new AzureIoTHubDeviceTwinProxy(deviceClient); // IDeviceManagementRequestHandler handles device management-specific requests to the app, // such as whether it is OK to perform a reboot at any givem moment, according the app business logic // ToasterDeviceManagementRequestHandler is the Toaster app implementation of the interface IDeviceManagementRequestHandler appRequestHandler = new DeviceManagementRequestHandler(); // Create the DeviceManagementClient, the main entry point into device management _dmClient = await DeviceManagementClient.CreateAsync(deviceTwinProxy, appRequestHandler); // Set the callback for desired properties update. The callback will be invoked // for all desired properties -- including those specific to device management await deviceClient.SetDesiredPropertyUpdateCallback(OnDesiredPropertyUpdate, null); } catch { LogError(); } }
/// <summary> /// Initializes a new instance of the Sample class. /// </summary> /// <exception cref="ArgumentNullException">Thrown when one or more required arguments are null.</exception> /// <param name="tenantId">Identifier for the tenant.</param> /// <param name="clientId">Identifier for the client.</param> /// <param name="clientSecret">The client secret.</param> /// <param name="accountEndpoint">The account endpoint.</param> /// <param name="instance">The instance.</param> /// <param name="connectionString">The connection string.</param> /// <param name="deviceId">Identifier for the device.</param> /// <param name="deviceTag">Device tag.</param> /// <param name="delete">Boolean flag to indicate whether the update should be deleted when finished.</param> public Sample(string tenantId, string clientId, string clientSecret, string accountEndpoint, string instance, string connectionString, string deviceId, string deviceTag, bool delete) { if (tenantId == null) { throw new ArgumentNullException(nameof(tenantId)); } if (clientId == null) { throw new ArgumentNullException(nameof(clientId)); } if (clientSecret == null) { throw new ArgumentNullException(nameof(clientSecret)); } _accountEndpoint = accountEndpoint ?? throw new ArgumentNullException(nameof(accountEndpoint)); _instanceId = instance ?? throw new ArgumentNullException(nameof(instance)); _connectionString = connectionString ?? throw new ArgumentNullException(nameof(connectionString)); _deviceId = deviceId ?? throw new ArgumentNullException(nameof(deviceId)); _deviceTag = deviceTag ?? throw new ArgumentNullException(nameof(deviceTag)); _delete = delete; var credentials = new ClientSecretCredential(tenantId, clientId, clientSecret); _updatesClient = new DeviceUpdateClient(accountEndpoint, instance, credentials); _managementClient = new DeviceManagementClient(accountEndpoint, instance, credentials); }
public async Task <string> AppInstallAsync(DeviceManagementClient client) { try { var appInstallInfo = new AppInstallInfo(); if (null != Dependencies) { foreach (var dependencyBlobInfo in Dependencies) { var depPath = await dependencyBlobInfo.DownloadToTempAsync(client); appInstallInfo.Dependencies.Add(depPath); } } var path = await Appx.DownloadToTempAsync(client); appInstallInfo.AppxPath = path; appInstallInfo.PackageFamilyName = PackageFamilyName; await client.InstallAppAsync(appInstallInfo); var response = JsonConvert.SerializeObject(new { response = "succeeded" }); return(response); } catch (Exception e) { var response = JsonConvert.SerializeObject(new { response = "failed", reason = e.Message }); return(response); } }
private ManagementClient(string baseUrl, IRestConnection restConnection) { restConnection.Setup(baseUrl, null); User = new UserManagementClient(baseUrl, restConnection); Company = new CompanyManagementClient(restConnection); Service = new ServiceManagementClient(restConnection); Network = new NetworkManagementClient(restConnection); Device = new DeviceManagementClient(restConnection); TelemetryDataSinksMetadata = new TelemetryDataSinksMetadataClient(restConnection); }
public void MockupProxyPostponedRebootTest() { var twin = new TwinMockup(); var requestHandler = new HandlerMockupForReboot(false); var proxy = new ConfigurationProxyMockup(); var dmClient = DeviceManagementClient.Create(twin, requestHandler, proxy); dmClient.RebootAsync().Wait(); Assert.AreEqual(proxy.ReceivedRequest, null); Assert.AreEqual(proxy.ReturnedResponse, null); }
private async Task ResetConnectionAsync() { Logger.Log("ResetConnectionAsync start", LoggingLevel.Verbose); // Attempt to close any existing connections before // creating a new one if (_deviceClient != null) { await _deviceClient.CloseAsync().ContinueWith((t) => { var e = t.Exception; if (e != null) { var msg = "existingClient.CloseAsync exception: " + e.Message + "\n" + e.StackTrace; System.Diagnostics.Debug.WriteLine(msg); Logger.Log(msg, LoggingLevel.Verbose); } }); } // Get new SAS Token var deviceConnectionString = await GetConnectionStringAsync(); // Create DeviceClient. Application uses DeviceClient for telemetry messages, device twin // as well as device management _deviceClient = DeviceClient.CreateFromConnectionString(deviceConnectionString, TransportType.Mqtt); // For testing connection failure, we can use a short time-out. // _deviceClient.OperationTimeoutInMilliseconds = 5000; // IDeviceTwin abstracts away communication with the back-end. // AzureIoTHubDeviceTwinProxy is an implementation of Azure IoT Hub IDeviceTwin deviceTwin = new AzureIoTHubDeviceTwinProxy(_deviceClient, _iotHubOfflineEvent, Logger.Log); // IDeviceManagementRequestHandler handles device management-specific requests to the app, // such as whether it is OK to perform a reboot at any givem moment, according the app business logic // ToasterDeviceManagementRequestHandler is the Toaster app implementation of the interface IDeviceManagementRequestHandler appRequestHandler = new ToasterDeviceManagementRequestHandler(this); // Create the DeviceManagementClient, the main entry point into device management this.deviceManagementClient = await DeviceManagementClient.CreateAsync(deviceTwin, appRequestHandler); await EnableDeviceManagementUiAsync(true); // Set the callback for desired properties update. The callback will be invoked // for all desired properties -- including those specific to device management await _deviceClient.SetDesiredPropertyUpdateCallbackAsync(OnDesiredPropertyUpdated, null); // Tell the deviceManagementClient to sync the device with the current desired state. await this.deviceManagementClient.ApplyDesiredStateAsync(); Logger.Log("ResetConnectionAsync end", LoggingLevel.Verbose); }
public void MockupProxyImmediateRebootTest() { var twin = new TwinMockup(); var requestHandler = new HandlerMockupForReboot(true); var proxy = new ConfigurationProxyMockup(); var dmClient = DeviceManagementClient.Create(twin, requestHandler, proxy); dmClient.RebootAsync().Wait(); Assert.AreEqual(proxy.ReceivedRequest.Tag, DMMessageKind.ImmediateReboot); Assert.AreEqual(proxy.ReturnedResponse.Tag, DMMessageKind.ImmediateReboot); Assert.AreEqual(proxy.ReturnedResponse.Status, ResponseStatus.Success); }
public async Task GetGroups() { DeviceManagementClient client = CreateClient(); AsyncPageable <BinaryData> fetchResponse = client.GetGroupsAsync(new RequestContext()); int counter = 0; await foreach (var item in fetchResponse) { Assert.IsNotNull(item); counter++; } Assert.IsTrue(counter > 0); }
private static async Task DownloadCertificates(DeviceManagementClient client, string connectionString, string containerName, HashSet <string> certificateFilesSet) { // ToDo: since our cache is temporary, we might have to download those files everytime to verify the hashes. Debug.Assert(certificateFilesSet != null); foreach (string fileName in certificateFilesSet) { IoTDMClient.BlobInfo blobInfo = new IoTDMClient.BlobInfo(); blobInfo.ConnectionString = connectionString; blobInfo.ContainerName = containerName; blobInfo.BlobName = fileName; Debug.WriteLine("Downloading " + blobInfo.BlobName); await blobInfo.DownloadToTempAsync(client); } }
public async Task <string> DownloadToTempAsync(DeviceManagementClient client) { var path = DMGarbageCollector.TempFolder + BlobName; var info = new AzureFileTransferInfo() { ConnectionString = ConnectionString, ContainerName = ContainerName, BlobName = BlobName, Upload = false, LocalPath = path }; await AzureBlobFileTransfer.TransferFileAsync(info, client); return(path); }
public async Task <string> ProvisionPkgsAsync(DeviceManagementClient client) { try { var provInfo = new ProvisionInfo(); var ppkgPath = await ProvisioningPackage.DownloadToTempAsync(client); provInfo.ProvisioningPkgs.Add(ppkgPath); await client.ProvisionAsync(provInfo); var response = JsonConvert.SerializeObject(new { response = "succeeded" }); return(response); } catch (Exception e) { var response = JsonConvert.SerializeObject(new { response = "failed", reason = e.Message }); return(response); } }
public static async Task DownloadCertificates( DeviceManagementClient client, string connectionString, string containerName, CertificateConfiguration certificateConfiguration) { HashSet <string> certificateFilesSet = new HashSet <string>(); MergeCertificateFileNames(certificateConfiguration.rootCATrustedCertificates_Root, certificateFilesSet); MergeCertificateFileNames(certificateConfiguration.rootCATrustedCertificates_CA, certificateFilesSet); MergeCertificateFileNames(certificateConfiguration.rootCATrustedCertificates_TrustedPublisher, certificateFilesSet); MergeCertificateFileNames(certificateConfiguration.rootCATrustedCertificates_TrustedPeople, certificateFilesSet); MergeCertificateFileNames(certificateConfiguration.certificateStore_CA_System, certificateFilesSet); MergeCertificateFileNames(certificateConfiguration.certificateStore_Root_System, certificateFilesSet); MergeCertificateFileNames(certificateConfiguration.certificateStore_My_User, certificateFilesSet); MergeCertificateFileNames(certificateConfiguration.certificateStore_My_System, certificateFilesSet); await DownloadCertificates(client, connectionString, containerName, certificateFilesSet); }
private async Task InitializeDeviceClientAsync() { // Create DeviceClient. Application uses DeviceClient for telemetry messages, device twin // as well as device management //DeviceClient deviceClient = DeviceClient.CreateFromConnectionString(DeviceConnectionString, TransportType.Mqtt); deviceClient = DeviceClient.CreateFromConnectionString(DeviceConnectionString, TransportType.Mqtt); //deviceClient = DeviceClient.CreateFromConnectionString(DeviceConnectionString); // IDeviceTwin abstracts away communication with the back-end. // AzureIoTHubDeviceTwinProxy is an implementation of Azure IoT Hub IDeviceTwin deviceTwinProxy = new AzureIoTHubDeviceTwinProxy(deviceClient); try { // IDeviceManagementRequestHandler handles device management-specific requests to the app, // such as whether it is OK to perform a reboot at any givem moment, according to the app // business logic. // DMRequestHandler is the Toaster app implementation of the interface IDeviceManagementRequestHandler appRequestHandler = new DMRequestHandler(this); // Create the DeviceManagementClient, the main entry point into device management this.deviceManagementClient = await DeviceManagementClient.CreateAsync(deviceTwinProxy, appRequestHandler); // Set the callback for desired properties update. The callback will be invoked // for all desired properties -- including those specific to device management await deviceClient.SetDesiredPropertyUpdateCallback(OnDesiredPropertyUpdate, null); await this.deviceClient.OpenAsync(); connectionstatus.Text = "Connected"; // Set up callbacks: await deviceClient.SetMethodHandlerAsync("Getsensordata", Getsensordata, null); //this.UpdateDeviceStatus(); } catch (Exception ex) { Debug.WriteLine("Error in sample InitializeDeviceClientAsync: {0}", ex.Message); } }
private async Task InitializeDeviceClientAsync() { // Create DeviceClient. Application uses DeviceClient for telemetry messages, device twin // as well as device management DeviceClient deviceClient = DeviceClient.CreateFromConnectionString(DeviceConnectionString, TransportType.Mqtt); // IDeviceTwin abstracts away communication with the back-end. // AzureIoTHubDeviceTwinProxy is an implementation of Azure IoT Hub IDeviceTwin deviceTwinProxy = new AzureIoTHubDeviceTwinProxy(deviceClient); // IDeviceManagementRequestHandler handles device management-specific requests to the app, // such as whether it is OK to perform a reboot at any givem moment, according the app business logic // ToasterDeviceManagementRequestHandler is the Toaster app implementation of the interface IDeviceManagementRequestHandler appRequestHandler = new ToasterDeviceManagementRequestHandler(this); // Create the DeviceManagementClient, the main entry point into device management this.deviceManagementClient = await DeviceManagementClient.CreateAsync(deviceTwinProxy, appRequestHandler); EnableDeviceManagementUI(true); // Set the callback for desired properties update. The callback will be invoked // for all desired properties -- including those specific to device management await deviceClient.SetDesiredPropertyUpdateCallback(OnDesiredPropertyUpdate, null); }
/// <summary> /// Device Update for IoT Hub Sample: Deploy update to a test device /// </summary> /// <param name="updateVersion">Update version to retrieve.</param> /// <param name="deviceGroup">Device group to deploy the update to.</param> static async Task Main(string updateVersion, string deviceGroup) { Console.WriteLine("Device Update for IoT Hub Sample: Deploy update to a test device"); Console.WriteLine(); if (string.IsNullOrWhiteSpace(updateVersion)) { throw new ArgumentException("You have to provider a valid update version."); } var credentials = new InteractiveBrowserCredential(Constant.TenantId, Constant.ClientId); var client = new DeviceManagementClient(Constant.AccountEndpoint, Constant.Instance, credentials); Console.WriteLine("Retrieve update:"); Console.WriteLine($" Provider: {Constant.Provider}"); Console.WriteLine($" Name : {Constant.Name}"); Console.WriteLine($" Version : {updateVersion}"); Console.WriteLine(); Console.WriteLine($"Checking existence of device group '{deviceGroup}'..."); try { var response = await client.GetGroupAsync(deviceGroup); if (response.Status == (int)HttpStatusCode.NotFound) { throw new ApplicationException($"Group '{deviceGroup}' doesn't exist. Create it before you create a deployment."); } Console.WriteLine($"Group '{deviceGroup}' already exists."); } catch (RequestFailedException e) { Console.WriteLine(e); throw; } Console.WriteLine(); Console.WriteLine($"Creating deployment of update '{updateVersion}' to device group '{deviceGroup}'..."); var deploymentId = $"test{DateTime.UtcNow.ToString("MMddhhmmss")}"; var deployment = new { deploymentId, startDateTime = DateTime.UtcNow.ToString("O"), groupId = deviceGroup, updateId = new { manufacturer = Constant.Provider, name = Constant.Name, version = updateVersion } }; var body = JsonSerializer.Serialize(deployment); Console.WriteLine(); Console.WriteLine($"Deploying update '{updateVersion}' to device group '{deviceGroup}'..."); Console.WriteLine($"(this may take a long time to finish)"); try { var response = await client.CreateOrUpdateDeploymentAsync(deviceGroup, deploymentId, RequestContent.Create(body)); bool repeat = true; while (repeat) { response = await client.GetDeploymentStatusAsync(deviceGroup, deploymentId); var doc = JsonDocument.Parse(response.Content.ToMemory()); if (doc.RootElement.TryGetProperty("devicesCompletedSucceededCount", out var deviceCountValue) && deviceCountValue.GetInt32() > 0) { Console.WriteLine($"\nSuccessfully deployed to {deviceCountValue.GetInt32()} devices."); repeat = false; } else { Console.Write("."); await Task.Delay(DefaultRetryAfterValue); } } } catch (RequestFailedException e) { Console.WriteLine(e); throw; } }
protected override async void OnNavigatedTo(NavigationEventArgs e) { dispatcher = CoreWindow.GetForCurrentThread().Dispatcher; var device = new TpmDevice(0); try { string deviceConnectionString = await device.GetConnectionStringAsync(); // Create DeviceClient. Application uses DeviceClient for telemetry messages, device twin // as well as device management DeviceClient deviceClient = DeviceClient.CreateFromConnectionString(deviceConnectionString, TransportType.Mqtt); // // IDeviceTwin abstracts away communication with the back-end. // // AzureIoTHubDeviceTwinProxy is an implementation of Azure IoT Hub IDeviceTwin deviceTwinProxy = new AzureIoTHubDeviceTwinProxy(deviceClient); // // IDeviceManagementRequestHandler handles device management-specific requests to the app, // // such as whether it is OK to perform a reboot at any givem moment, according the app business logic // // ToasterDeviceManagementRequestHandler is the Toaster app implementation of the interface IDeviceManagementRequestHandler appRequestHandler = new DeviceManagementRequestHandler(); // // Create the DeviceManagementClient, the main entry point into device management _dmClient = await DeviceManagementClient.CreateAsync(deviceTwinProxy, appRequestHandler); // // Set the callback for desired properties update. The callback will be invoked // // for all desired properties -- including those specific to device management await deviceClient.SetDesiredPropertyUpdateCallback(OnDesiredPropertyUpdate, null); string str = "Device Restarted"; var message = new Message(Encoding.ASCII.GetBytes(str)); await deviceClient.SendEventAsync(message); } catch { } await InitRfcommServer(); ConnectCtrl c = new ConnectCtrl(this); main.Children.Add(c); ResultCollection = new ObservableCollection <RfcommChatDeviceDisplay>(); c.SetResultList(ResultCollection); // TODO: // check if you are running in the factory (e.g. contacting a specific server or connecting to a predefined network) // initialize the TPM device //try //{ // tpm = new TpmDevice(0); //} //catch //{ // Debug.WriteLine("TPM not present Error"); // return; //} //// reset TPM to clean previous //try //{ // Debug.WriteLine("Reset TPM..."); // tpm.Destroy(); //} //catch (Exception ex) //{ // Debug.WriteLine("TPM was not initialized!"); //} //Debug.WriteLine("TPM initialized"); //string id = tpm.GetDeviceId(); ////HWID is unique for this device. //string hwid = tpm.GetHardwareDeviceId(); //Debug.WriteLine("TPM Hardware ID:" + hwid); //string hmackey = CryptoKeyGenerator.GenerateKey(32); //Debug.WriteLine("TPM hmackey:" + hmackey); ////provision the device. //tpm.Provision(hmackey, "gunterlhub.azure-devices.net", hwid); // TODO: // send hmacky and hwid to production server and create the devices on the iot hub // connect to production server via bluetooth if availiable // }
public static async Task TransferFileAsync(AzureFileTransferInfo transferInfo, DeviceManagementClient client) { // // C++ Azure Blob SDK not supported for ARM, so use Service to copy file to/from // App's LocalData and then use C# Azure Blob SDK to transfer // var appLocalDataFile = await ApplicationData.Current.TemporaryFolder.CreateFileAsync(transferInfo.BlobName, CreationCollisionOption.ReplaceExisting); transferInfo.AppLocalDataPath = appLocalDataFile.Path; if (!transferInfo.Upload) { transferInfo.AppLocalDataPath = await DownloadFile(transferInfo, appLocalDataFile); } await client.TransferFileAsync(transferInfo); if (transferInfo.Upload) { await UploadFile(transferInfo, appLocalDataFile); } await appLocalDataFile.DeleteAsync(); }
public async Task GroupAndDeployment() { DeviceManagementClient client = CreateClient(); string groupid = "joegroup"; /* list groups. */ AsyncPageable <BinaryData> fetchResponse = client.GetGroupsAsync(new RequestContext()); int counter = 0; await foreach (var item in fetchResponse) { Assert.IsNotNull(item); counter++; } Assert.IsTrue(counter > 0); /* create a group. */ var body = new { groupId = groupid, tags = new string[] { groupid }, createdDateTime = "2021-11-17T16:29:56.5770502+00:00", groupType = "DeviceClassIdAndIoTHubTag", deviceClassId = "0919e3ae422a2bfa8c84ff905813e60351e456d1" }; Response createResponse = await client.CreateOrUpdateGroupAsync(groupid, RequestContent.Create(body), new RequestContext()); Assert.IsTrue(createResponse.Status == 200); /* get a group. */ Response getResponse = await client.GetGroupAsync(groupid, new RequestContext()); Assert.IsTrue(getResponse.Status == 200); /* create a deployment. */ string deploymentid = "testdeployment1"; var deploymentBody = new { deploymentId = deploymentid, startDateTime = "2021-09-02T16:29:56.5770502Z", groupId = groupid, updateId = new { provider = "fabrikam", name = "vacuum", version = "2021.1117.1036.48" } }; Response createDeploymentResponse = await client.CreateOrUpdateDeploymentAsync(groupid, deploymentid, RequestContent.Create(deploymentBody), new RequestContext()); Assert.IsTrue(createDeploymentResponse.Status == 200); /* get deployment. */ Response getDepoloymentResponse = await client.GetDeploymentAsync(groupid, deploymentid, new RequestContext()); Assert.IsTrue(getDepoloymentResponse.Status == 200); /* delete deployment. */ Response deleteDeploymentResponse = await client.DeleteDeploymentAsync(groupid, deploymentid, new RequestContext()); Assert.IsTrue(deleteDeploymentResponse.Status == 204); /* delete group. */ Response deleteGroupResponse = await client.DeleteGroupAsync(groupid, new RequestContext()); Assert.IsTrue(deleteGroupResponse.Status == 204); }