private async Task ReceiveC2dMessagesPollingAndCompleteAsync(CancellationToken ct)
        {
            Console.WriteLine($"{DateTime.Now}> Trying to receive C2D messages by polling using the ReceiveAsync() method. Press 'n' to move to the next phase.");

            while (!ct.IsCancellationRequested)
            {
                if (Console.IsInputRedirected || // the pipeline doesn't have a console or redirects console input
                    (Console.KeyAvailable &&
                     ConsoleKey.N == Console.ReadKey().Key))
                {
                    Console.WriteLine($"\n{DateTime.Now}> Ending message polling.");
                    break;
                }

                using Message receivedMessage = await _deviceClient.ReceiveAsync(ct);

                if (receivedMessage == null)
                {
                    continue;
                }

                Console.WriteLine($"{DateTime.Now}> Polling using ReceiveAsync() - received message with Id={receivedMessage.MessageId}");
                PrintMessage(receivedMessage);

                await _deviceClient.CompleteAsync(receivedMessage, ct);

                Console.WriteLine($"{DateTime.Now}> Completed C2D message with Id={receivedMessage.MessageId}.");
            }
        }
예제 #2
0
        private async Task ReceiveC2dMessagesPollingAndComplete(TimeSpan timeout)
        {
            var sw = new Stopwatch();

            sw.Start();

            Console.WriteLine($"{DateTime.Now}> Receiving C2D messages on the polling ReceiveAsync().");
            while (sw.Elapsed < timeout)
            {
                using Message receivedMessage = await _deviceClient.ReceiveAsync(timeout);

                if (receivedMessage == null)
                {
                    Console.WriteLine($"{DateTime.Now}> Polling ReceiveAsync() - no message received.");
                    await Task.Delay(s_sleepDuration);

                    continue;
                }

                Console.WriteLine($"{DateTime.Now}> Polling ReceiveAsync() - received message with Id={receivedMessage.MessageId}");
                ProcessReceivedMessage(receivedMessage);

                await _deviceClient.CompleteAsync(receivedMessage);

                Console.WriteLine($"{DateTime.Now}> Completed C2D message with Id={receivedMessage.MessageId}.");
            }

            sw.Stop();
        }
예제 #3
0
        public async void ReceiveDataFromAzure()
        {
            Message receivedMessage;
            string  messageData;

            while (true)
            {
                receivedMessage = await deviceClient.ReceiveAsync();

                if (receivedMessage != null)
                {
                    try
                    {
                        messageData = Encoding.ASCII.GetString(receivedMessage.GetBytes());

                        if (messageData == "driveGangnamStation")
                        {
                            var uri = new Uri(@"ms-drive-to:?destination.latitude=37.497942&destination.longitude=127.027621&destination.name=Gangnam Station");
                            await Launcher.LaunchUriAsync(uri);

                            await deviceClient.CompleteAsync(receivedMessage);
                        }
                        else if (messageData == "driveHancomTower")
                        {
                            var uri = new Uri(@"ms-drive-to:?destination.latitude=37.400696&destination.longitude=127.112183&destination.name=Hancom Tower");
                            await Launcher.LaunchUriAsync(uri);

                            await deviceClient.CompleteAsync(receivedMessage);
                        }
                        else if (messageData == "walkGangnamStation")
                        {
                            var uri = new Uri(@"ms-walk-to:?destination.latitude=37.497942&destination.longitude=127.027621&destination.name=Gangnam Station");
                            await Launcher.LaunchUriAsync(uri);

                            await deviceClient.CompleteAsync(receivedMessage);
                        }
                        else if (messageData == "walkHancomTower")
                        {
                            var uri = new Uri(@"ms-walk-to:?destination.latitude=37.400696&destination.longitude=127.112183&destination.name=Hancom Tower");
                            await Launcher.LaunchUriAsync(uri);

                            await deviceClient.CompleteAsync(receivedMessage);
                        }
                    }
                    catch
                    {
                        return;
                    }
                }
            }
        }
        async Task CleanupDeviceQueueAsync(string hostname, Device device)
        {
            await Task.Delay(TimeSpan.FromSeconds(1));

            DeviceClient deviceClient = null;

            try
            {
                deviceClient = DeviceClient.Create(
                    hostname,
                    new DeviceAuthenticationWithRegistrySymmetricKey(this.deviceId, device.Authentication.SymmetricKey.PrimaryKey));
                while (true)
                {
                    using (Client.Message message = await deviceClient.ReceiveAsync(TimeSpan.FromSeconds(2)))
                    {
                        if (message == null)
                        {
                            break;
                        }
                        if (message.LockToken != null)
                        {
                            await deviceClient.CompleteAsync(message.LockToken);
                        }
                    }
                }
            }
            finally
            {
                if (deviceClient != null)
                {
                    await deviceClient.CloseAsync();
                }
            }
        }
        public async Task ReceiveDataFromAzureAsync()
        {
            Message receivedMessage;
            string  messageData;

            while (true)
            {
                receivedMessage = await m_clt.ReceiveAsync();

                if (receivedMessage != null)
                {
                    messageData = Encoding.ASCII.GetString(receivedMessage.GetBytes());
                    //Wykonanie polecenia
                    if (messageData.Length >= 1)
                    {
                        await this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
                        {
                            m_col.Add(messageData);
                        });
                    }
                    //await m_deviceClient.RejectAsync(receivedMessage);
                    //await m_deviceClient.AbandonAsync(receivedMessage); - odrzuca, ale komunikat wraca
                    //Potwierdzenie wykonania
                    await m_clt.CompleteAsync(receivedMessage); //potwierdza odebranie
                }
            }
        }
