Beispiel #1
1
        private void AddReportUI(BatteryReport report)
        {
            var max = Convert.ToDouble(report.FullChargeCapacityInMilliwattHours);
            var rem = Convert.ToDouble(report.RemainingCapacityInMilliwattHours);

            PowerPercent = ((rem / max) * 100).ToString("F2");
        }
        private async Task <BatteryReport> GetBatteryStatus()
        {
            string batteryStatus;
            int    batteryPercent;

            var deviceInfo = await DeviceInformation.FindAllAsync(Battery.GetDeviceSelector());

            BatteryReport br = null;

            foreach (DeviceInformation device in deviceInfo)
            {
                try
                {
                    // Create battery object
                    var battery = await Battery.FromIdAsync(device.Id);

                    // Get report
                    var report = battery.GetReport();
                    br            = report;
                    batteryStatus = report.Status.ToString();
                    if (batteryStatus == "Idle")
                    {
                        batteryStatus = PowerManager.RemainingChargePercent.ToString() + "%";
                    }
                }
                catch (Exception e)
                {
                    /* Add error handling, as applicable */
                }
            }

            batteryPercent = PowerManager.RemainingChargePercent;
            return(br);
        }
Beispiel #3
0
        public BatteryInfo(BatteryReport batteryReport)
        {
            Status = batteryReport.Status;

            switch (Status)
            {
            case BatteryStatus.NotPresent:
                StatusColor = "#777777";
                break;

            case BatteryStatus.Discharging:
                StatusColor = "#770000";
                break;

            case BatteryStatus.Idle:
                StatusColor = "#000077";
                break;

            case BatteryStatus.Charging:
                StatusColor = "#007700";
                break;

            default:
                StatusColor = "#000000";
                break;
            }

            Maximum   = batteryReport.FullChargeCapacityInMilliwattHours ?? 0;
            Remaining = batteryReport.RemainingCapacityInMilliwattHours ?? 0;
            Design    = batteryReport.DesignCapacityInMilliwattHours ?? 0;

            Percentage       = Remaining / Maximum;
            PercentageString = Percentage.ToString("P");
        }
    static void Main()
    {
        float           temperatureInput, stateOfChargeInput, chargeRateInput;
        ResourceManager resourceInfo = GetLanguageInput();

        CultureInformation.SetCultureInformation(resourceInfo);
        temperatureInput   = GetTemperatureUnit();
        stateOfChargeInput = GetStateOfChargeInput();
        chargeRateInput    = GetChargeRateInput();
        BatteryExamine batteryExamine = new BatteryExamine();
        bool           result         = batteryExamine.BatteryIsOk(new BatteryFactors(temperatureInput, stateOfChargeInput, chargeRateInput));
        BatteryParameterBreachSubject batteryParameterBreachSubject = new BatteryParameterBreachSubject();
        AccumulateBreachParameter     accumulateBreachParameter     = new AccumulateBreachParameter();

        batteryParameterBreachSubject.Attach(accumulateBreachParameter);
        batteryParameterBreachSubject.BatteryFeaturesBreachCheck(new BatteryFactors(temperatureInput, stateOfChargeInput, chargeRateInput));
        Dictionary <string, string> batteryAlertMessages = accumulateBreachParameter.GetReport();
        IReports      iReportsCosoleLogger           = new ConsoleReportLogger();
        BatteryReport batteryReportWithConsoleLogger = new BatteryReport(iReportsCosoleLogger);

        batteryReportWithConsoleLogger.ReportLogger(batteryAlertMessages);
        IReports      iReportsDummyLogger          = new DummyReportLogger();
        BatteryReport batteryReportWithDummyLogger = new BatteryReport(iReportsDummyLogger);

        batteryReportWithDummyLogger.ReportLogger(batteryAlertMessages);
    }
        /// <summary>
        /// Gets the current battery percentage.
        /// </summary>
        /// <param name="report">The battery report.</param>
        /// <returns>The battery level as a percentage.</returns>
        private static int GetPercentage(BatteryReport report)
        {
            if ((report == null) || (report.RemainingCapacityInMilliwattHours == null) || (report.FullChargeCapacityInMilliwattHours == null))
            {
                return(0);
            }

            return(Math.Min(100, Convert.ToInt32(((double)report.RemainingCapacityInMilliwattHours / (double)report.FullChargeCapacityInMilliwattHours) * 100)));
        }
Beispiel #6
0
 internal Battery(Windows.Devices.Power.Battery battery)
 {
     InternalDevice = battery;
     _Report        = InternalDevice.GetReport();
     InternalDevice.ReportUpdated += InternalDevice_ReportUpdated;
     InternalDeviceInformation     = DeviceInformation.CreateFromIdAsync(InternalDevice.DeviceId).GetResults();
     DeviceEnumerator.ConnectionStatusChangedByID += DeviceEnumerator_ConnectionStatusChangedByID;
     DeviceEnumerator.DeviceInformationUpdated    += DeviceEnumerator_DeviceInformationUpdated;
 }
