ReceiveCloudToDeviceMessageAsync() public static method

public static ReceiveCloudToDeviceMessageAsync ( ) : Task
return Task
        static void DoReceives(CancellationToken ct, string iotHubConnectionString)
        {
            // Was cancellation already requested?
            if (ct.IsCancellationRequested == true)
            {
                Console.WriteLine("DoReceives was cancelled before it got started.");
                ct.ThrowIfCancellationRequested();
            }

            var deviceClient = DeviceClient.CreateFromConnectionString(iotHubConnectionString, TransportType.Amqp);

            while (true)
            {
                //receive cloud messages
                var rcvTask = AzureIoTHub.ReceiveCloudToDeviceMessageAsync(deviceClient);
                rcvTask.Wait(ct);
                Console.WriteLine("Received message from cloud: {0}", rcvTask.Result);

                if (ct.IsCancellationRequested)
                {
                    Console.WriteLine("Task DoReceives cancelled");
                    ct.ThrowIfCancellationRequested();
                }
            }
        }
        public MainPage()
        {
            this.InitializeComponent();

            Task.Run(
                async() =>
            {
                while (true)
                {
                    var message = await AzureIoTHub.ReceiveCloudToDeviceMessageAsync();
                    await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.High, () =>
                    {
                        textBox.Text += Environment.NewLine + message;
                        if (message.ToLower().Contains("alert"))
                        {
                            textBox1.IsEnabled = true;
                        }
                        else
                        {
                            textBox1.IsEnabled = false;
                        }
                    });
                }
            }
                );
        }
Example #3
0
        public async Task RecieveAlert()
        {
            string Alert = await AzureIoTHub.ReceiveCloudToDeviceMessageAsync();

            status.Text = Alert;
            await RecieveAlert();
        }
Example #4
0
        private async Task ListenToIot()
        {
            string msg = string.Empty;

            while (true)
            {
                try
                {
                    msg = await AzureIoTHub.ReceiveCloudToDeviceMessageAsync();

                    //await AzureIoTHub.SendDeviceToCloudMessageAsync();
                }
                catch (Exception ex)
                {
                    Debug.WriteLine(ex.Message);
                }

                if (msg.Contains("play"))
                {
                    PlayMusic();
                }
                else if (msg.Contains("stop"))
                {
                    StopMusic();
                }

                Debug.WriteLine(msg);
            }
        }
Example #5
0
        private void CheckIncomingCommand(Frame frame)
        {
            while (true)
            {
                string json = AzureIoTHub.ReceiveCloudToDeviceMessageAsync().Result;

                dynamic deserializeObject = JsonConvert.DeserializeObject(json);
                string  command           = deserializeObject.Type;

                frame.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                {
                    if (command.Equals("Timer"))
                    {
                        frame.Navigate(typeof(Timer), json);
                    }
                    else if (command.Equals("Count"))
                    {
                        frame.Navigate(typeof(Count), json);
                    }
                    else if (command.Equals("Location"))
                    {
                        frame.Navigate(typeof(Location), json);
                    }
                });
            }
        }
Example #6
0
        static void DoReceives(CancellationToken ct)
        {
            // Was cancellation already requested?
            if (ct.IsCancellationRequested == true)
            {
                Console.WriteLine("DoReceives was cancelled before it got started.");
                ct.ThrowIfCancellationRequested();
            }

            while (true)
            {
                //receive cloud messages
                var rcvTask = AzureIoTHub.ReceiveCloudToDeviceMessageAsync();
                rcvTask.Wait(ct);
                Console.WriteLine("Received message from cloud: {0}", rcvTask.Result);

//                ct.WaitHandle.WaitOne(TimeSpan.FromSeconds(5));

                if (ct.IsCancellationRequested)
                {
                    Console.WriteLine("Task DoReceives cancelled");
                    ct.ThrowIfCancellationRequested();
                }
            }
        }
        public async Task RecieveAlert()
        {
            string value = await AzureIoTHub.ReceiveCloudToDeviceMessageAsync();

            RecieveMessageStatus.Text = value;
            if (value.Equals("Capture"))
            {
                ImageCapture();
            }
            if (value.Equals("forward"))
            {
                moveforward();
            }
            if (value.Equals("backward"))
            {
                movebackward();
            }
            if (value.Equals("right"))
            {
                moveright();
            }
            if (value.Equals("left"))
            {
                moveleft();
            }
            if (value.Equals("stop"))
            {
                stop();
            }
            await RecieveAlert();
        }
        private async void SendButton_Click(object sender, RoutedEventArgs e)
        {
            AzureIoTHub.SendDeviceToCloudMessageAsync();
            var message = await AzureIoTHub.ReceiveCloudToDeviceMessageAsync();

            Debug.WriteLine("Message: " + message);
        }