예제 #6
0
        /// <summary>
        /// ReceiveCloudMessageAsync() receives a cloud message, but rather than processing the message directly it uses an event
        /// to send all listeners notification
        /// </summary>
        public static async void ReceiveCloudMessageAsync()
        {
            Console.WriteLine("\nReceiving cloud to device messages from service");
            while (true)
            {
                try
                {
                    Microsoft.Azure.Devices.Client.Message receivedMessage = await deviceClient.ReceiveAsync();

                    if (receivedMessage == null)
                    {
                        continue;
                    }

                    DeviceMessageEventArgs eventArgs = new DeviceMessageEventArgs(Encoding.ASCII.GetString(receivedMessage.GetBytes()));

                    ReceivedMessage?.Invoke(receivedMessage, eventArgs);

                    Console.WriteLine($"Received message: {eventArgs.ReceivedMessage}");

                    await deviceClient.CompleteAsync(receivedMessage);
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"{Utils.FormatExceptionMessage(ex)}");

                    throw ex;
                }
            }
        }
예제 #7
0
        async Task ReceiveCommands()
        {
            Debug.WriteLine("\nDevice waiting for commands from IoTHub...\n");
            Message receivedMessage;
            string  messageData;

            while (true)
            {
                try
                {
                    receivedMessage = await deviceClient.ReceiveAsync();

                    if (receivedMessage != null)
                    {
                        messageData             = Encoding.ASCII.GetString(receivedMessage.GetBytes());
                        txtReceivedCommand.Text = messageData;
                        Debug.WriteLine("\t{0}> Received message: {1}", DateTime.Now.ToLocalTime(), messageData);
                        await deviceClient.CompleteAsync(receivedMessage);
                    }
                }
                catch (Exception ex)
                {
                    Debug.WriteLine("IoT Hub Receive Failed.");
                    Debug.WriteLine(ex.Message);
                }
                await Task.Delay(TimeSpan.FromSeconds(10));
            }
        }
예제 #8
0
        private static async Task ReceiveMessageWithoutTimeoutCheckAsync(DeviceClient dc, TimeSpan bufferTime, MsTestLogger logger)
        {
            var sw = new Stopwatch();

            while (true)
            {
                try
                {
                    logger.Trace($"{nameof(ReceiveMessageWithoutTimeoutCheckAsync)} - Calling ReceiveAsync()");

                    sw.Restart();
                    using Client.Message message = await dc.ReceiveAsync().ConfigureAwait(false);

                    sw.Stop();

                    logger.Trace($"{nameof(ReceiveMessageWithoutTimeoutCheckAsync)} - Received message={message}; time taken={sw.ElapsedMilliseconds} ms");

                    if (message == null)
                    {
                        break;
                    }

                    await dc.CompleteAsync(message).ConfigureAwait(false);
                }
                finally
                {
                    TimeSpan maxLatency = TimeSpan.FromMilliseconds(dc.OperationTimeoutInMilliseconds) + bufferTime;
                    if (sw.Elapsed > maxLatency)
                    {
                        Assert.Fail($"ReceiveAsync did not return in {maxLatency}, instead it took {sw.Elapsed}.");
                    }
                }
            }
        }
