Exemple #1
0
        private void DeviceInstanceReceivedMessage(object sender, EventArgs e)
        {
            C2DMessage message       = ((ReceivedMessageEventArgs)e).Message;
            var        textToDisplay = message.timecreated + " - Alert received:" + message.message + ": " + message.value + " " + message.unitofmeasure;

            this.BeginInvoke(new AppendAlert(Target), textToDisplay);
        }
Exemple #2
0
 /// <summary>
 /// CTD_ReceivedMessage
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 private async void CTD_ReceivedMessage(object sender, EventArgs e)
 {
     await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
     {
         C2DMessage message = ((ConnectTheDots.ReceivedMessageEventArgs)e).Message;
         var textToDisplay  = message.timecreated + " - Alert received:" + message.message + ": " + message.value + " " + message.unitofmeasure + "\r\n";
         TBAlerts.Text     += textToDisplay;
     });
 }
Exemple #3
0
        private void DeviceInstance_SentMessageEventHandlerBacNet(object sender, EventArgs e)
        {
            C2DMessage message = ((ReceivedMessageEventArgs)e).Message;

            if (sendFrequency.Value >= 1000 || SentMessagesCount % 10 == 0 || message.alerttype.ToLower() == "error")
            {
                if (message.alerttype.ToLower() == "error")
                {
                    errorsList.AppendLine(message.message);
                }
                this.BeginInvoke(new AppendAlert(Target), message.alerttype + " - " + message.message);
            }

            SentMessagesCount++;
        }
Exemple #4
0
        private static async Task ReceiveC2dAsync(CancellationToken ct)
        {
            //Console.WriteLine("\nReceiving cloud to device messages from service");
            while (!ct.IsCancellationRequested)
            {
                Message receivedMessage = await deviceClient.ReceiveAsync();

                if (receivedMessage == null)
                {
                    continue;
                }

                string     content = Encoding.ASCII.GetString(receivedMessage.GetBytes());
                C2DMessage message = null;
                try
                {
                    message = JsonConvert.DeserializeObject <C2DMessage>(content);
                } catch (JsonSerializationException)
                {
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine("ERROR: Invalid message received!");
                    Console.ResetColor();

                    await deviceClient.CompleteAsync(receivedMessage);

                    continue;
                }

                if (string.IsNullOrWhiteSpace(message.From))
                {
                    await deviceClient.CompleteAsync(receivedMessage);

                    continue;
                }

                Console.ForegroundColor = ConsoleColor.Yellow;
                Console.WriteLine("Hello " + message.From);
                Console.ResetColor();

                await deviceClient.CompleteAsync(receivedMessage);
            }
        }
Exemple #5
0
        static void Main(string[] args)
        {
            Console.WriteLine("Send Cloud-to-Device message\n");
            serviceClient = ServiceClient.CreateFromConnectionString(Config.IotHub.ConnectionStringService);

            Console.WriteLine("Press any key to send a C2D message.");
            Console.ReadLine();
            var msg = new C2DMessage {
                From = "Raffaele"
            };

            SendCloudToDeviceMessageAsync(msg).Wait();
            Console.WriteLine("Message sent!");

            var info = GetInfoAsync().Result;

            Console.WriteLine(info);

            ShutDown().Wait();

            Console.ReadLine();
        }
Exemple #6
0
 private async static Task SendCloudToDeviceMessageAsync(C2DMessage msg)
 {
     var commandMessage = new Message(Encoding.ASCII.GetBytes(JsonConvert.SerializeObject(msg)));
     await serviceClient.SendAsync(Config.DeviceId, commandMessage);
 }
Exemple #7
0
        public bool Connect(string connectionString)
        {
            try
            {
                if (Connected)
                {
                    Disconnect();
                }
                while (!cancelledReceiver || !cancelledReceiver)
                {
                    Thread.Sleep(SendTelemetryFreq);
                }
                // Create Azure IoT Hub Client and open messaging channel
                _deviceClient = DeviceClient.CreateFromConnectionString(connectionString, TransportType.Http1);
                _deviceClient.OpenAsync();
                Connected = true;

                // Create send and receive tasks
                CancellationToken ct = _tokenSource.Token;
                Task.Factory.StartNew(async() => {
                    while (Connected)
                    {
                        await SendData();
                        await Task.Delay(SendTelemetryFreq);

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

                Task.Factory.StartNew(async() =>
                {
                    while (Connected)
                    {
                        // 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 (Exception e)
                            {
                                // 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", "DE");
                            cancelledReceiver = true;
                            break;
                        }
                    }
                }, ct);
            }
            catch (Exception e)
            {
                Debug.WriteLine("Error while trying to connect to IoT Hub: " + e.Message, "DE");
                _deviceClient = null;
                return(false);
            }
            return(true);
        }
Exemple #8
0
 public ReceivedMessageEventArgs(C2DMessage message)
 {
     Message = message;
 }