Example #9
0
 private void timer_Elapsed(object sender, ElapsedEventArgs e)
 {
     Task.Run(async() =>
     {
         var message = await AzureIoTHub.ReceiveCloudToDeviceMessageAsync();
     });
 }
Example #10
0
 public void Start()
 {
     _timer          = new Timer(10 * 1000); // every 10 minutes
     _timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed);
     _timer.Start();
     Task.Run(async() => { var message = await AzureIoTHub.ReceiveCloudToDeviceMessageAsync(); });
     // write code here that runs when the Windows Service starts up.
 }
Example #11
0
        public async void listen()
        {
            while (true)
            {
                string cloudMessage = await AzureIoTHub.ReceiveCloudToDeviceMessageAsync();

                System.Diagnostics.Debug.WriteLine(cloudMessage);
            }
        }
Example #12
0
        private static async void RecieveMessageFromDevice()
        {
            await AzureIoTHub.ReceiveCloudToDeviceMessageAsync();

            // var tasks = new List<Task>();
            // //foreach (string partition in d2cPartitions)
            // //{
            //     tasks.Add(AzureIoTHub.ReceiveCloudToDeviceMessageAsync());
            //// }
            // Task.WaitAll(tasks.ToArray());
            //await AzureIoTHub.ReceiveCloudToDeviceMessageAsync();
        }
        public static async void ListenForMessages()
        {
            while (true)
            {
                string str = await AzureIoTHub.ReceiveCloudToDeviceMessageAsync();

                if (str == "Update")
                {
                    MainPage main = new MainPage();
                    main.RefreshList();
                }
            }
        }
Example #14
0
        /// <summary>
        /// Always listens for messages directly from console app
        /// </summary>
        private async Task listenForMessageFromDeviceTask()
        {
            while (true)
            {
                var msg = await AzureIoTHub.ReceiveCloudToDeviceMessageAsync();

                if (msg == null)
                {
                    continue;
                }

                Globals.ParseMsg(msg);
            }
        }
Example #15
0
        public async void ListenForMessages()
        {
            while (true)
            {
                string str = await AzureIoTHub.ReceiveCloudToDeviceMessageAsync();

                if (str == "Update")
                {
                    Debug.WriteLine("Received: " + str);
                    RefreshList();
                }
                Debug.WriteLine("Received: " + str);
            }
        }
 public MainPage()
 {
     this.InitializeComponent();
     Task.Run(
             async () => {
                 while (true)
                 {
                     var message = await AzureIoTHub.ReceiveCloudToDeviceMessageAsync();
                     await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.High, () => {
                         test.Text += Environment.NewLine + message;
                     });
                 }
             }
             );
 }
        // timer callbacks for temperature monitoring
        private async void Timer_Tick2(object sender, object e)
        {
            if (senseHat == null)
            {
                return;
            }

            // get ambient temperature from sensehat and write to log
            senseHat.Sensors.HumiditySensor.Update();

            if (senseHat.Sensors.Temperature.HasValue)
            {
                double temp = senseHat.Sensors.Temperature.Value;
                ambTemp = (int)Math.Round(temp) - 10; // temperature around sensor is higher than environment
                writeToLog("Current ambient tempeature: " + ambTemp.ToString());
            }

            string str = await AzureIoTHub.ReceiveCloudToDeviceMessageAsync();

            if (str != null)
            {
                writeToLog("Message from Azure IoT hub: " + str);
            }
        }