예제 #9
0
        public async Task <string> ReceiveCommand()
        {
            Debug.WriteLine("\nDevice waiting for commands from IoTHub...\n");
            Message receivedMessage;
            string  messageData;

            while (true)
            {
                receivedMessage = await this.deviceClient.ReceiveAsync();

                if (receivedMessage != null)
                {
                    messageData = Encoding.ASCII.GetString(receivedMessage.GetBytes());
                    Debug.WriteLine("\t{0}> Received message: {1}", DateTime.Now.ToLocalTime(), messageData);

                    await deviceClient.CompleteAsync(receivedMessage);

                    return(messageData);
                }

                //  Note: In this sample, the polling interval is set to
                //  10 seconds to enable you to see messages as they are sent.
                //  To enable an IoT solution to scale, you should extend this //  interval. For example, to scale to 1 million devices, set
                //  the polling interval to 25 minutes.
                //  For further information, see
                //  https://azure.microsoft.com/documentation/articles/iot-hub-devguide/#messaging
                await Task.Delay(TimeSpan.FromSeconds(10));
            }
        }
예제 #10
0
        private async void cmd07SubscribeAndWaitForMessage_Click(object sender, RoutedEventArgs e)
        {
            DeviceClient dc = DeviceClient.CreateFromConnectionString(m_devConnection,
                                                                      Microsoft.Azure.Devices.Client.TransportType.Amqp); //MQTT - ok, but no AbadonAsync
            await dc.OpenAsync();

            Debug.WriteLine("Waiting for message!");
            bool end = false;

            while (!end)
            {
                var msg = await dc.ReceiveAsync(TimeSpan.FromSeconds(500));

                if (msg != null)
                {
                    Debug.WriteLine($"{msg.MessageId} - {Encoding.ASCII.GetString(msg.GetBytes())}");
                    if (msg.DeliveryCount > 1)
                    {
                        await dc.CompleteAsync(msg);

                        end = true;
                        Debug.WriteLine($"{msg.MessageId} - OK");
                    }
                    else
                    {
                        await dc.AbandonAsync(msg); //Not working in MQTT (due to protocol characteristics)

                        // dc.RejectAsync - doszło ale odrzycamy
                        Debug.WriteLine($"{msg.MessageId} - AbadonAsync");
                    }
                }
            }
        }
예제 #11
0
        private static async void ReceiveMessageFromCloud(object sender, DoWorkEventArgs e)
        {
            while (true)
            {
                
                var message = await deviceClient.ReceiveAsync();

                // Check if message was received
                if (message == null)
                {
                    continue;
                }

                try
                {
                    Console.WriteLine($"Command Received: {message.Properties["Command"]}");
                    var messageToSend = JsonConvert.SerializeObject(BuildResponse(message.Properties["Command"]));
                    Console.WriteLine($"Sending response: {messageToSend}");
                    await deviceClient.CompleteAsync(message);
                    Console.WriteLine("CompleteAsync Done");
                    await deviceClient.SendEventAsync(new Message(Encoding.UTF8.GetBytes(messageToSend)));
                    Console.WriteLine("Response sent");
                }
                catch (Exception exception)
                {
                    Console.WriteLine(exception);
                    await deviceClient.RejectAsync(message);
                }
            }
        }
예제 #12
0
        static async Task ReceiveCommands(DeviceClient deviceClient)
        {
            Console.WriteLine("\nDevice waiting for commands from IoTHub...\n");
            Message receivedMessage;
            string  messageData;

            while (true)
            {
                receivedMessage = await deviceClient.ReceiveAsync(TimeSpan.FromSeconds(1)).ConfigureAwait(false);

                if (receivedMessage != null)
                {
                    messageData = Encoding.ASCII.GetString(receivedMessage.GetBytes());
                    Console.WriteLine("\t{0}> Received message: {1}", DateTime.Now.ToLocalTime(), messageData);

                    int propCount = 0;
                    foreach (var prop in receivedMessage.Properties)
                    {
                        Console.WriteLine("\t\tProperty[{0}> Key={1} : Value={2}", propCount++, prop.Key, prop.Value);
                    }

                    await deviceClient.CompleteAsync(receivedMessage).ConfigureAwait(false);
                }
            }
        }
