Ejemplo n.º 1
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(ConnectionString(), TransportType.Http1);
                deviceClient.OpenAsync();
                IsConnected = true;

                // Send Device Meta Data to IoT Suite
                sendData(Model);

                CancellationToken ct = TokenSource.Token;
                // Create send task
                Task.Factory.StartNew(async() => {
                    while (true)
                    {
                        if (SendTelemetryData)
                        {
                            // Send current telemetry data
                            sendData(this.Telemetry);
                        }
                        await Task.Delay(SendTelemetryFreq);

                        if (ct.IsCancellationRequested)
                        {
                            // Cancel was called
                            Debug.WriteLine("Sending task canceled");
                            break;
                        }
                    }
                }, ct);

                // Create receive task
                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
                                var obj = DeSerialize(message.GetBytes());

                                ReceivedMessage command = new ReceivedMessage();
                                command.Name            = obj["Name"].ToString();
                                command.MessageId       = obj["MessageId"].ToString();
                                command.CreatedTime     = obj["CreatedTime"].ToString();
                                command.Parameters      = new Dictionary <string, object>();
                                foreach (dynamic param in obj["Parameters"])
                                {
                                    command.Parameters.Add(param.Name, param.Value);
                                }

                                // Invoke message received callback
                                OnReceivedMessage(new ReceivedMessageEventArgs(command));

                                // We received the message, indicate IoTHub we treated it
                                await deviceClient.CompleteAsync(message);
                            }
                            catch (Exception e)
                            {
                                // Something went wrong. Indicate the backend that we coudn't accept the message
                                Debug.WriteLine("Error while deserializing message received: " + e.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.ToString());
                deviceClient = null;
                return(false);
            }
            return(true);
        }
Ejemplo n.º 2
0
 public ReceivedMessageEventArgs(ReceivedMessage message)
 {
     Message = message;
 }