Beispiel #7
0
        public EnergyPage()
        {
            InitializeComponent();
            navigationHelper = new NavigationHelper(this);

            BatteryReport batteryReport = Battery.AggregateBattery.GetReport();

            isBatteryPresent = !(batteryReport.Status == BatteryStatus.NotPresent);
        }
        /// <summary>
        /// Returns the status description.
        /// </summary>
        /// <param name="report">The battery report.</param>
        /// <returns>The status of the battery report.</returns>
        private static string GetStatusDescription(BatteryReport report)
        {
            if ((report == null) || (report.Status == BatteryStatus.NotPresent))
            {
                return(Unavailable);
            }

            return(report.Status.ToString().ToLower());
        }
Beispiel #9
0
        /// <summary>
        /// Method that updates <see cref="GenericGattCharacteristic.Value"/> with the current battery level
        /// </summary>
        private void UpdateBatteryValue()
        {
            // Get report
            BatteryReport report        = aggBattery.GetReport();
            float         fullCharge    = Convert.ToSingle(report.FullChargeCapacityInMilliwattHours);
            float         currentCharge = Convert.ToSingle(report.RemainingCapacityInMilliwattHours);

            float val = (fullCharge > 0) ? (currentCharge / fullCharge) * 100.0f : 0.0f;

            Value = GattHelper.Converters.GattConvert.ToIBuffer((byte)Math.Round(val, 0));
        }
Beispiel #10
0
        /// <summary>
        /// Get battery info from BatteryReport class
        /// </summary>
        private void GetInfoFromBatteryReport()
        {
            BatteryReport battRep = Battery.AggregateBattery.GetReport(); // get summary info of all batterys

            Type battRepType = battRep.GetType();

            PropertyInfo[] allPI = battRepType.GetProperties();

            foreach (PropertyInfo pi in allPI)
            {
                InsertPairToDictionary(pi.Name, pi.GetValue(battRep));
            }
        }
Beispiel #11
0
        public static double BatteryInfo()
        {
            Battery       b  = Battery.AggregateBattery;
            BatteryReport br = b.GetReport();

            if (br.FullChargeCapacityInMilliwattHours != null && br.RemainingCapacityInMilliwattHours != null)
            {
                double remian = Convert.ToDouble(br.RemainingCapacityInMilliwattHours);
                double full   = Convert.ToDouble(br.FullChargeCapacityInMilliwattHours);
                return(remian / full * 100);
            }
            else
            {
                return(75d);
            }
        }
        async private void RequestIndividualBatteryReports()
        {
            // Find batteries
            var deviceInfo = await DeviceInformation.FindAllAsync(Battery.GetDeviceSelector());

            foreach (DeviceInformation device in deviceInfo)
            {
                try
                {
                    // Create battery object
                    var battery = await Battery.FromIdAsync(device.Id);

                    // Get report
                    batteryReport = battery.GetReport();
                }
                catch { /* Add error handling, as applicable */ }
            }
        }
Beispiel #13
0
        private void RequestAggregateBatteryReport()
        {
            // Clear UI
            BatteryReportPanel.Children.Clear();

            Battery.AggregateBattery.ReportUpdated += AggregateBattery_ReportUpdated;

            // Create aggregate battery object
            var aggBattery = Battery.AggregateBattery;

            // Get report
            batteryReport = aggBattery.GetReport();

            // Update UI
            AddReportUIAsync(BatteryReportPanel, batteryReport, aggBattery.DeviceId);

            UpdateTileInfoAsync();
        }