예제 #13
0
        /// <summary>
        /// Receive C2D message(running without iot edge)
        /// </summary>
        /// <param name="userContext"></param>
        /// <returns></returns>
        static async Task Receive(object userContext)
        {
            var userContextValues = userContext as Tuple <DeviceClient, Slaves.ModuleHandle>;

            if (userContextValues == null)
            {
                throw new InvalidOperationException("UserContext doesn't contain " +
                                                    "expected values");
            }
            DeviceClient ioTHubModuleClient = userContextValues.Item1;
            var          timeout            = TimeSpan.FromSeconds(3);

            while (m_run)
            {
                try
                {
                    Message message = await ioTHubModuleClient.ReceiveAsync(timeout);

                    if (message != null)
                    {
                        await PipeMessage(message, userContext);

                        await ioTHubModuleClient.CompleteAsync(message);
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine();
                    Console.WriteLine("Error when receiving: {0}", ex.Message);
                }
            }
        }
예제 #14
0
        private async void ReceiveC2dAsync()
        {
            Console.WriteLine("\nReceiving cloud to device messages from service");
            while (true)
            {
                Message receivedMessage = await deviceClient.ReceiveAsync();

                if (receivedMessage == null)
                {
                    continue;
                }

                Console.ForegroundColor = ConsoleColor.Yellow;
                var msg = Encoding.ASCII.GetString(receivedMessage.GetBytes());
                var obj = JsonConvert.DeserializeObject <DeviceCommand>(msg);
                if (obj != null)
                {
                    ChangeRGB(obj);
                }
                Console.WriteLine("Received message: {0}", msg);
                Console.ResetColor();
                await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => {
                    WriteLog("Receive Message: " + msg);
                });

                await deviceClient.CompleteAsync(receivedMessage);
            }
        }
예제 #15
0
        public async static Task ReceiveAsync(DeviceClient deviceClient)
        {
            Console.WriteLine("Device sending to messages to IoTHub...");

            // DeviceClient deviceClient = DeviceClient.CreateFromConnectionString(DeviceConnectionString, TransportType.Amqp);

            Message receivedMessage;
            string  messageData;

            while (true)
            {
                receivedMessage = deviceClient.ReceiveAsync().Result;

                if (receivedMessage != null)
                {
                    StringBuilder sb = new StringBuilder();

                    foreach (byte b in receivedMessage.GetBytes())
                    {
                        sb.Append((char)b);
                    }

                    messageData = sb.ToString();

                    // dispose string builder
                    sb = null;

                    Console.WriteLine(DateTime.Now.ToLocalTime() + "> Received message: " + messageData);

                    await deviceClient.CompleteAsync(receivedMessage);
                }
                Thread.Sleep(3000);
            }
        }
        public async void checkIoTHubForMessages()
        {
            while (true)
            {
                try
                {
                    Microsoft.Azure.Devices.Client.Message IoTMessage = await deviceClient.ReceiveAsync();

                    if (IoTMessage != null)
                    {
                        string IoTMessageString = Encoding.ASCII.GetString(IoTMessage.GetBytes());
                        Dictionary <string, string> thisIsMyProperty = new Dictionary <string, string>();
                        thisIsMyProperty.Add("source", "IoTHub");

                        // create a gateway message from IoTMessageString
                        Microsoft.Azure.Devices.Gateway.Message messageToPublish = new Microsoft.Azure.Devices.Gateway.Message("Data: " + IoTMessageString, thisIsMyProperty);

                        this.broker.Publish(messageToPublish);          // publish message
                        await deviceClient.CompleteAsync(IoTMessage);   // mark the message received

                        Console.WriteLine("received message: " + IoTMessageString);
                        Console.WriteLine(" code not implemented to handle messages.  Finish me!");
                    }
                }
                catch { }
            }
        }
