-1

i want to toggle relays on/off remotely using raspberry pi model b running windows iot core, that raspberry pi have to connect with azure iot hub , and initially i can toggle relay on/off by accessing ui with browser over internet ,

Better approach(c#, node.js on windows iot core), link to related article will be appreciated.

1 Answers1

0

For using Azure IoT Hub, you can utilize direct method.

  • Device side:

For Windows IoT Core, you can start with UWP app.

The following is a simple sample of implementing the direct method on the device:

using Microsoft.Azure.Devices.Client;
using System.Diagnostics;
using System.Text;
using System.Threading.Tasks;
using Windows.UI.Xaml.Controls;


namespace App1
{
    public sealed partial class MainPage : Page
    {
        private string connectionStr = "HostName=[YOUR HUB NAME].azure-devices.net;DeviceId=[YOUR DEVICE ID];SharedAccessKey=[SHARED ACCESS KEY]";
        private DeviceClient deviceClient;

        public MainPage()
        {
            this.InitializeComponent();
            AddDirectMethod();
        }

        private async void AddDirectMethod()
        {
            deviceClient = DeviceClient.CreateFromConnectionString(connectionStr, TransportType.Mqtt);
            await deviceClient.SetMethodHandlerAsync("TurnOn", new MethodCallback(TurnOnRelay), null);
            await deviceClient.SetMethodHandlerAsync("TurnOff", new MethodCallback(TurnOffRelay), null);
        }

        private Task<MethodResponse> TurnOffRelay(MethodRequest methodRequest, object userContext)
        {
            Debug.WriteLine("Direct method name:" + methodRequest.Name);

            // Put Relay toggle code here.
            // ...

            string result = "{\"Relay Status\":\"The Relay is OFF.\"}";
            return Task.FromResult(new MethodResponse(Encoding.UTF8.GetBytes(result), 200));
        }

        private Task<MethodResponse> TurnOnRelay(MethodRequest methodRequest, object userContext)
        {
            Debug.WriteLine("Direct method name:" + methodRequest.Name);

            // Put Relay toggle code here.
            // ...

            string result = "{\"Relay Status\":\"The Relay is ON.\"}";
            return Task.FromResult(new MethodResponse(Encoding.UTF8.GetBytes(result), 200));
        }
    }
}

You need install NuGet package microsoft.azure.devices.client to your UWP app. Here is a detailed tutorial of a .NET console app you can reference.

  • Cloud side:

You can call direct method from Azure Portal like this:

enter image description here

Rita Han
  • 9,574
  • 1
  • 11
  • 24