示例#1
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();
        }