/// <summary> /// Connect /// Connect to Azure IoT Hub ans start the send and receive loops /// </summary> /// <returns></returns> public bool Connect() { try { // Create Azure IoT Hub Client and open messaging channel deviceClient = DeviceClient.CreateFromConnectionString(this.ConnectionString); deviceClient.OpenAsync(); IsConnected = true; // Create send and receive tasks CancellationToken ct = TokenSource.Token; Task.Factory.StartNew(async()=> { while (true) { if (SendTelemetryData) { // Create message to be sent D2CMessage[] dataToSend = new D2CMessage[Sensors.Count]; int index = 0; foreach (KeyValuePair<string, D2CMessage> sensor in Sensors) { // Update the values that sensor.Value.displayname = DisplayName; sensor.Value.location = Location; sensor.Value.timecreated = DateTime.UtcNow.ToString("o"); dataToSend[index++] = sensor.Value; } // Send message sendDeviceTelemetryData(dataToSend); } await Task.Delay(SendTelemetryFreq); if (ct.IsCancellationRequested) { // Cancel was called Debug.WriteLine("Sending task canceled"); break; } } }, ct); Task.Factory.StartNew(async() => { while (true) { // Receive message from Cloud (for now this is a pull because only HTTP is available for UWP applications) Message message = await deviceClient.ReceiveAsync(); if (message != null) { try { // Read message and deserialize C2DMessage command = DeSerialize(message.GetBytes()); // Invoke message received callback OnReceivedMessage(new ReceivedMessageEventArgs(command)); // We received the message, indicate IoTHub we treated it await deviceClient.CompleteAsync(message); } catch { // Something went wrong. Indicate the backend that we coudn't accept the message await deviceClient.RejectAsync(message); } } if (ct.IsCancellationRequested) { // Cancel was called Debug.WriteLine("Receiving task canceled"); break; } } }, ct); } catch (Exception e) { Debug.WriteLine("Error while trying to connect to IoT Hub: " + e.Message); deviceClient = null; return false; } return true; }
public Task RejectAsync(string lockToken) { return(_deviceClient.RejectAsync(lockToken)); }