Reputation: 1086
I've been trying to make a direct method call using the AMQP protocol. But can't make it work. I believe calling direct method is possible over AMQP if I'm not wrong. It works with MQTT though. Any clues would be much appreciated.
Here's the code:
using Microsoft.Azure.Devices.Client;
using Microsoft.Azure.Devices.Shared;
using Newtonsoft.Json;
using System;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace VirtualIoTDevice
{
internal class Program
{
private const string DeviceConnectionString = "device-connection-string";
private const string DEVICE_ID = "device01";
private static DeviceClient _device;
private static async Task Main(string[] args)
{
Console.WriteLine("Initializing virtual IoT device..");
using (_device = DeviceClient.CreateFromConnectionString(DeviceConnectionString, DEVICE_ID))
{
await _device.OpenAsync();
await _device.SetMethodHandlerAsync("showMessage", ShowMessage, null);
Console.ReadKey();
}
}
private static Task<MethodResponse> ShowMessage(MethodRequest methodRequest, object userContext)
{
Console.WriteLine("***Direct message received***");
Console.WriteLine(methodRequest.DataAsJson);
var responsePayload = Encoding.ASCII.GetBytes(JsonConvert.SerializeObject(new { response = "Message shown!" }));
return Task.FromResult(new MethodResponse(responsePayload, 200));
}
}
}
And here's the command to invoke the direct method:
az iot hub invoke-device-method -n "iothub-name" -d "device01" --method-name "showMessage"
Upvotes: 0
Views: 416
Reputation: 16138
Ok, I know what your issue is: In the latest version of the SDK there was some change in regards to blocking threads. I don't know if this was an intended change or a regression.
However, in your case the Console.ReadKey()
is somehow blocking AMQP from connecting in the first place. MQTT is not affected by this - which could indicate it might be a regression.
So, if you change Console.ReadKey()
to for example await Task.Delay(-1)
it works again in my test.
Upvotes: 2