Beispiel #14
0
        private async Task UpdateBatteryInfo()
        {
            BatteryReport br = await this.GetBatteryStatus();

            DateTime d = DateTime.UtcNow;
            long     x = d.ToFileTime();

            if (br == null)
            {
                await AzureIoTHub.SendDeviceToCloudMessageAsync("{\"pkey\":\"" + deviceId + "\", \"rkey\":\"" + x.ToString() + "\",\"status\":\"Idle\", \"rate\":\"0\", \"percent\":\"100\"}");
            }
            else
            {
                Debug.WriteLine(br.Status.ToString());
                Debug.WriteLine("Rate: " + br.ChargeRateInMilliwatts.Value.ToString() + "mW");
                Debug.WriteLine("Remaining: " + PowerManager.RemainingChargePercent.ToString() + "% " + PowerManager.RemainingDischargeTime.Hours.ToString() + "h " + PowerManager.RemainingDischargeTime.Minutes.ToString() + "min");
                //mt.SendData("R:"+ br.ChargeRateInMilliwatts.Value.ToString() + "P:" + PowerManager.RemainingChargePercent.ToString());

                await AzureIoTHub.SendDeviceToCloudMessageAsync("{\"pkey\":\"" + deviceId + "\", \"rkey\":\"" + x.ToString() + "\",\"status\":\"" + br.Status.ToString() + "\", \"rate\":\"" + br.ChargeRateInMilliwatts.Value.ToString() + "\", \"percent\":\"" + PowerManager.RemainingChargePercent.ToString() + "\"}");
            }//ScreenCapture screen = ScreenCapture.GetForCurrentView();
        }
        /// <summary>
        /// Gets the aggregate battery status
        /// </summary>
        private void GetAggregateBatteryStatus(BatteryReport report)
        {
            // Check if the aggregate report object is null
            if (report == null)
            {
                return;
            }

            // Set properties
            DesignCap     = report.DesignCapacityInMilliwattHours;
            FullChargeCap = report.FullChargeCapacityInMilliwattHours;
            RemainingCap  = report.RemainingCapacityInMilliwattHours;
            ChargeRate    = report.ChargeRateInMilliwatts;
            BatteryStatus = report.Status;

            // Add to charge data
            ChargeData.Add(new ChargeDetail()
            {
                Time  = DateTime.Now,
                Value = report.ChargeRateInMilliwatts
            });
        }