예제 #17
0
        async static Task MessageReceiveLoop(CancellationToken ct)
        {
            // Main Loop
            while (!ct.IsCancellationRequested)
            {
                Message receivedMessage;
                string  messageData;

                receivedMessage = await _deviceClient.ReceiveAsync(TimeSpan.FromSeconds(30)).ConfigureAwait(false);

                if (receivedMessage != null)
                {
                    messageData = Encoding.ASCII.GetString(receivedMessage.GetBytes());
                    // Console.WriteLine("\t{0}> Received message: {1}", DateTime.Now.ToLocalTime(), messageData);
                    try
                    {
                        imageNumberNext = Convert.ToInt32(messageData, CultureInfo.InvariantCulture);
                    } catch (FormatException)
                    {
                        Console.WriteLine("Error while converting to Int\t{0}> Received message: {1}", DateTime.Now.ToLocalTime(), messageData);
                    }


                    await _deviceClient.CompleteAsync(receivedMessage).ConfigureAwait(false);
                }
            }
        }
예제 #18
0
        private async void CloudToDeviceAsync()
        {
            while (true)
            {
                try {
                    Message receivedMessage = await deviceClient.ReceiveAsync();

                    if (receivedMessage == null)
                    {
                        await Task.Delay(2000);

                        continue;
                    }

                    await deviceClient.CompleteAsync(receivedMessage);

                    string command = Encoding.ASCII.GetString(receivedMessage.GetBytes());

                    if (telemetry.SetSampleRateInSeconds(command))
                    {
                        continue;
                    }

                    T cmd = (T)Convert.ChangeType(command, typeof(T));

                    CommandReceived?.Invoke(this, new CommandEventArgs <T>(cmd));
                }
                catch { telemetry.Exceptions++; }
            }
        }
예제 #19
0
        private static void StartReceiveMessages()
        {
            receiveMessageTimer = new Timer(async(state) => {
                try
                {
                    Message receivedMessage = await deviceClient.ReceiveAsync();
                    if (receivedMessage == null)
                    {
                        return;
                    }

                    var jsonStr = Encoding.ASCII.GetString(receivedMessage.GetBytes());

                    var req = JsonConvert.DeserializeObject <AppUpdateRequest>(jsonStr);

                    await DownloadDockerImageLocallyAsync(req);

                    await TagDockerImageLocallyAsync(req);

                    await deviceClient.CompleteAsync(receivedMessage);
                }catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
            }, null, 0, 1000);
        }
예제 #20
0
        private static async Task ReceiveMessageWithTimeoutCheckAsync(DeviceClient dc, TimeSpan timeout)
        {
            while (true)
            {
                var sw = new Stopwatch();
                try
                {
                    sw.Start();
                    Client.Message message = await dc.ReceiveAsync(timeout).ConfigureAwait(false);

                    sw.Stop();

                    if (message == null)
                    {
                        break;
                    }

                    await dc.CompleteAsync(message).ConfigureAwait(false);
                }
                finally
                {
                    if (sw.Elapsed > (timeout + s_fiveSeconds))
                    {
                        Assert.Fail("ReceiveAsync did not return in Operation Timeout time.");
                    }
                }
            }
        }
예제 #21
0
        private async void MainPage_Loaded(object sender, RoutedEventArgs e)
        {
            while (true)
            {
                // Check, if new messages are available
                var message = await client.ReceiveAsync();

                if (message != null)
                {
                    // Message received
                    var content = Encoding.ASCII.GetString(message.GetBytes());
                    if (content.Equals("on"))
                    {
                        // Switch LED on
                        pin.Write(GpioPinValue.High);
                    }

                    else
                    {
                        // Switch LED off
                        pin.Write(GpioPinValue.Low);
                    }

                    // Confirm message processing
                    await client.CompleteAsync(message);
                }
            }
        }
