Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[IoT Hub] Invoke direct method on a device. #11472

Merged
merged 2 commits into from
Apr 2, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions src/IotHub/IotHub.Test/ScenarioTests/IotHubDPDeviceTests.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,10 @@ function Test-AzureRmIotHubDeviceLifecycle
Assert-True { $updateddevice1twin3.DeviceId -eq $device1}
Assert-True { $updateddevice1twin3.tags.Count -eq 1}

# Invoke direct method on device
$errorMessage = 'Timed out waiting for device to connect.'
Assert-ThrowsContains { Invoke-AzIotHubDeviceMethod -ResourceGroupName $ResourceGroupName -IotHubName $IotHubName -DeviceId $device1 -Name "SetTelemetryInterval" } $errorMessage

# Get all devices
$devices = Get-AzIotHubDevice -ResourceGroupName $ResourceGroupName -IotHubName $IotHubName
Assert-True { $devices.Count -eq 3}
Expand Down

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion src/IotHub/IotHub/Az.IotHub.psd1
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@ CmdletsToExport = 'Add-AzIotHubKey', 'Get-AzIotHubEventHubConsumerGroup',
'Set-AzIotHubDeviceParent', 'Add-AzIotHubDeviceChildren',
'Remove-AzIotHubDeviceChildren', 'Get-AzIotHubDeviceChildren',
'Get-AzIotHubDistributedTracing', 'Set-AzIotHubDistributedTracing',
'Get-AzIotHubDeviceTwin', 'Update-AzIotHubDeviceTwin'
'Get-AzIotHubDeviceTwin', 'Update-AzIotHubDeviceTwin', 'Invoke-AzIotHubDeviceMethod'
# Variables to export from this module
# VariablesToExport = @()

Expand Down
1 change: 1 addition & 0 deletions src/IotHub/IotHub/ChangeLog.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
* Manage IoT device twin configuration, New cmdlets are:
- `Get-AzIotHubDeviceTwin`
- `Update-AzIotHubDeviceTwin`
* Added cmdlet to invoke direct method on a device in an Iot Hub.

## Version 2.3.0
* Added support to manage distributed settings per-device. New Cmdlets are:
Expand Down
22 changes: 22 additions & 0 deletions src/IotHub/IotHub/IotHub.format.ps1xml
Original file line number Diff line number Diff line change
Expand Up @@ -965,5 +965,27 @@
</ListEntries>
</ListControl>
</View>
<View>
<Name>
Microsoft.Azure.Commands.Management.IotHub.Models.PSCloudToDeviceMethodResult
</Name>
<ViewSelectedBy>
<TypeName>Microsoft.Azure.Commands.Management.IotHub.Models.PSCloudToDeviceMethodResult</TypeName>
</ViewSelectedBy>
<ListControl>
<ListEntries>
<ListEntry>
<ListItems>
<ListItem>
<PropertyName>Status</PropertyName>
</ListItem>
<ListItem>
<PropertyName>Payload</PropertyName>
</ListItem>
</ListItems>
</ListEntry>
</ListEntries>
</ListControl>
</View>
</ViewDefinitions>
</Configuration>
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------