Beispiel #16
0
        /// <summary>
        /// Updates the local settings based on the current battery report.
        /// </summary>
        /// <param name="report">The current battery report.</param>
        public void Update(BatteryReport report)
        {
            lock (_lock)
            {
                if ((report == null) || (report.Status != BatteryStatus.Discharging) || (report.RemainingCapacityInMilliwattHours == null))
                {
                    Remove();
                    return;
                }

                var localSettings = ApplicationData.Current.LocalSettings;
                var time          = localSettings.Values[Time];
                var level         = localSettings.Values[BatteryLevel];

                if ((time == null) || (level == null))
                {
                    localSettings.Values[Time]         = DateTime.Now.ToString();
                    localSettings.Values[BatteryLevel] = report.RemainingCapacityInMilliwattHours.Value;

                    return;
                }

                var snapshotTime = DateTime.Parse(time.ToString());
                var elapsed      = DateTime.Now - snapshotTime;
                var discharged   = (int)level - report.RemainingCapacityInMilliwattHours.Value;

                if ((elapsed.TotalSeconds < 60) || (discharged == 0))
                {
                    return;
                }

                var mwps     = ((double)discharged / elapsed.TotalSeconds);
                var estimate = ((double)report.RemainingCapacityInMilliwattHours.Value / mwps);
                var display  = string.Format("{0:dd\\.hh\\:mm}", TimeSpan.FromSeconds(estimate));

                localSettings.Values[EstimatedTime] = display;
            }
        }
        private void UpdateDynamicSystemData()
        {
            DynamicSystemData = new DynamicSystemInfo();

            try
            {
                MEMORYSTATUSEX memoryStatus = new MEMORYSTATUSEX();
                GlobalMemoryStatusEx(memoryStatus);
                DynamicSystemData.PhysicalMemory       = $"total = {memoryStatus.ullTotalPhys / GB:N2} GB, available = {memoryStatus.ullAvailPhys / GB:N2} GB";
                DynamicSystemData.PhysicalPlusPagefile = $"total = {memoryStatus.ullTotalPageFile / GB:N2} GB, available = {memoryStatus.ullAvailPageFile / GB:N2} GB";
                DynamicSystemData.VirtualMemory        = $"total = {memoryStatus.ullTotalVirtual / GB:N2} GB, available = {memoryStatus.ullAvailVirtual / GB:N2} GB";
                ulong pageFileOnDisk = memoryStatus.ullTotalPageFile - memoryStatus.ullTotalPhys;
                DynamicSystemData.PagefileOnDisk = $"{pageFileOnDisk / GB:N2} GB";
                DynamicSystemData.MemoryLoad     = $"{memoryStatus.dwMemoryLoad}%";
            }
            catch (Exception ex)
            {
                App.AnalyticsWriteLine("MainPage.UpdateDynamicSystemData", "MEMORYSTATUSEX", ex.Message);
            }

            bool isBatteryAvailable = true;

            try
            {
                SYSTEM_POWER_STATUS powerStatus = new SYSTEM_POWER_STATUS();
                GetSystemPowerStatus(ref powerStatus);
                DynamicSystemData.ACLineStatus = powerStatus.ACLineStatus.ToString();

                DynamicSystemData.BatteryChargeStatus = $"{powerStatus.BatteryChargeStatus:G}";
                if (powerStatus.BatteryChargeStatus == BatteryFlag.NoSystemBattery ||
                    powerStatus.BatteryChargeStatus == BatteryFlag.Unknown)
                {
                    isBatteryAvailable            = false;
                    DynamicSystemData.BatteryLife = "n/a";
                }
                else
                {
                    DynamicSystemData.BatteryLife = $"{powerStatus.BatteryLifePercent}%";
                }
                DynamicSystemData.BatterySaver = powerStatus.BatterySaver.ToString();
            }
            catch (Exception ex)
            {
                App.AnalyticsWriteLine("MainPage.UpdateDynamicSystemData", "SYSTEM_POWER_STATUS", ex.Message);
            }

            if (isBatteryAvailable)
            {
                try
                {
                    Battery       battery       = Battery.AggregateBattery;
                    BatteryReport batteryReport = battery.GetReport();
                    DynamicSystemData.ChargeRate = $"{batteryReport.ChargeRateInMilliwatts:N0} mW";
                    DynamicSystemData.Capacity   =
                        $"design = {batteryReport.DesignCapacityInMilliwattHours:N0} mWh, " +
                        $"full = {batteryReport.FullChargeCapacityInMilliwattHours:N0} mWh, " +
                        $"remaining = {batteryReport.RemainingCapacityInMilliwattHours:N0} mWh";
                }
                catch (Exception ex)
                {
                    App.AnalyticsWriteLine("MainPage.UpdateDynamicSystemData", "BatteryReport", ex.Message);
                }
            }
            else
            {
                DynamicSystemData.ChargeRate = "n/a";
                DynamicSystemData.Capacity   = "n/a";
            }

            try
            {
                ulong freeBytesAvailable;
                ulong totalNumberOfBytes;
                ulong totalNumberOfFreeBytes;

                // You can only specify a folder path that this app can access, but you can
                // get full disk information from any folder path.
                IStorageFolder appFolder = ApplicationData.Current.LocalFolder;
                GetDiskFreeSpaceEx(appFolder.Path, out freeBytesAvailable, out totalNumberOfBytes, out totalNumberOfFreeBytes);
                DynamicSystemData.TotalDiskSize = $"{totalNumberOfBytes / GB:N2} GB";
                DynamicSystemData.DiskFreeSpace = $"{freeBytesAvailable / GB:N2} GB";
            }
            catch (Exception ex)
            {
                App.AnalyticsWriteLine("MainPage.UpdateDynamicSystemData", "GetDiskFreeSpaceEx", ex.Message);
            }

            try
            {
                IntPtr infoPtr = IntPtr.Zero;
                uint   infoLen = (uint)Marshal.SizeOf <FIXED_INFO>();
                int    ret     = -1;

                while (ret != ERROR_SUCCESS)
                {
                    infoPtr = Marshal.AllocHGlobal(Convert.ToInt32(infoLen));
                    ret     = GetNetworkParams(infoPtr, ref infoLen);
                    if (ret == ERROR_BUFFER_OVERFLOW)
                    {
                        // Try again with a bigger buffer.
                        Marshal.FreeHGlobal(infoPtr);
                        continue;
                    }
                }

                FIXED_INFO info = Marshal.PtrToStructure <FIXED_INFO>(infoPtr);
                DynamicSystemData.DomainName = info.DomainName;

                string nodeType = string.Empty;
                switch (info.NodeType)
                {
                case BROADCAST_NODETYPE:
                    nodeType = "Broadcast";
                    break;

                case PEER_TO_PEER_NODETYPE:
                    nodeType = "Peer to Peer";
                    break;

                case MIXED_NODETYPE:
                    nodeType = "Mixed";
                    break;

                case HYBRID_NODETYPE:
                    nodeType = "Hybrid";
                    break;

                default:
                    nodeType = $"Unknown ({info.NodeType})";
                    break;
                }
                DynamicSystemData.NodeType = nodeType;
            }
            catch (Exception ex)
            {
                App.AnalyticsWriteLine("MainPage.UpdateDynamicSystemData", "GetNetworkParams", ex.Message);
            }

            try
            {
                ConnectionProfile profile = NetworkInformation.GetInternetConnectionProfile();
                DynamicSystemData.ConnectedProfile = profile.ProfileName;

                NetworkAdapter internetAdapter = profile.NetworkAdapter;
                DynamicSystemData.IanaInterfaceType = $"{(IanaInterfaceType)internetAdapter.IanaInterfaceType}";
                DynamicSystemData.InboundSpeed      = $"{internetAdapter.InboundMaxBitsPerSecond / MBPS:N0} Mbps";
                DynamicSystemData.OutboundSpeed     = $"{internetAdapter.OutboundMaxBitsPerSecond / MBPS:N0} Mbps";

                IReadOnlyList <HostName> hostNames = NetworkInformation.GetHostNames();
                HostName connectedHost             = hostNames.Where
                                                         (h => h.IPInformation != null &&
                                                         h.IPInformation.NetworkAdapter != null &&
                                                         h.IPInformation.NetworkAdapter.NetworkAdapterId == internetAdapter.NetworkAdapterId)
                                                     .FirstOrDefault();
                if (connectedHost != null)
                {
                    DynamicSystemData.HostAddress = connectedHost.CanonicalName;
                    DynamicSystemData.AddressType = connectedHost.Type.ToString();
                }
            }
            catch (Exception ex)
            {
                App.AnalyticsWriteLine("MainPage.UpdateDynamicSystemData", "GetInternetConnectionProfile", ex.Message);
            }

            dynamicDataGrid.DataContext = DynamicSystemData;
        }