예제 #22
0
        private static async void ReceiveC2dAsync()
        {
            Console.WriteLine("\nReceiving cloud to device messages from service");
            while (true)
            {
                Message receivedMessage = await s_deviceClient.ReceiveAsync();

                if (receivedMessage == null)
                {
                    continue;
                }

                Console.ForegroundColor = ConsoleColor.Yellow;
                var message      = Encoding.ASCII.GetString(receivedMessage.GetBytes());
                var messageArray = message.Replace(']', ',').Replace('[', ',').Replace('"', ',').Split(',', StringSplitOptions.RemoveEmptyEntries);
                var intArray     = Array.ConvertAll(messageArray, int.Parse);
                for (int i = 0; i < intArray.Length; i++)
                {
                    Console.Write(intArray[i] + " ");
                }
                Console.WriteLine();
                Console.ResetColor();

                await s_deviceClient.CompleteAsync(receivedMessage);
            }
        }
        protected async Task ReceiveMessageAsync(CancellationToken ct)
        {
            ExceptionDispatchInfo exInfo = null;

            _mRecv.ScheduleTime = null;
            _swRecv.Restart();

            try
            {
                Task <Client.Message> t = _dc.ReceiveAsync(ct);
                _mRecv.ScheduleTime = _swRecv.ElapsedMilliseconds;

                _swRecv.Restart();
                Client.Message msg = await t.ConfigureAwait(false);

                await _dc.CompleteAsync(msg).ConfigureAwait(false);

                int deviceIdFromMessage = BitConverter.ToInt32(msg.GetBytes());
                if (_id != deviceIdFromMessage)
                {
                    throw new InvalidOperationException($"DeviceId mismatch: Expected {_id} actual {deviceIdFromMessage}.");
                }
            }
            catch (Exception ex)
            {
                _mRecv.ErrorMessage = $"{ex.GetType().Name} - {ex.Message}";
                exInfo = ExceptionDispatchInfo.Capture(ex);
            }

            _mRecv.ExecuteTime = _swRecv.ElapsedMilliseconds;
            await _writer.WriteAsync(_mRecv).ConfigureAwait(false);

            exInfo?.Throw();
        }
        public async Task SignalCompletedCommand(DeserializableCommand command)
        {
            if (command == null)
            {
                throw new ArgumentNullException("command");
            }

            Debug.Assert(
                !string.IsNullOrEmpty(command.LockToken),
                "command.LockToken is a null reference or empty string.");

            await AzureRetryHelper.OperationWithBasicRetryAsync(
                async() =>
            {
                try
                {
                    await _deviceClient.CompleteAsync(command.LockToken);
                }
                catch (Exception ex)
                {
                    _logger.LogError(
                        "{0}{0}*** Exception: Complete Command ***{0}{0}Command Name: {1}{0}Command: {2}{0}Exception: {3}{0}{0}",
                        Console.Out.NewLine,
                        command.CommandName,
                        command.CommandHistory,
                        ex);
                }
            });
        }
예제 #25
0
        static async Task ReceiveCommands(DeviceClient deviceClient)
        {
            Console.WriteLine("\nDevice waiting for commands from IoTHub...\n");
            Message receivedMessage;
            string messageData;

            while (true)
            {
                receivedMessage = await deviceClient.ReceiveAsync();

                if (receivedMessage != null)
                {
                    messageData = Encoding.ASCII.GetString(receivedMessage.GetBytes());
                    Console.WriteLine("\t{0}> Received message: {1}", DateTime.Now.ToLocalTime(), messageData);

                    int propCount = 0;
                    foreach (var prop in receivedMessage.Properties)
                    {
                        Console.WriteLine("\t\tProperty[{0}> Key={1} : Value={2}", propCount++, prop.Key, prop.Value);
                    }

                    await deviceClient.CompleteAsync(receivedMessage);
                }

                //  Note: In this sample, the polling interval is set to 
                //  10 seconds to enable you to see messages as they are sent.
                //  To enable an IoT solution to scale, you should extend this //  interval. For example, to scale to 1 million devices, set 
                //  the polling interval to 25 minutes.
                //  For further information, see
                //  https://azure.microsoft.com/documentation/articles/iot-hub-devguide/#messaging
                Thread.Sleep(10000);
            }
        }
