/// <summary> /// Update information in observable collection /// </summary> private void UpdateProperties() { try { BatteryInfo[] batInfo = new BatteryInfo[] { new BatteryInfo_UWP_API(), new BatteryInfo_WMI(), new BatteryInfo_Win32() }; foreach (BatteryInfo i in batInfo) { foreach (KeyValuePair <string, string> pair in i.GetBatteryInfo()) { int index = properties.IndexOf(properties.FirstOrDefault(x => x.Name == pair.Key && x.Value != pair.Value)); if (index >= 0) { properties.RemoveAt(index); properties.Insert(index, new BatteryProperty(pair.Key, pair.Value)); } } } } catch (NullReferenceException e) { DefaultDialogs.ShowMessage("Не удалось обновить данные о батарее, возможно она больше не доступна\n" + "Системное описание ошибки" + e.Message, "Ошибка"); } catch (Exception e) { DefaultDialogs.ShowMessage("Не опознанная ошибка получения информации о батарее!\n" + "Системное описание ошибки" + e.Message, "Ошибка"); } }
private void ManageBattery(Image bar, BatteryInfo batteryInfo, Text amount) { if (batteryInfo == null && bar != null) { amount.text = _empty; bar.color = _colorEmpty; bar.fillAmount = 0f; return; } amount.text = FloatToPercent(batteryInfo); if (bar == null) { QuickLogger.Error("Bar is null"); return; } var charge = batteryInfo.BatteryCharge < 1 ? 0f : batteryInfo.BatteryCharge; float percent = Mathf.RoundToInt(charge / batteryInfo.BatteryCapacity); if (batteryInfo.BatteryCharge >= 0f) { Color value = (percent >= 0.5f) ? Color.Lerp(this._colorHalf, this._colorFull, 2f * percent - 1f) : Color.Lerp(this._colorEmpty, this._colorHalf, 2f * percent); bar.color = value; bar.fillAmount = percent; } else { bar.color = _colorEmpty; bar.fillAmount = 0f; } }
/// <summary> /// Get information about battrey from all available sources /// </summary> private void InitializePropertiesDictionary() { try { properties.Clear(); BatteryInfo[] batInfo = new BatteryInfo[] { new BatteryInfo_UWP_API(), new BatteryInfo_WMI(), new BatteryInfo_Win32() }; foreach (BatteryInfo i in batInfo) { foreach (KeyValuePair <string, string> pair in i.GetBatteryInfo()) { properties.Add(new BatteryProperty(pair.Key, pair.Value)); } } } catch (NullReferenceException e) { DefaultDialogs.ShowMessage("Не удалось обновить данные о батарее, возможно она больше не доступна\n" + "Системное описание ошибки" + e.Message, "Ошибка"); } catch (Exception e) { DefaultDialogs.ShowMessage("Не опознанная ошибка получения информации о батарее!\n" + "Системное описание ошибки" + e.Message, "Ошибка"); } }
//Callback handler from BatteryStatusController.OnStatus public void ReceiveBatteryStatus(BatteryInfo info) { //XDebug.Log(info.timestamp + " : level = " + info.level + ", scale = " + info.scale + ", percent = " + info.percent + ", status = " + info.status + ", health = " + info.health + ", temperature = " + info.temperature); //XDebug.Log(info); if (batteryTimeDisplay != null) { batteryTimeDisplay.text = "Last Update : " + info.timestamp.Split(' ')[1]; } if (batteryLevelDisplay != null) { batteryLevelDisplay.text = info.percent + "% (" + info.level + "/" + info.scale + ")"; } if (batteryStatusDisplay != null) { batteryStatusDisplay.text = "Status : " + info.status; } if (batteryHealthDisplay != null) { batteryHealthDisplay.text = "Health : " + info.health; } if (batteryTemperatureDisplay != null) { batteryTemperatureDisplay.text = "Temperature : " + info.temperature + " ℃"; } }
/// <summary> /// Get the voltage conversion from the read battery information. /// </summary> /// <param name="battInfo">Recently read battery information, <see cref="BatteryInfo"/>.</param> /// <returns>Interpreted voltage value.</returns> /// <remarks> /// If the return value is -1.0 then it means that no battery was detected. /// If the return value is -2.0 then it means that there was an A/D conversion error. /// </remarks> public static double VoltageConversion(BatteryInfo battInfo) { if (battInfo.present && !battInfo.adError) { double offset, voltage, proportion; proportion = (double)battInfo.level; proportion /= (double)BL_LEVEL_MASKVAL; if (battInfo.is3V) { voltage = 1.65; offset = 1.69; } else { voltage = 0.85; offset = 0.873; } voltage *= proportion; voltage += offset; return(voltage); } if (!battInfo.present) { return(-1.0); // Means "no battery." } return(-2.0); // Means A/D error. }
//Callback handler from BatteryStatusController.OnStatus public void ReceiveBatteryStatus(BatteryInfo info) { //XDebug.Log(info); if (batteryTimeDisplay != null) { batteryTimeDisplay.text = "Update : " + info.timestamp.Split(' ')[1]; } if (batteryLevelDisplay != null) { batteryLevelDisplay.text = info.percent + "% (" + info.level + "/" + info.scale + ")"; } if (batteryStatusDisplay != null) { batteryStatusDisplay.text = "Status : " + info.status; } if (batteryHealthDisplay != null) { batteryHealthDisplay.text = "Health : " + info.health; } if (batteryTemperatureDisplay != null) { batteryTemperatureDisplay.text = "Temperature : " + info.temperature + " ℃"; } if (batteryVoltageDisplay != null) { batteryVoltageDisplay.text = "Voltage : " + info.voltage.ToString("F2") + " V"; } }
public override string ToString() { var builder = new StringBuilder(); builder.Append("Model: ").Append(this.Model).Append("\r\n"); builder.Append("Manufacturer: ").Append(this.Manufacturer).Append("\r\n"); builder.Append("Price: ").Append(this.Price).Append("\r\n"); builder.Append("Owner: ").Append(this.Owner).Append("\r\n"); if (this.BatteryInfo != null) { builder.Append(BatteryInfo.ToString()); } else { builder.Append("Battery Hours Idle: ").Append("\r\n"); builder.Append("Battery Hours Talk: ").Append("\r\n"); builder.Append("Battery Model: ").Append("\r\n"); builder.Append("Battery Type: ").Append("\r\n"); } if (this.Displayinfo != null) { builder.Append(this.Displayinfo.ToString()); } else { builder.Append("Display Size: ").Append("\r\n"); builder.Append("Display Colors: ").Append("\r\n"); } return(builder.ToString()); }
public SystemMonitorService() { Info = new SysInfo(); Battery = new BatteryInfo(); Processor = new ProcessorInfo(); Memory = new MemoryInfo(); Network = new NetworkInfo(); }
// Update is called once per frame //private void Update () { //} //Callback handler from 'BatteryStatusController.OnStatus' public void ReceiveBatteryStatus(BatteryInfo info) { if (targetText != null) { sb.Length = 0; sb.AppendFormat(format, info.temperature); targetText.text = sb.ToString(); } }
public MainViewModel() { Battery = new BatteryInfo(BatteryHelper.GetLatestBatteryStatus()); dt = new DispatcherTimer(); dt.Interval = TimeSpan.FromSeconds(1); dt.Tick += Dt_Tick;; dt.Start(); }
public static Media CreateFrom(RegionOptions regionOptions) { UserControl element = null; Media media = new Media(regionOptions.Width, regionOptions.Height, regionOptions.Top, regionOptions.Left); if (Widgets.ContainsKey(regionOptions.Name)) { element = Widgets[regionOptions.Name]; } else { string name = regionOptions.Name; if (name != null) { if (!(name == "CarInfo")) { if (name == "BatteryInfo") { element = new BatteryInfo(); } else if (name == "LocationInfo") { element = new Location(); } else if (name == "PersonalInfo") { element = new Profile(); } } else { element = new CarInfo(); } } } element.Width = regionOptions.Width; element.Height = regionOptions.Height; element.HorizontalAlignment = HorizontalAlignment.Stretch; element.VerticalAlignment = VerticalAlignment.Stretch; element.Margin = new Thickness(0.0, 0.0, 0.0, 0.0); Canvas parent = element.Parent as Canvas; if (parent != null) { parent.Children.Remove(element); } media.MediaCanvas.Children.Add(element); media.HasOnLoaded = true; try { Widgets.Add(regionOptions.Name, element); } catch (Exception) { } return(media); }
void updateBattery() { Transform progress = power.Find("progress"); SpriteMgr sm = progress.GetComponent <SpriteMgr>(); UISprite sp = progress.GetComponent <UISprite>(); BatteryInfo info = AnysdkMgr.GetBatteryInfo(); sm.setIndex(info.state == "charging" ? 1 : 0); sp.fillAmount = (float)info.power / 100; }
static WidgetsFactory() { Widgets["PersonalInfo"] = new Profile(); Widgets["CarInfo"] = new CarInfo(); Widgets["BatteryInfo"] = new BatteryInfo(); Location location = new Location { Visibility = Visibility.Hidden }; Widgets["LocationInfo"] = location; }
static void Main(string[] args) { BatteryInfo batteryInfo = batteryUtility.GetBatteryInfo(); Console.WriteLine(batteryInfo.BatteryPercentage); batteryUtility.SubscribeBatteryEvents(); batteryUtility.InitializeTimer(); Console.ReadKey(); }
private async void txtBatteryLevel_DoubleTapped(object sender, DoubleTappedRoutedEventArgs e) { if (MiBand.Ready) { // datos de la bateria BatteryInfo battery = await band.GetBatteryInfo(); properties.Batterylevel = battery.Level + "%"; properties.BatteryState = battery.Status.ToString(); properties.LastCharged = battery.LastChargedS; } }
public async void batteryValueChanged(BatteryInfo info) { await parent.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => { if (info.Valid) { Batterylevel = info.Level + "%"; BatteryState = info.Status.ToString(); LastCharged = info.LastChargedS; } }); }
void Update(object state) { while (_check == false) { this._batteryInfo = BatteryInfo.GetBatteryInformation(); if (this._last_batteryInfo.CurrentCapacity != this._batteryInfo.CurrentCapacity) { this._last_batteryInfo = this._batteryInfo; this.BatteryStatusUpdate?.Invoke(this, this._batteryInfo); } } }
private string FloatToPercent(BatteryInfo batteryInfo) { if (batteryInfo == null) { return("0%"); } var charge = batteryInfo.BatteryCharge < 1 ? 0f : batteryInfo.BatteryCharge; float percent = charge / batteryInfo.BatteryCapacity; return((batteryInfo.BatteryCharge < 0f) ? Language.main.Get("ChargerSlotEmpty") : $"{Mathf.RoundToInt(percent * 100)}%"); }
//Callback handler for battery information. private void ReceiveStatus(string json) { if (string.IsNullOrEmpty(json)) { return; } BatteryInfo info = JsonUtility.FromJson <BatteryInfo>(json); if (OnStatus != null) { OnStatus.Invoke(info); } }
public BatteryInfo GetBatteryInfo() { // For SystemInformationHelper .csproj file should have <Project Sdk="Microsoft.NET.Sdk.WindowsDesktop"> int powerStatus = (int)SystemInformation.PowerStatus.PowerLineStatus; float batteryLife = SystemInformation.PowerStatus.BatteryLifePercent; batteryLife *= 100; BatteryInfo batteryInfo = new BatteryInfo { PowerStatus = powerStatus.ToString(CultureInfo.InvariantCulture), BatteryPercentage = batteryLife.ToString(CultureInfo.InvariantCulture) }; return(batteryInfo); }
private void _timer_Tick(object sender, EventArgs e) { CPUProgress.Value = _cpuCounter.NextValue(); CPUText.Text = string.Format("{0:0.00}%", CPUProgress.Value); double ram = 100.0 - ((double)PerformanceInfo.GetPhysicalAvailableMemoryInMiB() / _availableMemory) * 100.0; RAMProgress.Value = ram; RAMText.Text = string.Format("{0:0.00}%", ram); _free = PerformanceInfo.GetPhysicalAvailableMemoryInMiB(); _used = _availableMemory - _free; RAMAmount.Text = string.Format("{0} MB", _free); RAMAmount.ToolTip = CreateTooltip(); BatteryInfo.UpdateBatteryInfo(); }
private void OnEquip(string slot, InventoryItem item) { var battery = item.item.gameObject.GetComponent <IBattery>(); var newBattery = new BatteryInfo(item.item.GetTechType(), battery, slot); switch (slot) { case Slot1: _batteries[0] = newBattery; break; case Slot2: _batteries[1] = newBattery; break; } _mono.UpdateBatteryDisplay(_batteries); }
public Tuple <string, int> GetBattery() { BatteryInfo batteryInfo = GetBatteryInfo(); Console.WriteLine("Battery %: " + batteryInfo.BatteryPercentage); if (batteryInfo.PowerStatus.Equals("1", StringComparison.InvariantCultureIgnoreCase)) { return(new Tuple <string, int>("User PC Connected to AC Power Source", 0)); } else if (batteryInfo.PowerStatus.Equals("0", StringComparison.InvariantCultureIgnoreCase) && Convert.ToDouble(batteryInfo.BatteryPercentage, CultureInfo.InvariantCulture) >= 20) { return(new Tuple <string, int>("System is not plugged to AC Power source", 2464)); } else { return(new Tuple <string, int>("Battery Percentage is at a critical level", 2465)); } }
public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append("GSM model: " + Model + "\n"); sb.Append("GSM manufacturer: " + Manufacturer + "\n"); sb.Append("GSM price: " + Price + "\n"); sb.Append("GSM owner: " + Owner + "\n"); if (BatteryInfo != null) { sb.Append(BatteryInfo.ToString()); } if (DisplayInfo != null) { sb.Append(DisplayInfo.ToString()); } return(sb.ToString()); }
public static Media CreateFrom(RegionOptions regionOptions) { UserControl widget = null; Media Backing = new Media(regionOptions.Width, regionOptions.Height, regionOptions.Top, regionOptions.Left); switch (regionOptions.Name) { case "CarInfo": widget = new CarInfo(); break; case "BatteryInfo": widget = new BatteryInfo(); break; case "LocationInfo": widget = new Location(); break; case "PersonalInfo": widget = new Profile(); break; default: break; } widget.Width = regionOptions.Width; widget.Height = regionOptions.Height; //MediaGrid.Width = Width; //MediaGrid.Height = Height; widget.HorizontalAlignment = HorizontalAlignment.Center; widget.VerticalAlignment = VerticalAlignment.Center; widget.Margin = new Thickness(0, 0, 0, 0); Backing.MediaCanvas.Children.Add(widget); Backing.HasOnLoaded = true; return(Backing); }
public void ClearAllInfo() { Action method = null; Cleared = false; try { if (method == null) { method = new Action(() => { if (((WidgetsFactory.Widgets["PersonalInfo"] != null) && (WidgetsFactory.Widgets["CarInfo"] != null)) && ((WidgetsFactory.Widgets["BatteryInfo"] != null) && (WidgetsFactory.Widgets["LocationInfo"] != null))) { this.CustomerProfile = WidgetsFactory.Widgets["PersonalInfo"] as Profile; this.CarInfoWidget = WidgetsFactory.Widgets["CarInfo"] as CarInfo; this.BatteryInfoWidget = WidgetsFactory.Widgets["BatteryInfo"] as BatteryInfo; this.LocationWidget = WidgetsFactory.Widgets["LocationInfo"] as Location; this.CustomerProfile.CustomerProfilePicture.Source = null; this.CarInfoWidget.CarMake.Content = ""; this.CarInfoWidget.CarModel.Content = ""; this.CarInfoWidget.CarPlate.Content = ""; this.CustomerProfile.CustomerName.Content = ""; this.CustomerProfile.CustomerEmail.Content = ""; this.CustomerProfile.CustomerPhone.Content = ""; this.CustomerProfile.CustomerAddress.Text = ""; string str = "0"; this.BatteryInfoWidget.CurrentCharge.Content = str; this.BatteryInfoWidget.BatteryAnimation.PercentCharged = Convert.ToInt32(str); this.BatteryInfoWidget.LastCharged.Content = ""; this.BatteryInfoWidget.AccountBalance.Content = ""; Cleared = true; } }); } base.Dispatcher.BeginInvoke(DispatcherPriority.Normal, method); } catch (Exception) { } }
private void updateInfoFromSettings() { ApplicationDataContainer localSettings = ApplicationData.Current.LocalSettings; if (localSettings.Containers.ContainsKey("MiBand")) { var settings = localSettings.Containers["MiBand"]; // datos de la band properties.BandName = (string)settings.Values["Name"]; properties.MACAddress = (string)settings.Values["MAC"]; // datos de la bateria BatteryInfo battery = BatteryInfo.FromSetting((ApplicationDataCompositeValue)settings.Values["BatteryInfo"]); properties.Batterylevel = battery.Level + "%"; properties.BatteryState = battery.Status.ToString(); properties.LastCharged = battery.LastChargedS; // datos de los pasos properties.Goal = (int)settings.Values["DailyGoal"]; properties.CurrentSteps = (int)settings.Values["CurrentSteps"]; // datos de alarmas properties.Alarm1 = Alarm.FromSetting((ApplicationDataCompositeValue)settings.Values["Alarm1"]); properties.Alarm2 = Alarm.FromSetting((ApplicationDataCompositeValue)settings.Values["Alarm2"]); properties.Alarm3 = Alarm.FromSetting((ApplicationDataCompositeValue)settings.Values["Alarm3"]); tgAlarm1.DataContext = properties.Alarm1; tgAlarm2.DataContext = properties.Alarm2; tgAlarm3.DataContext = properties.Alarm3; txtAlarm1.DataContext = properties.Alarm1; txtAlarm2.DataContext = properties.Alarm2; txtAlarm3.DataContext = properties.Alarm3; // datos de localizacion y colores properties.ColorTheme = ColorTheme.FromInt32((int)settings.Values["ColorTheme"]); properties.WearLocation = (WearLocation)settings.Values["WearLocation"]; // datos del dispositivo properties.DeviceInfo = DeviceInfo.FromSetting((ApplicationDataCompositeValue)settings.Values["DeviceInfo"]); } }
public static BatteryInfo GetBatteryInfo() { BatteryInfo ret = new BatteryInfo(); ret.power = 100; ret.state = "full"; if (isAndroid()) { return(ret); // TODO } else if (isIOS()) { #if UNITY_IPHONE int battery = getBatteryInfo(); ret.power = battery % 1000; int tmp = battery / 1000; if (tmp == 2) { ret.state = "charging"; } else if (tmp == 3) { ret.state = "full"; } else { ret.state = "unplugged"; } #endif } return(ret); }
private BatteryInfo BatteryInformationExchange(uint password, bool secured, bool reTrigger) { List <BitEntry> entries = new List <BitEntry>(); BatteryInfo bi = new BatteryInfo(); BitBuffer bb; NurApi.CustomExchangeParams xch; NurApi.CustomExchangeResponse resp; int respLen; uint tmpVal; entries.Add(BuildEntry(ADD_PARAMETER, (uint)(reTrigger ? 1 : 0), BL_RETRIGGER_LEN)); /* Build the command. */ bb = BuildCommand(CMD_GET_BATTLEVEL, entries); /* * No response length as the battery may not be in place * -> error respones. */ xch = BuildDefault(bb, 0, false, false); resp = hApi.CustomExchangeSingulated(password, secured, NurApi.BANK_EPC, 32, epc.Length * 8, epc, xch); respLen = resp.tagBytes.Length; if (resp.error != NurApiErrors.NUR_NO_ERROR || respLen != BATTINFO_OK_BYTE_LEN) { if (respLen == MIN_ERROR_RESP_LENGTH && resp.tagBytes[0] == ERR_BATTERY) { hApi.ULog("BattInfo: battery not in place."); bi.level = 0; bi.adError = true; bi.is3V = false; bi.present = false; return(bi); } hApi.ULog("BattInfoError, len = " + respLen + "."); if (respLen >= MIN_ERROR_RESP_LENGTH) { InterpretedException("Battery info", resp); } DoException("Battery info", resp); } bi.present = true; hApi.ULog("BattInfo: no error."); /* 16 bits */ tmpVal = resp.tagBytes[0]; tmpVal <<= 8; tmpVal |= resp.tagBytes[1]; bi.adError = IsMaskBitSet(tmpVal, BL_ADERR_BIT); bi.is3V = IsMaskBitSet(tmpVal, BL_3VOLT_BIT); bi.level = (tmpVal & BL_LEVEL_MASKVAL); return(bi); }
private void Dt_Tick(object sender, object e) { dt.Start(); Battery = new BatteryInfo(BatteryHelper.GetLatestBatteryStatus()); dt.Start(); }