Example #18
0
        //public string deviceName = "MikroKopter_BT"; // Specify the device name to be selected; You can find the device name from the webb under bluetooth

        public async void Run(IBackgroundTaskInstance taskInstance)
        {
            //
            // TODO: Insert code to perform background work
            //
            // If you start any asynchronous methods here, prevent the task
            // from closing prematurely by using BackgroundTaskDeferral as
            // described in http://aka.ms/backgroundtaskdeferral
            //
            _deferral = taskInstance.GetDeferral();

            PowerManager.BatteryStatusChanged          += PowerManager_BatteryStatusChanged;
            PowerManager.PowerSupplyStatusChanged      += PowerManager_PowerSupplyStatusChanged;
            PowerManager.RemainingChargePercentChanged += PowerManager_RemainingChargePercentChanged;

            deviceId = await AzureIoTHub.TestHubConnection(false, "");

            DateTime d = DateTime.UtcNow;

            //RateSensor bs = new RateSensor();
            //bs.RateSensorInit();

            //await Task.Delay(1000);

            //bs.RateMonitorON();

            //mt = new MiotyTX();
            //mt.Init();
            //await Task.Delay(1000);

            long x = d.ToFileTime();

            if (deviceId != null)
            {
                await AzureIoTHub.SendDeviceToCloudMessageAsync("{\"pkey\":\"" + deviceId + "\", \"rkey\":\"" + x.ToString() + "\",\"status\":\"Device Restarted\"}");

                bool result = await AzureIoTHub.SendDeviceToCloudMessageAsync("Device Restarted");

                //InitAzureIotReceiver();
            }

            AzureIoTHub.counter++;

            // request access to vibration device
            //if (await VibrationDevice.RequestAccessAsync() != VibrationAccessStatus.Allowed)
            //{
            //    Debug.WriteLine("access to vibration device denied!!!!!!");
            //}

            //enable this to start periodic message to iot Hub
            this.timer = ThreadPoolTimer.CreateTimer(Timer_Tick, TimeSpan.FromSeconds(2));

            //this.fileReadTimer = ThreadPoolTimer.CreateTimer(FileReadTimer_Tick, TimeSpan.FromMilliseconds(900));

            try
            {
                await Task.Run(async() =>
                {
                    while (true)
                    {
                        string receivedMessage = null;

                        try
                        {
                            receivedMessage = await AzureIoTHub.ReceiveCloudToDeviceMessageAsync();
                            AzureIoTHub.counter++;
                        }
                        catch (Exception ex)
                        {
                            Debug.WriteLine("******ERROR RECEIVER: " + ex.Message);
                        }


                        if (receivedMessage == null)
                        {
                            continue;
                        }
                        Debug.WriteLine("Received message:" + receivedMessage);

                        JsonObject j = null;
                        try
                        {
                            j = JsonObject.Parse(receivedMessage);
                        }
                        catch
                        {
                            Debug.WriteLine(" error");
                            continue;
                        }

                        try
                        {
                            if (j.Keys.Contains("msg"))
                            {
                                string msg = j.GetNamedString("msg");
                                AzureIoTHub.counter++;
                                MessageListItem m = new MessageListItem();
                                m.message         = msg;
                                AzureIoTHub.msgList.Add(m);

                                Windows.Storage.StorageFolder storageFolder = Windows.Storage.KnownFolders.PicturesLibrary;
                                Windows.Storage.StorageFile msgFile         = await storageFolder.CreateFileAsync("message.txt", Windows.Storage.CreationCollisionOption.GenerateUniqueName);
                                await Windows.Storage.FileIO.AppendTextAsync(msgFile, msg);
                            }
                            if (j.Keys.Contains("cmd"))
                            {
                                string cmd = j.GetNamedString("cmd");
                                if (cmd == "info")
                                {
                                    await UpdateBatteryInfo();
                                }
                                if (cmd == "wake")
                                {
                                    if (ShutdownManager.IsPowerStateSupported(PowerState.ConnectedStandby))
                                    {
                                        ShutdownManager.EnterPowerState(PowerState.ConnectedStandby, TimeSpan.FromSeconds(1));
                                        //ShutdownManager.EnterPowerState(PowerState.SleepS3, TimeSpan.FromSeconds(15));
                                    }
                                }
                                if (cmd == "vibra")
                                {
                                    //try
                                    //{
                                    //    VibrationDevice VibrationDevice = await VibrationDevice.GetDefaultAsync();
                                    //    SimpleHapticsControllerFeedback BuzzFeedback = null;
                                    //    foreach (var f in VibrationDevice.SimpleHapticsController.SupportedFeedback)
                                    //    {
                                    //        if (f.Waveform == KnownSimpleHapticsControllerWaveforms.BuzzContinuous)
                                    //            BuzzFeedback = f;
                                    //    }
                                    //    if (BuzzFeedback != null)
                                    //    {
                                    //        VibrationDevice.SimpleHapticsController.SendHapticFeedbackForDuration(BuzzFeedback, 1, TimeSpan.FromMilliseconds(200));
                                    //    }
                                    //}
                                    //catch (Exception ex)
                                    //{
                                    //}
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                        }
                    }
                });
            }
            catch (Exception ex)
            {
            }


            //
            // Once the asynchronous method(s) are done, close the deferral.
            //
            //_deferral.Complete();
        }
Example #19
0
        private async void ReceiveCloudToDeviceThrottleMessage()
        {
            iotHubThresholdValue = await AzureIoTHub.ReceiveCloudToDeviceMessageAsync();

            ReceiveCloudToDeviceThrottleMessage();
        }
Example #20
0
 private async void timerTick(object sender, object e)
 {
     this.OutAzure.Text = await AzureIoTHub.ReceiveCloudToDeviceMessageAsync();
 }