예제 #26
0
        static async Task ReceiveCommands(DeviceClient deviceClient)
        {
            Debug.WriteLine("\nDevice waiting for commands from IoTHub...\n");
            Message receivedMessage;
            string messageData;

            while (true)
            {
                receivedMessage = await deviceClient.ReceiveAsync();

                if (receivedMessage != null)
                {
                    messageData = Encoding.ASCII.GetString(receivedMessage.GetBytes());
                    Debug.WriteLine("\t{0}> Received message: {1}", DateTime.Now.ToLocalTime(), messageData);

                    await deviceClient.CompleteAsync(receivedMessage);
                }

                //  Note: In this sample, the polling interval is set to 
                //  10 seconds to enable you to see messages as they are sent.
                //  To enable an IoT solution to scale, you should extend this //  interval. For example, to scale to 1 million devices, set 
                //  the polling interval to 25 minutes.
                //  For further information, see
                //  https://azure.microsoft.com/documentation/articles/iot-hub-devguide/#messaging
                await Task.Delay(TimeSpan.FromSeconds(10));
            }
        }
예제 #27
0
        static async Task ReceiveCommands(DeviceClient deviceClient)
        {
            Console.WriteLine("\nDevice waiting for commands from IoTHub...\n");
            Message receivedMessage;
            string  messageData;

            while (true)
            {
                receivedMessage = await deviceClient.ReceiveAsync().ConfigureAwait(false);

                if (receivedMessage != null)
                {
                    messageData = Encoding.ASCII.GetString(receivedMessage.GetBytes());
                    Console.WriteLine("\t{0}> Received message: {1}", DateTime.Now.ToLocalTime(), messageData);

                    int propCount = 0;
                    foreach (var prop in receivedMessage.Properties)
                    {
                        Console.WriteLine("\t\tProperty[{0}> Key={1} : Value={2}", propCount++, prop.Key, prop.Value);
                    }

                    await deviceClient.CompleteAsync(receivedMessage).ConfigureAwait(false);
                }

                //  Note: In this sample, the polling interval is set to
                //  10 seconds to enable you to see messages as they are sent.
                //  To enable an IoT solution to scale, you should extend this //  interval. For example, to scale to 1 million devices, set
                //  the polling interval to 25 minutes.
                //  For further information, see
                //  https://azure.microsoft.com/documentation/articles/iot-hub-devguide/#messaging
                Thread.Sleep(10000);
            }
        }
예제 #28
0
        private static async Task RecieveMessageFromCloudAsync()
        {
            if (deviceClient != null)
            {
                isListening = true;
                Console.WriteLine("Listening to the Cloud for messages....");
                while (true)
                {
                    var receivedMessage = await deviceClient.ReceiveAsync();

                    if (receivedMessage == null)
                    {
                        continue;
                    }

                    var command = Encoding.ASCII.GetString(receivedMessage.GetBytes());
                    Console.ForegroundColor = ConsoleColor.Yellow;
                    Console.WriteLine($"Received message: {command}");
                    Console.ResetColor();
                    await deviceClient.CompleteAsync(receivedMessage);

                    if (command != "exit")
                    {
                        continue;
                    }
                    isListening = false;
                    Console.WriteLine("EXIT command received.  Stoping to listen...");
                    break;
                }
            }
        }
예제 #29
0
        public async void ReceiveAsync()
        {
            Console.WriteLine("\nReceiving cloud to device messages from service");
            while (true)
            {
                Message receivedMessage = await deviceClient.ReceiveAsync();

                if (receivedMessage == null)
                {
                    continue;
                }

                Console.ForegroundColor = ConsoleColor.Yellow;
                Console.WriteLine("Received message: {0}", Encoding.ASCII.GetString(receivedMessage.GetBytes()));
                Console.ResetColor();

                //FIXME:

                //Works with HTTP
                //remove the lock, remove from queue
                //await deviceClient.RejectAsync(receivedMessage);

                //successfully procedded, remove from queue

                //Works with HTTP, MQTT. AMQP QOS level 2
                await deviceClient.CompleteAsync(receivedMessage);


                //abondon
                //remove the lock, keep in the queue
                //Works with HTTP
                // await deviceClient.AbandonAsync(receivedMessage);
            }
        }