Beispiel #18
0
        private void SetTemplate()
        {
            ReaderContext           = new ReaderView();
            ContentGrid.DataContext = ReaderContext;
            ContextGrid.DataContext = new ESContext();

            RBgContext            = new BgContext(GRConfig.ContentReader.BgContext);
            ContentBg.DataContext = RBgContext;

            RBgContext.ApplyBackgrounds();

            if (Paragraph.Translator == null)
            {
                Paragraph.Translator = new libtranslate.Translator();
            }

            StringResources stx = StringResources.Load("Settings");

            ExpContent = new Paragraph[]
            {
                new Paragraph(stx.Text("Appearance_ContentReader_Exp1"))
                , new Paragraph(stx.Text("Appearance_ContentReader_Exp2"))
                , new Paragraph(stx.Text("Appearance_ContentReader_Exp3"))
                , new Paragraph(stx.Text("Appearance_ContentReader_Exp4"))
            };

            XTitleStepper.Text = YTitleStepper.Text = stx.Text("Appearance_ContentReader_Exp2");

            ColorList.ItemsSource = new ColorItem[]
            {
                new ColorItem(
                    stx.Text("Appearance_ContentReader_Background")
                    , GRConfig.ContentReader.BackgroundColor
                    )
                {
                    BindAction = (c) => {
                        GRConfig.ContentReader.BackgroundColor = c;
                        UpdateExampleFc();
                    }
                }

                , new ColorItem(
                    stx.Text("Appearance_ContentReader_ScrollBar")
                    , GRConfig.ContentReader.ScrollBarColor
                    )
                {
                    BindAction = (c) => {
                        GRConfig.ContentReader.ScrollBarColor = c;
                        UpdateScrollBar();
                    }
                }

                , new ColorItem(
                    stx.Text("Appearance_ContentReader_FontColor")
                    , GRConfig.ContentReader.FontColor
                    )
                {
                    BindAction = (c) => { GRConfig.ContentReader.FontColor = c; }
                }

                , new ColorItem(
                    stx.Text("Appearance_ContentReader_TapBrushColor")
                    , GRConfig.ContentReader.TapBrushColor
                    )
                {
                    BindAction = (c) => { GRConfig.ContentReader.TapBrushColor = c; }
                }

                , new ColorItem(
                    stx.Text("Appearance_ContentReader_NavBg")
                    , GRConfig.ContentReader.BgColorNav
                    )
                {
                    BindAction = (c) => { GRConfig.ContentReader.BgColorNav = c; }
                }

                , new ColorItem(
                    stx.Text("Appearance_ContentReader_AssistHelper")
                    , GRConfig.ContentReader.BgColorAssist
                    )
                {
                    BindAction = (c) => { GRConfig.ContentReader.BgColorAssist = c; }
                }
            };

            ClockColorList.ItemsSource = new ColorItem[]
            {
                new ColorItem(
                    stx.Text("Appearance_ContentReader_Clock_ARColor")
                    , GRConfig.ContentReader.Clock.ARColor
                    )
                {
                    BindAction = (c) => { GRConfig.ContentReader.Clock.ARColor = c; }
                }

                , new ColorItem(
                    stx.Text("Appearance_ContentReader_Clock_HHColor")
                    , GRConfig.ContentReader.Clock.HHColor
                    )
                {
                    BindAction = (c) => { GRConfig.ContentReader.Clock.HHColor = c; }
                }

                , new ColorItem(
                    stx.Text("Appearance_ContentReader_Clock_MHColor")
                    , GRConfig.ContentReader.Clock.MHColor
                    )
                {
                    BindAction = (c) => { GRConfig.ContentReader.Clock.MHColor = c; }
                }

                , new ColorItem(
                    stx.Text("Appearance_ContentReader_Clock_SColor")
                    , GRConfig.ContentReader.Clock.SColor
                    )
                {
                    BindAction = (c) => { GRConfig.ContentReader.Clock.SColor = c; }
                }

                , new ColorItem(
                    stx.Text("Appearance_ContentReader_EStepper_DColor")
                    , GRConfig.ContentReader.EpStepper.DColor
                    )
                {
                    BindAction = (c) => { GRConfig.ContentReader.EpStepper.DColor = c; }
                }

                , new ColorItem(
                    stx.Text("Appearance_ContentReader_EStepper_SColor")
                    , GRConfig.ContentReader.EpStepper.SColor
                    )
                {
                    BindAction = (c) => { GRConfig.ContentReader.EpStepper.SColor = c; }
                }

                , new ColorItem(
                    stx.Text("Appearance_ContentReader_Background")
                    , GRConfig.ContentReader.EpStepper.BackgroundColor
                    )
                {
                    BindAction = (c) => { GRConfig.ContentReader.EpStepper.BackgroundColor = c; }
                }
            };

            BatteryReport Report = Battery.AggregateBattery.GetReport();

            if (Report.RemainingCapacityInMilliwattHours != null)
            {
                YClock.Progress
                      = XClock.Progress
                      = ( float )Report.RemainingCapacityInMilliwattHours / ( float )Report.FullChargeCapacityInMilliwattHours;
            }

            SSliders[FontSizeInput.Name]    = FontSizeSlider;
            SSliders[BlockHeightInput.Name] = BlockHeightSlider;
            SSliders[LineSpacingInput.Name] = LineSpacingSlider;
            SSliders[ParaSpacingInput.Name] = ParaSpacingSlider;

            FontSizeSlider.Value    = GRConfig.ContentReader.FontSize;
            LineSpacingSlider.Value = GRConfig.ContentReader.LineHeight;
            ParaSpacingSlider.Value = 2 * GRConfig.ContentReader.ParagraphSpacing;

            FontSizeInput.Text    = FontSizeSlider.Value.ToString();
            LineSpacingInput.Text = LineSpacingSlider.Value.ToString();
            ParaSpacingInput.Text = ParaSpacingSlider.Value.ToString();

            double BlockHeight = GRConfig.ContentReader.BlockHeight;

            if (0 < BlockHeight)
            {
                BlockHeightSlider.Value = BlockHeight;
            }

            FontWeight FWeight = GRConfig.ContentReader.FontWeight;
            // Set font weights
            Dictionary <string, FontWeight> ForReflection = new Dictionary <string, FontWeight>()
            {
                { "Thin", FontWeights.Thin }
                , { "ExtraLight", FontWeights.ExtraLight }
                , { "Light", FontWeights.Light }
                , { "SemiLight", FontWeights.SemiLight }
                , { "Normal", FontWeights.Normal }
                , { "Medium", FontWeights.Medium }
                , { "SemiBold", FontWeights.SemiBold }
                , { "Bold", FontWeights.Bold }
                , { "ExtraBold", FontWeights.ExtraBold }
                , { "Black", FontWeights.Black }
                , { "ExtraBlack", FontWeights.ExtraBlack }
            };

            Logger.Log(ID, "Default FontWeight is " + FWeight.Weight);
            List <PInfoWrapper> PIW = new List <PInfoWrapper>();

            foreach (KeyValuePair <string, FontWeight> K in ForReflection)
            {
                PInfoWrapper PWrapper = new PInfoWrapper(K.Key, K.Value);
                PIW.Add(PWrapper);
            }
            FontWeightCB.ItemsSource = PIW;

            FontWeightCB.SelectedItem = PIW.First(x => x.Weight.Weight == FWeight.Weight);

            YClock.Time      = XClock.Time = DateTime.Now;
            XDayofWeek.Text  = YDayofWeek.Text = YClock.Time.ToString("dddd");
            XDayofMonth.Text = YDayofMonth.Text = YClock.Time.Day.ToString();
            XMonth.Text      = YMonth.Text = YClock.Time.ToString("MMMM");

            SetLayoutAware();

            UpdateExampleLs();
            UpdateExamplePs();
            UpdateExampleFc();
            UpdateExampleFs();
            UpdateExampleBh();

            for (int i = 0; i < 3; i++)
            {
                var j = ContentGrid.Dispatcher.RunIdleAsync((x) =>
                {
                    UpdateExampleFs();
                    UpdateExampleBh();
                });
            }
        }
 private  void AddReportUI(BatteryReport report)
 {
     var max = Convert.ToDouble(report.FullChargeCapacityInMilliwattHours);
     var rem = Convert.ToDouble(report.RemainingCapacityInMilliwattHours);
     PowerPercent = ((rem / max) * 100).ToString("F2");
 }
