/// <summary>
 /// Send device's telemetry data to Azure IoT Hub
 /// </summary>
 public async void sendDeviceTelemetryData(D2CMessage[] data)
 {
     try
     {
         var msg = new Message(Serialize(data));
         if (deviceClient != null)
         {
             await deviceClient.SendEventAsync(msg);
             Debug.WriteLine("Sent telemetry data to IoT Hub\n" + data.ToString());
         }
         else Debug.WriteLine("Connection To IoT Hub is not established. Cannot send message now");
         
     }
     catch (System.Exception e)
     {
         Debug.WriteLine("Exception while sending device telemetry data :\n" + e.Message.ToString());
     }
 }
        /// <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;
        }
Пример #3
0
        /// <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, TransportType.Http1);

                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, CTDSensor> sensor in Sensors)
                            {
                                // Update the values that
                                sensor.Value.message.guid        = this.Guid;
                                sensor.Value.message.displayname = DisplayName;
                                sensor.Value.message.location    = Location;
                                sensor.Value.message.timecreated = DateTime.UtcNow.ToString("o");
                                if (sensor.Value.send)
                                {
                                    dataToSend[index++] = sensor.Value.message;
                                }
                            }
                            // 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)
                    {
                        if (deviceClient != null)
                        {
                            Message message = null;
                            try
                            {
                                // Receive message from Cloud (for now this is a pull because only HTTP is available for UWP applications)
                                message = await deviceClient.ReceiveAsync();
                            }
                            catch (Exception e)
                            {
                                // Something went wrong. Indicate the backend that we coudn't accept the message
                                Debug.WriteLine("Something went wrong when receiving message from IoT Hub: " + e.Message);
                            }

                            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 (Exception e)
                                {
                                    Debug.WriteLine("Something went wrong when receiving message from IoT Hub: " + e.Message);
                                    // Something went wrong. Indicate the backend that we coudn't accept the message
                                    await deviceClient.RejectAsync(message);
                                }
                            }
                        }
                        else
                        {
                            await Task.Delay(200);
                        }

                        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);
        }