[IOT]透過 DeviceClient 讀取 Azure IOT Hub 送來的 Message 並處理

最近透過 Windows IOT Core 讀取 Azure IOT Hub 送來的 Message 並處理開門的事,

透過 Dispatcher.RunAsync 不要讓要執行的 Task 去影響UI的操作。

 

以下記錄一下程式處理的框架,如下,

//先建立 DeviceClient
_deviceClient = DeviceClient.CreateFromConnectionString(deviceConnstring, TransportType.Http1);
//處理取得Cloud給這個Device的訊息
var task = Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => {
	ReceiveFromIoTHub();
});
	

public async void ReceiveFromIoTHub()
{
	Message receivedMessage;
	string messageData;
	bool isOpening = false;
	while (true)
	{
		receivedMessage = await _deviceClient.ReceiveAsync();
		if (receivedMessage != null)
		{
			messageData = Encoding.UTF8.GetString(receivedMessage.GetBytes());
			await _deviceClient.CompleteAsync(receivedMessage);
			Debug.WriteLine($"Receive From Cloud:{messageData}");
			//如果是要做開門的話,要先check是否已有指令正在開門中
			if (!isOpening && messageData == "Open")
			{
				//開始取得Cloud送來的訊息
				var task = Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async () => {
					isOpening = true;
					try {
						//OpenDoor(); //透過設定 GPIO 來開門
						await Task.Delay(TimeSpan.FromSeconds(2));
						//CloseDoor(); //透過設定 GPIO 來取消開門
					}
					finally {
						isOpening = false;
					}
				});
			}
		}
	}
}

參考資料

CoreDispatcher.RunAsync Method

Hi, 

亂馬客Blog已移到了 「亂馬客​ : Re:從零開始的軟體開發生活

請大家繼續支持 ^_^