namespace Microsoft.Azure.Commands.Management.IotHub
{
using System;
using System.Collections.Generic;
using System.Management.Automation;
using Microsoft.Azure.Commands.Management.IotHub.Common;
using Microsoft.Azure.Commands.Management.IotHub.Models;
using Microsoft.Azure.Devices;
using Microsoft.Azure.Management.IotHub;
using Microsoft.Azure.Management.IotHub.Models;
using Microsoft.WindowsAzure.Commands.Utilities.Common;
using ResourceManager.Common.ArgumentCompleters;

[Cmdlet("Invoke", ResourceManager.Common.AzureRMConstants.AzureRMPrefix + "IotHubDeviceMethod", DefaultParameterSetName = ResourceParameterSet, SupportsShouldProcess = true)]
[OutputType(typeof(PSCloudToDeviceMethodResult))]
public class InvokeAzIotHubDeviceMethod : IotHubBaseCmdlet
{
private const string ResourceIdParameterSet = "ResourceIdSet";
private const string ResourceParameterSet = "ResourceSet";
private const string InputObjectParameterSet = "InputObjectSet";

[Parameter(Position = 0, Mandatory = true, ParameterSetName = InputObjectParameterSet, ValueFromPipeline = true, HelpMessage = "IotHub object")]
[ValidateNotNullOrEmpty]
public PSIotHub InputObject { get; set; }

[Parameter(Position = 0, Mandatory = true, ParameterSetName = ResourceIdParameterSet, ValueFromPipelineByPropertyName = true, HelpMessage = "IotHub Resource Id")]
[ValidateNotNullOrEmpty]
[ResourceIdCompleter("Microsoft.Devices/IotHubs")]
public string ResourceId { get; set; }

[Parameter(Position = 0, Mandatory = true, ParameterSetName = ResourceParameterSet, HelpMessage = "Name of the Resource Group")]
[ValidateNotNullOrEmpty]
[ResourceGroupCompleter]
public string ResourceGroupName { get; set; }

[Parameter(Position = 1, Mandatory = true, ParameterSetName = ResourceParameterSet, HelpMessage = "Name of the Iot Hub")]
[ValidateNotNullOrEmpty]
public string IotHubName { get; set; }

[Parameter(Position = 1, Mandatory = true, ParameterSetName = InputObjectParameterSet, HelpMessage = "Target Device Id.")]
[Parameter(Position = 1, Mandatory = true, ParameterSetName = ResourceIdParameterSet, HelpMessage = "Target Device Id.")]
[Parameter(Position = 2, Mandatory = true, ParameterSetName = ResourceParameterSet, HelpMessage = "Target Device Id.")]
[ValidateNotNullOrEmpty]
public string DeviceId { get; set; }

[Parameter(Mandatory = true, HelpMessage = "The name of the method to invoke on this device.")]
public string Name { get; set; }

[Parameter(Mandatory = false, HelpMessage = "The payload for the method to invoke on this device.")]
public string Payload { get; set; }

[Parameter(Mandatory = false, HelpMessage = "Number of seconds to wait until a result is received from the direct method. Default is 10.")]
public int ResponseTimeOut { get; set; }

[Parameter(Mandatory = false, HelpMessage = "Number of seconds to wait until a connection is successfully made. Default is 10.")]
[ValidateRange(10, 300)]
public int ConnectionTimeOut { get; set; }

public override void ExecuteCmdlet()
{
if (ShouldProcess(this.IotHubName, Properties.Resources.InvokeIotHubDeviceMethod))
{
IotHubDescription iotHubDescription;
if (ParameterSetName.Equals(InputObjectParameterSet))
{
this.ResourceGroupName = this.InputObject.Resourcegroup;
this.IotHubName = this.InputObject.Name;
iotHubDescription = IotHubUtils.ConvertObject<PSIotHub, IotHubDescription>(this.InputObject);
}
else
{
if (ParameterSetName.Equals(ResourceIdParameterSet))
{
this.ResourceGroupName = IotHubUtils.GetResourceGroupName(this.ResourceId);
this.IotHubName = IotHubUtils.GetIotHubName(this.ResourceId);
}

iotHubDescription = this.IotHubClient.IotHubResource.Get(this.ResourceGroupName, this.IotHubName);
}

IEnumerable<SharedAccessSignatureAuthorizationRule> authPolicies = this.IotHubClient.IotHubResource.ListKeys(this.ResourceGroupName, this.IotHubName);
SharedAccessSignatureAuthorizationRule policy = IotHubUtils.GetPolicy(authPolicies, PSAccessRights.ServiceConnect);
PSIotHubConnectionString psIotHubConnectionString = IotHubUtils.ToPSIotHubConnectionString(policy, iotHubDescription.Properties.HostName);
ServiceClient serviceClient = ServiceClient.CreateFromConnectionString(psIotHubConnectionString.PrimaryConnectionString);

if (!this.IsParameterBound(c => c.ResponseTimeOut))
{
this.ResponseTimeOut = 10;
}

if (!this.IsParameterBound(c => c.ConnectionTimeOut))
{
this.ConnectionTimeOut = 10;
}

CloudToDeviceMethod method = new CloudToDeviceMethod(this.Name, new TimeSpan(0, 0, this.ResponseTimeOut), new TimeSpan(0, 0, this.ConnectionTimeOut));
if (this.IsParameterBound(c => c.Payload))
{
method = method.SetPayloadJson(this.Payload);
}

CloudToDeviceMethodResult result = serviceClient.InvokeDeviceMethodAsync(this.DeviceId, method).GetAwaiter().GetResult();
PSCloudToDeviceMethodResult psCloudToDeviceMethodResult = new PSCloudToDeviceMethodResult()
{
Status = result.Status,
Payload = result.GetPayloadAsJson()
};
this.WriteObject(psCloudToDeviceMethodResult);
}
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------

namespace Microsoft.Azure.Commands.Management.IotHub.Models
{
/// <summary>
/// Represents the Device Method Invocation Results.
/// </summary>

public class PSCloudToDeviceMethodResult
{
/// <summary>
/// Gets or sets the status of device method invocation.
/// </summary>
public int Status { get; set; }

/// <summary>
/// Gets or sets the result payload of device method invocation.
/// </summary>
public string Payload { get; set; }
}
}
9 changes: 9 additions & 0 deletions src/IotHub/IotHub/Properties/Resources.Designer.cs

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 3 additions & 0 deletions src/IotHub/IotHub/Properties/Resources.resx
Original file line number Diff line number Diff line change
Expand Up @@ -222,4 +222,7 @@
<data name="UpdateIotHubDeviceTwin" xml:space="preserve">
<value>Update Device Twin</value>
</data>
<data name="InvokeIotHubDeviceMethod" xml:space="preserve">
<value>Invoke Direct Method on a device</value>
</data>
</root>
3 changes: 3 additions & 0 deletions src/IotHub/IotHub/help/Az.IotHub.md
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,9 @@ Get information on all the endpoints for your IoT Hub
### [Get-AzIotHubValidSku](Get-AzIotHubValidSku.md)
Gets all valid skus that this IotHub can transition to.

### [Invoke-AzIotHubDeviceMethod](Invoke-AzIotHubDeviceMethod.md)
Invoke a direct method on a device.

### [Invoke-AzIotHubManualFailover](Invoke-AzIotHubManualFailover.md)
Invoke failover process for the IoT Hub to the geo-paired disaster recovery region.

Expand Down
Loading