Beispiel #20
0
        private void AddReportUI(StackPanel sp, BatteryReport report, string DeviceID)
        {
            // Create battery report UI
            TextBlock txt1 = new TextBlock {
                Text = "Device ID: " + DeviceID
            };

            txt1.FontSize     = 15;
            txt1.Margin       = new Thickness(0, 15, 0, 0);
            txt1.TextWrapping = TextWrapping.WrapWholeWords;

            TextBlock txt2 = new TextBlock {
                Text = "Battery status: " + report.Status.ToString()
            };

            txt2.FontStyle = Windows.UI.Text.FontStyle.Italic;
            txt2.Margin    = new Thickness(0, 0, 0, 15);

            TextBlock txt3 = new TextBlock {
                Text = "Charge rate (mW): " + report.ChargeRateInMilliwatts.ToString()
            };
            TextBlock txt4 = new TextBlock {
                Text = "Design energy capacity (mWh): " + report.DesignCapacityInMilliwattHours.ToString()
            };
            TextBlock txt5 = new TextBlock {
                Text = "Fully-charged energy capacity (mWh): " + report.FullChargeCapacityInMilliwattHours.ToString()
            };
            TextBlock txt6 = new TextBlock {
                Text = "Remaining energy capacity (mWh): " + report.RemainingCapacityInMilliwattHours.ToString()
            };

            // Create energy capacity progress bar & labels
            TextBlock pbLabel = new TextBlock {
                Text = "Percent remaining energy capacity"
            };

            pbLabel.Margin     = new Thickness(0, 10, 0, 5);
            pbLabel.FontFamily = new FontFamily("Segoe UI");
            pbLabel.FontSize   = 11;

            ProgressBar pb = new ProgressBar();

            pb.Margin              = new Thickness(0, 5, 0, 0);
            pb.Width               = 200;
            pb.Height              = 10;
            pb.IsIndeterminate     = false;
            pb.HorizontalAlignment = HorizontalAlignment.Left;

            TextBlock pbPercent = new TextBlock();

            pbPercent.Margin     = new Thickness(0, 5, 0, 10);
            pbPercent.FontFamily = new FontFamily("Segoe UI");
            pbLabel.FontSize     = 11;

            // Disable progress bar if values are null
            if ((report.FullChargeCapacityInMilliwattHours == null) ||
                (report.RemainingCapacityInMilliwattHours == null))
            {
                pb.IsEnabled   = false;
                pbPercent.Text = "N/A";
            }
            else
            {
                pb.IsEnabled   = true;
                pb.Maximum     = Convert.ToDouble(report.FullChargeCapacityInMilliwattHours);
                pb.Value       = Convert.ToDouble(report.RemainingCapacityInMilliwattHours);
                pbPercent.Text = ((pb.Value / pb.Maximum) * 100).ToString("F2") + "%";
            }

            // Add controls to stackpanel
            sp.Children.Add(txt1);
            sp.Children.Add(txt2);
            sp.Children.Add(txt3);
            sp.Children.Add(txt4);
            sp.Children.Add(txt5);
            sp.Children.Add(txt6);
            sp.Children.Add(pbLabel);
            sp.Children.Add(pb);
            sp.Children.Add(pbPercent);
        }