예제 #30
0
        private async Task ReceiveDataFromAzure()
        {
#if IOTHUB
            while (_azureIoTHubClient != null)
            {
                var message = await _azureIoTHubClient.ReceiveAsync();

                if (message != null)
                {
                    try
                    {
                        var msg = new Models.ReceivedMessage(message.GetBytes());
                        msg.MessageId = message.MessageId;
                        msg.Topic     = message.To;
                        DispatcherServices.Invoke(() => ReceivedMessageList.Insert(0, msg));
                        // Received a new message, display it
                        // We received the message, indicate IoTHub we treated it
                        await _azureIoTHubClient.CompleteAsync(message);
                    }
                    catch
                    {
                        await _azureIoTHubClient.RejectAsync(message);
                    }
                }
            }
#else
            await Task.FromResult(default(object));
#endif
        }
        private async Task ReceiveCommands()
        {
            Console.WriteLine("\nDevice waiting for commands from IoTHub...\n");
            Console.WriteLine("Use the IoT Hub Azure Portal to send a message to this device.\n");

            Message receivedMessage;
            string  messageData;

            receivedMessage = await _deviceClient.ReceiveAsync(TimeSpan.FromSeconds(30)).ConfigureAwait(false);

            if (receivedMessage != null)
            {
                messageData = Encoding.ASCII.GetString(receivedMessage.GetBytes());
                Console.WriteLine("\t{0}> Received message: {1}", DateTime.Now.ToLocalTime(), messageData);

                int propCount = 0;
                foreach (var prop in receivedMessage.Properties)
                {
                    Console.WriteLine("\t\tProperty[{0}> Key={1} : Value={2}", propCount++, prop.Key, prop.Value);
                }

                await _deviceClient.CompleteAsync(receivedMessage).ConfigureAwait(false);
            }
            else
            {
                Console.WriteLine("\t{0}> Timed out", DateTime.Now.ToLocalTime());
            }
        }
예제 #32
0
        //------------------------------------------------------------------------------------------------------------------------
        public async void ReceiveDataFromAzure()
        {
            Message receivedMessage;
            string  messageData;

            while (true)
            {
                receivedMessage = await deviceClient.ReceiveAsync();

                if (receivedMessage != null)
                {
                    messageData = Encoding.ASCII.GetString(receivedMessage.GetBytes());
                    await deviceClient.CompleteAsync(receivedMessage);

                    var payload = JsonConvert.DeserializeObject <AzureIOTPayoad>(messageData);
                    if (payload.ThingName == "Led")
                    {
                        led?.SetBrightness(payload.Led);
                    }
                    else if (payload.ThingName == "LCD")
                    {
                        lcd?.Display(payload.LCD, new int[] { 255, 255, 0 });
                    }
                }
            }
        }
예제 #33
0
        static async Task ReceiveCommands(DeviceClient deviceClient)
        {
            Console.WriteLine("\nDevice waiting for commands from IoTHub...\n");
            Message receivedMessage;
            string messageData;

            while (true)
            {
                receivedMessage = await deviceClient.ReceiveAsync(TimeSpan.FromSeconds(1));
                
                if (receivedMessage != null)
                {
                    messageData = Encoding.ASCII.GetString(receivedMessage.GetBytes());
                    Console.WriteLine("\t{0}> Received message: {1}", DateTime.Now.ToLocalTime(), messageData);

                    int propCount = 0;
                    foreach (var prop in receivedMessage.Properties)
                    {
                        Console.WriteLine("\t\tProperty[{0}> Key={1} : Value={2}", propCount++, prop.Key, prop.Value);
                    }

                    await deviceClient.CompleteAsync(receivedMessage);
                }
            }
        }
예제 #34
0
        static async Task ReceiveCommands(DeviceClient deviceClient)
        {
            Console.WriteLine("\nDevice waiting for commands from IoTHub...\n");
            Message receivedMessage;
            string messageData;

            while (true)
            {
                receivedMessage = await deviceClient.ReceiveAsync(TimeSpan.FromSeconds(1));
                
                if (receivedMessage != null)
                {
                    messageData = Encoding.ASCII.GetString(receivedMessage.GetBytes());
                    Console.WriteLine("\t{0}> Received message: {1}", DateTime.Now.ToLocalTime(), messageData);

                    await deviceClient.CompleteAsync(receivedMessage);
                }
            }
        }