Beispiel #21
0
 private void InternalDevice_ReportUpdated(Windows.Devices.Power.Battery sender, object args)
 {
     _Report = InternalDevice.GetReport();
 }
 /// <summary>
 /// Calculate in how long will it take to charge or discharge a battery with set capacity and current charge rate.
 /// NOTE: Charge is negative when discharging!
 /// </summary>
 /// <param name="report">Battery report</param>
 /// <param name="capacityInMiliwattHours">Capacity used for calculating charge/discharge time</param>
 /// <returns>Returns how long it will take to charge or discharge in hours. Positive number is charging and negative is discharging.</returns>
 private static double CalculateHoursLeft(BatteryReport report, double capacityInMiliwattHours)
     => capacityInMiliwattHours / report.ChargeRateInMilliwatts.Value;
        private void UpdateTileInfo(BatteryReport batteryReport) //TODO add report as param instead of global variable laziness
        {
            string from = ((Convert.ToDouble(batteryReport.RemainingCapacityInMilliwattHours) / Convert.ToDouble(batteryReport.FullChargeCapacityInMilliwattHours)) * 100).ToString("F2") + " % ";

            string subject = batteryReport.Status.ToString();
            string body    = batteryReport.ChargeRateInMilliwatts.ToString() + "mW";
            string footer  = DateTime.Now.ToString();


            // Construct the tile content
            TileContent content = new TileContent()
            {
                Visual = new TileVisual()
                {
                    TileMedium = new TileBinding()
                    {
                        Content = new TileBindingContentAdaptive()
                        {
                            Children =
                            {
                                new AdaptiveText()
                                {
                                    Text = from
                                },

                                new AdaptiveText()
                                {
                                    Text = subject,
                                    //HintStyle = AdaptiveTextStyle.CaptionSubtle
                                },

                                new AdaptiveText()
                                {
                                    Text = body,
                                    //HintStyle = AdaptiveTextStyle.CaptionSubtle
                                },

                                new AdaptiveText()
                                {
                                    Text      = footer,
                                    HintStyle = AdaptiveTextStyle.CaptionSubtle
                                }
                            }
                        }
                    },

                    TileWide = new TileBinding()
                    {
                        Content = new TileBindingContentAdaptive()
                        {
                            Children =
                            {
                                new AdaptiveText()
                                {
                                    Text      = from,
                                    HintStyle = AdaptiveTextStyle.Subtitle
                                },

                                new AdaptiveText()
                                {
                                    Text      = subject,
                                    HintStyle = AdaptiveTextStyle.CaptionSubtle
                                },

                                new AdaptiveText()
                                {
                                    Text      = body,
                                    HintStyle = AdaptiveTextStyle.CaptionSubtle
                                }
                            }
                        }
                    }
                }
            };

            TileNotification notification = new TileNotification(content.GetXml());

            notification.ExpirationTime = DateTimeOffset.UtcNow.AddMinutes(15);
            TileUpdateManager.CreateTileUpdaterForApplication().Update(notification);
        }
Beispiel #24
0
        private void AddReportUI(BatteryReport report, string DeviceID)
        {
            // Create battery report UI
            TextBlock txt1 = new TextBlock { Text = "Device ID: " + DeviceID };
            txt1.FontSize = 15;
            txt1.Margin = new Thickness(0, 15, 0, 0);
            txt1.TextWrapping = TextWrapping.WrapWholeWords;
            if((report.Status.ToString()).ToLower() == "charging")
            {
                batteryStateText.Text = "Charging";
                //chargingORdischarging.Text = "Charging";
                //batteryStatus.Text = "Charging";
                toWhatState.Text = "to charge";
                double diff = ((((double)report.FullChargeCapacityInMilliwattHours) / 3.8) - (((double)report.RemainingCapacityInMilliwattHours) / 3.8));
                if (diff == 0)
                {
                    batteryStateText.Text = "Charged";
                    //batteryStatus.Text = "Charged";
                    //chargingORdischarging.Text = "Charged";
                    toWhatState.Opacity = 0;
                    //timeToCharge.Text = "";
                    //timeToCharge.Opacity = 0;
                }
                else
                {
                    double time_to_charge = Math.Abs( ((diff)) / ((double)report.ChargeRateInMilliwatts / 3.8));
                    string hours = ((int)time_to_charge).ToString();
                    string minutes = ((int)((time_to_charge - (int)time_to_charge) * 60)).ToString();
                    if (hours == "0")
                    {
                        //timeToCharge.Text = minutes + " min ";
                        timeInWords.Text = minutes + " min ";
                    }
                    else
                    {
                        //timeToCharge.Text = hours + " h " + minutes + " min ";
                        timeInWords.Text = hours + " h " + minutes + " min ";
                    }
                }
                
            }
            else
            {
                batteryStateText.Text = report.Status.ToString();
                //batteryStatus.Text = report.Status.ToString();
                //chargingORdischarging.Text = report.Status.ToString();
                toWhatState.Text = "to discharge";
                double time_to_charge = Math.Abs((((double)report.RemainingCapacityInMilliwattHours)/3.8) / ((double)report.ChargeRateInMilliwatts / 3.8));
                Debug.WriteLine("Discharge : Time to discharge : " + time_to_charge);
                string hours = ((int)time_to_charge).ToString();
                string minutes = ((int)((time_to_charge - (int)time_to_charge)* 60)).ToString();
                if (hours == "0")
                {
                    //timeToCharge.Text = minutes + " min ";
                    timeInWords.Text = minutes + " min ";
                }
                else
                {
                    //timeToCharge.Text = hours + " h " + minutes + " min ";
                    timeInWords.Text = hours + " h " + minutes + " min ";
                }

            }
            chargingpercentage.Text = ((int)((Convert.ToDouble(report.RemainingCapacityInMilliwattHours) / (Convert.ToDouble(report.FullChargeCapacityInMilliwattHours))) * 100)).ToString();
            //chargingRate.Text = ((int)(report.ChargeRateInMilliwatts / 3.8)).ToString() + "mA";
            chargingRatemA.Text = (report.ChargeRateInMilliwatts / 3.8).ToString();
            chargingRatemW.Text = (report.ChargeRateInMilliwatts).ToString();
            Debug.WriteLine(report.ChargeRateInMilliwatts);
            
            
            //fullEnergyCapacitymAH.Text = ((report.FullChargeCapacityInMilliwattHours)/3.8).ToString();
            //fullEnergyCapacitymWH.Text = ((report.FullChargeCapacityInMilliwattHours)).ToString();

            //remainingEnergyCapacitymWH.Text = (report.RemainingCapacityInMilliwattHours).ToString();
            //remainingEnergyCapacitymAH.Text = ((report.RemainingCapacityInMilliwattHours) / 3.8).ToString();
            //batteryPercent.Text = ((int)((Convert.ToDouble(report.RemainingCapacityInMilliwattHours) / (Convert.ToDouble(report.FullChargeCapacityInMilliwattHours))) * 100)).ToString("F2") + "%";
            
        }