├── LGSTrayHID ├── libhidapi │ ├── readme.md │ └── hidapi.dll ├── Properties │ ├── launchSettings.json │ └── PublishProfiles │ │ ├── Framedep.pubxml │ │ └── Standalone.pubxml ├── HidApi │ ├── HidApiWinApi.cs │ ├── HidDeviceInfo.cs │ ├── HidDeviceInfoHelpers.cs │ ├── HidDevicePtr.cs │ ├── HidApiHotPlug.cs │ └── HidApi.cs ├── Features │ ├── IBatteryReturn.cs │ ├── Battery1004.cs │ ├── Battery1000.cs │ └── Battery1001.cs ├── Hidpp20.cs ├── HidppManagerService.cs ├── LGSTrayHID.csproj ├── Program.cs ├── HidppManagerContext.cs ├── HidppDevice.cs └── HidppDevices.cs ├── Assets ├── multi_icon.png ├── server_index.png ├── charging_icon.png └── numerical_icon.png ├── LGSTrayUI ├── NativeMethods.json ├── Resources │ ├── Mouse.png │ ├── Battery.png │ ├── Charging.png │ ├── Headset.png │ ├── Keyboard.png │ ├── Missing.png │ ├── Mouse_dark.png │ ├── logo_black.ico │ ├── Battery_dark.png │ ├── Charging_dark.png │ ├── Headset_dark.png │ ├── Indicator_10.png │ ├── Indicator_100.png │ ├── Indicator_30.png │ ├── Indicator_50.png │ ├── Keyboard_dark.png │ └── Missing_dark.png ├── NativeMethods.txt ├── Properties │ ├── launchSettings.json │ ├── PublishProfiles │ │ ├── Framedep.pubxml │ │ └── Standalone.pubxml │ ├── Settings.settings │ ├── Settings.Designer.cs │ ├── Resources.Designer.cs │ └── Resources.resx ├── NotifyIconResources.xaml.cs ├── appsettings.toml ├── App.xaml ├── AssemblyInfo.cs ├── App.config ├── ThemeBrushConverter.cs ├── AppExtensions.cs ├── UserSettingsWrapper.cs ├── LogiDeviceIcon.xaml ├── MainTaskbarIconWrapper.cs ├── CheckTheme.cs ├── NotifyIconResources.xaml ├── LogiDeviceViewModel.cs ├── LGSTrayUI.csproj ├── LogiDeviceCollection.cs ├── App.xaml.cs ├── LogiDeviceIcon.xaml.cs ├── NotifyIconViewModel.cs └── BatteryIconDrawing.cs ├── .editorconfig ├── LGSTrayCore ├── Managers │ ├── IDeviceManager.cs │ ├── LGSTrayHIDManager.cs │ └── GHubManager.cs ├── ILogiDeviceCollection.cs ├── LGSTrayCore.csproj ├── IServiceExtension.cs ├── HttpServer │ ├── HttpServer.cs │ └── HttpController.cs └── LogiDevice.cs ├── LGSTrayPrimitives ├── DeviceType.cs ├── PowerSupplyStatus.cs ├── LGSTrayPrimitives.csproj ├── IPC │ ├── MessagePipeHelper.cs │ └── MessageStructs.cs └── AppSettings.cs ├── .github └── workflows │ └── nightly-builds.yml ├── .gitattributes ├── publish.py ├── LGSTrayBattery.sln ├── .gitignore ├── readme.md └── LICENSE /LGSTrayHID/libhidapi/readme.md: -------------------------------------------------------------------------------- 1 | Custom build of hidapi 0.14.0 with hotplugging support -------------------------------------------------------------------------------- /Assets/multi_icon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/andyvorld/LGSTrayBattery/master/Assets/multi_icon.png -------------------------------------------------------------------------------- /Assets/server_index.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/andyvorld/LGSTrayBattery/master/Assets/server_index.png -------------------------------------------------------------------------------- /Assets/charging_icon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/andyvorld/LGSTrayBattery/master/Assets/charging_icon.png -------------------------------------------------------------------------------- /Assets/numerical_icon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/andyvorld/LGSTrayBattery/master/Assets/numerical_icon.png -------------------------------------------------------------------------------- /LGSTrayUI/NativeMethods.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "https://aka.ms/CsWin32.schema.json", 3 | "public": true 4 | } -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | [*.cs] 2 | 3 | # IDE0290: Use primary constructor 4 | csharp_style_prefer_primary_constructors = false 5 | -------------------------------------------------------------------------------- /LGSTrayUI/Resources/Mouse.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/andyvorld/LGSTrayBattery/master/LGSTrayUI/Resources/Mouse.png -------------------------------------------------------------------------------- /LGSTrayHID/libhidapi/hidapi.dll: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/andyvorld/LGSTrayBattery/master/LGSTrayHID/libhidapi/hidapi.dll -------------------------------------------------------------------------------- /LGSTrayUI/Resources/Battery.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/andyvorld/LGSTrayBattery/master/LGSTrayUI/Resources/Battery.png -------------------------------------------------------------------------------- /LGSTrayUI/Resources/Charging.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/andyvorld/LGSTrayBattery/master/LGSTrayUI/Resources/Charging.png -------------------------------------------------------------------------------- /LGSTrayUI/Resources/Headset.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/andyvorld/LGSTrayBattery/master/LGSTrayUI/Resources/Headset.png -------------------------------------------------------------------------------- /LGSTrayUI/Resources/Keyboard.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/andyvorld/LGSTrayBattery/master/LGSTrayUI/Resources/Keyboard.png -------------------------------------------------------------------------------- /LGSTrayUI/Resources/Missing.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/andyvorld/LGSTrayBattery/master/LGSTrayUI/Resources/Missing.png -------------------------------------------------------------------------------- /LGSTrayUI/Resources/Mouse_dark.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/andyvorld/LGSTrayBattery/master/LGSTrayUI/Resources/Mouse_dark.png -------------------------------------------------------------------------------- /LGSTrayUI/Resources/logo_black.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/andyvorld/LGSTrayBattery/master/LGSTrayUI/Resources/logo_black.ico -------------------------------------------------------------------------------- /LGSTrayUI/Resources/Battery_dark.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/andyvorld/LGSTrayBattery/master/LGSTrayUI/Resources/Battery_dark.png -------------------------------------------------------------------------------- /LGSTrayUI/Resources/Charging_dark.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/andyvorld/LGSTrayBattery/master/LGSTrayUI/Resources/Charging_dark.png -------------------------------------------------------------------------------- /LGSTrayUI/Resources/Headset_dark.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/andyvorld/LGSTrayBattery/master/LGSTrayUI/Resources/Headset_dark.png -------------------------------------------------------------------------------- /LGSTrayUI/Resources/Indicator_10.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/andyvorld/LGSTrayBattery/master/LGSTrayUI/Resources/Indicator_10.png -------------------------------------------------------------------------------- /LGSTrayUI/Resources/Indicator_100.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/andyvorld/LGSTrayBattery/master/LGSTrayUI/Resources/Indicator_100.png -------------------------------------------------------------------------------- /LGSTrayUI/Resources/Indicator_30.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/andyvorld/LGSTrayBattery/master/LGSTrayUI/Resources/Indicator_30.png -------------------------------------------------------------------------------- /LGSTrayUI/Resources/Indicator_50.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/andyvorld/LGSTrayBattery/master/LGSTrayUI/Resources/Indicator_50.png -------------------------------------------------------------------------------- /LGSTrayUI/Resources/Keyboard_dark.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/andyvorld/LGSTrayBattery/master/LGSTrayUI/Resources/Keyboard_dark.png -------------------------------------------------------------------------------- /LGSTrayUI/Resources/Missing_dark.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/andyvorld/LGSTrayBattery/master/LGSTrayUI/Resources/Missing_dark.png -------------------------------------------------------------------------------- /LGSTrayCore/Managers/IDeviceManager.cs: -------------------------------------------------------------------------------- 1 | namespace LGSTrayCore.Managers; 2 | 3 | public interface IDeviceManager 4 | { 5 | public void RediscoverDevices(); 6 | } 7 | -------------------------------------------------------------------------------- /LGSTrayHID/Properties/launchSettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "profiles": { 3 | "LGSTrayHID": { 4 | "commandName": "Project", 5 | "nativeDebugging": false 6 | } 7 | } 8 | } -------------------------------------------------------------------------------- /LGSTrayUI/NativeMethods.txt: -------------------------------------------------------------------------------- 1 | SetPriorityClass 2 | SetProcessInformation 3 | PROCESS_POWER_THROTTLING_STATE 4 | PROCESS_POWER_THROTTLING_CURRENT_VERSION 5 | PROCESS_POWER_THROTTLING_EXECUTION_SPEED -------------------------------------------------------------------------------- /LGSTrayPrimitives/DeviceType.cs: -------------------------------------------------------------------------------- 1 | namespace LGSTrayPrimitives 2 | { 3 | public enum DeviceType : byte 4 | { 5 | Keyboard = 0, 6 | Mouse = 3, 7 | Headset = 8, 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /LGSTrayUI/Properties/launchSettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "profiles": { 3 | "LGSTrayUI": { 4 | "commandName": "Project", 5 | "nativeDebugging": false 6 | }, 7 | "LGSTrayUI - Debug Native": { 8 | "commandName": "Project", 9 | "nativeDebugging": true 10 | } 11 | } 12 | } -------------------------------------------------------------------------------- /LGSTrayUI/NotifyIconResources.xaml.cs: -------------------------------------------------------------------------------- 1 | using System.Windows.Controls; 2 | namespace LGSTrayUI; 3 | 4 | /// 5 | /// Interaction logic for NotifyIconResources.xaml 6 | /// 7 | public partial class NotifyIconResources : UserControl 8 | { 9 | public NotifyIconResources() 10 | { 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /LGSTrayPrimitives/PowerSupplyStatus.cs: -------------------------------------------------------------------------------- 1 | namespace LGSTrayPrimitives 2 | { 3 | public enum PowerSupplyStatus : byte 4 | { 5 | POWER_SUPPLY_STATUS_DISCHARGING = 0, 6 | POWER_SUPPLY_STATUS_CHARGING, 7 | POWER_SUPPLY_STATUS_FULL, 8 | POWER_SUPPLY_STATUS_NOT_CHARGING, 9 | POWER_SUPPLY_STATUS_UNKNOWN 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /LGSTrayCore/ILogiDeviceCollection.cs: -------------------------------------------------------------------------------- 1 | using LGSTrayPrimitives.MessageStructs; 2 | 3 | namespace LGSTrayCore 4 | { 5 | public interface ILogiDeviceCollection 6 | { 7 | public IEnumerable GetDevices(); 8 | public void OnInitMessage(InitMessage initMessage); 9 | public void OnUpdateMessage(UpdateMessage updateMessage); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /LGSTrayUI/appsettings.toml: -------------------------------------------------------------------------------- 1 | [UI] 2 | enableRichToolTips = true 3 | 4 | [HTTPServer] 5 | enabled = true 6 | addr = "localhost" 7 | port = 12321 8 | useIpv6 = true 9 | 10 | [GHub] 11 | enabled = true 12 | 13 | [Native] 14 | enabled = true 15 | 16 | # Time in seconds to retry a device poll on failure 17 | retryTime = 10 18 | 19 | # Time in seconds to next device poll on sucess 20 | pollPeriod = 600 21 | 22 | # List of disabled devices 23 | disabledDevices = [ 24 | ] -------------------------------------------------------------------------------- /LGSTrayPrimitives/LGSTrayPrimitives.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net8.0 5 | enable 6 | enable 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | -------------------------------------------------------------------------------- /LGSTrayUI/App.xaml: -------------------------------------------------------------------------------- 1 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /LGSTrayHID/Properties/PublishProfiles/Framedep.pubxml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | 7 | Release 8 | Any CPU 9 | ..\bin\Release\publish\win-x64\framedep\ 10 | FileSystem 11 | <_TargetId>Folder 12 | net8.0-windows 13 | win-x64 14 | false 15 | 16 | -------------------------------------------------------------------------------- /LGSTrayUI/Properties/PublishProfiles/Framedep.pubxml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | 7 | Release 8 | Any CPU 9 | ..\bin\Release\publish\win-x64\framedep\ 10 | FileSystem 11 | <_TargetId>Folder 12 | net8.0-windows 13 | win-x64 14 | false 15 | 16 | -------------------------------------------------------------------------------- /LGSTrayHID/Properties/PublishProfiles/Standalone.pubxml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | 7 | Release 8 | Any CPU 9 | ..\bin\Release\publish\win-x64\standalone\ 10 | FileSystem 11 | <_TargetId>Folder 12 | net8.0-windows 13 | win-x64 14 | true 15 | 16 | -------------------------------------------------------------------------------- /LGSTrayUI/Properties/PublishProfiles/Standalone.pubxml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | 7 | Release 8 | Any CPU 9 | ..\bin\Release\publish\win-x64\standalone\ 10 | FileSystem 11 | <_TargetId>Folder 12 | net8.0-windows 13 | win-x64 14 | true 15 | 16 | -------------------------------------------------------------------------------- /LGSTrayUI/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Windows; 2 | 3 | [assembly: ThemeInfo( 4 | ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located 5 | //(used if a resource is not found in the page, 6 | // or application resource dictionaries) 7 | ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located 8 | //(used if a resource is not found in the page, 9 | // app, or any theme specific resource dictionaries) 10 | )] 11 | -------------------------------------------------------------------------------- /LGSTrayPrimitives/IPC/MessagePipeHelper.cs: -------------------------------------------------------------------------------- 1 | using MessagePipe; 2 | using Microsoft.Extensions.DependencyInjection; 3 | 4 | namespace LGSTrayPrimitives.IPC 5 | { 6 | public static class MessagePipeHelper 7 | { 8 | public static void AddLGSMessagePipe(this IServiceCollection services, bool hostAsServer = false) 9 | { 10 | services.AddMessagePipe(options => 11 | { 12 | options.EnableCaptureStackTrace = true; 13 | }); 14 | 15 | services.AddMessagePipeNamedPipeInterprocess("LGSTray", config => 16 | { 17 | config.HostAsServer = hostAsServer; 18 | }); 19 | } 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /LGSTrayHID/HidApi/HidApiWinApi.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Runtime.InteropServices; 5 | using System.Text; 6 | using System.Threading.Tasks; 7 | 8 | namespace LGSTrayHID.HidApi 9 | { 10 | internal static partial class HidApiWinApi 11 | { 12 | [LibraryImport("hidapi", EntryPoint = "hid_winapi_get_container_id")] 13 | private static unsafe partial int _HidWinApiGetContainerId(nint dev, Guid* container_id); 14 | 15 | internal static unsafe int HidWinApiGetContainerId(nint dev, out Guid container_id) 16 | { 17 | Guid _container_id = new(); 18 | int ret = _HidWinApiGetContainerId(dev, &_container_id); 19 | container_id = _container_id; 20 | 21 | return ret; 22 | } 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /LGSTrayUI/Properties/Settings.settings: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | <?xml version="1.0" encoding="utf-16"?> 7 | <ArrayOfString xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> 8 | <string /> 9 | </ArrayOfString> 10 | 11 | 12 | False 13 | 14 | 15 | -------------------------------------------------------------------------------- /LGSTrayHID/Features/IBatteryReturn.cs: -------------------------------------------------------------------------------- 1 | using LGSTrayPrimitives; 2 | 3 | namespace LGSTrayHID.Features 4 | { 5 | public readonly record struct BatteryUpdateReturn 6 | { 7 | public readonly double batteryPercentage; 8 | public readonly PowerSupplyStatus status; 9 | public readonly int batteryMVolt; 10 | 11 | public BatteryUpdateReturn() 12 | { 13 | this.batteryPercentage = 0; 14 | this.status = PowerSupplyStatus.POWER_SUPPLY_STATUS_UNKNOWN; 15 | this.batteryMVolt = -1; 16 | } 17 | 18 | public BatteryUpdateReturn(double batteryPercentage, PowerSupplyStatus status, int batteryMVolt) 19 | { 20 | this.batteryPercentage = batteryPercentage; 21 | this.status = status; 22 | this.batteryMVolt = batteryMVolt; 23 | } 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /LGSTrayCore/LGSTrayCore.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net8.0 5 | enable 6 | enable 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | -------------------------------------------------------------------------------- /LGSTrayHID/HidApi/HidDeviceInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Runtime.InteropServices; 2 | 3 | namespace LGSTrayHID.HidApi 4 | { 5 | internal enum HidBusType : int 6 | { 7 | HID_API_BUS_UNKNOWN = 0x00, 8 | HID_API_BUS_USB = 0x01, 9 | HID_API_BUS_BLUETOOTH = 0x02, 10 | HID_API_BUS_I2C = 0x03, 11 | HID_API_BUS_SPI = 0x04, 12 | } 13 | 14 | [StructLayout(LayoutKind.Sequential)] 15 | internal readonly unsafe struct HidDeviceInfo 16 | { 17 | internal readonly byte* Path; 18 | internal readonly ushort VendorId; 19 | internal readonly ushort ProductId; 20 | internal readonly byte* SerialNumber; 21 | internal readonly ushort ReleaseNumber; 22 | internal readonly byte* ManufacturerString; 23 | internal readonly byte* ProductString; 24 | internal readonly ushort UsagePage; 25 | internal readonly ushort Usage; 26 | internal readonly int InterfaceNumber; 27 | internal readonly HidDeviceInfo* Next; 28 | internal readonly HidBusType BusType; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /LGSTrayHID/Features/Battery1004.cs: -------------------------------------------------------------------------------- 1 | using LGSTrayPrimitives; 2 | using static LGSTrayPrimitives.PowerSupplyStatus; 3 | 4 | namespace LGSTrayHID.Features 5 | { 6 | public static class Battery1004 7 | { 8 | public static async Task GetBatteryAsync(HidppDevice device) 9 | { 10 | Hidpp20 buffer = new byte[7] { 0x10, device.DeviceIdx, device.FeatureMap[0x1004], 0x10 | HidppDevices.SW_ID, 0x00, 0x00, 0x00 }; 11 | Hidpp20 ret = await device.Parent.WriteRead20(device.Parent.DevShort, buffer); 12 | 13 | if (ret.Length == 0) { return null; } 14 | 15 | int mv = -1; 16 | double batPercent = ret.GetParam(0); 17 | var status = ret.GetParam(2) switch 18 | { 19 | 0 => POWER_SUPPLY_STATUS_DISCHARGING, 20 | 1 or 2 => POWER_SUPPLY_STATUS_CHARGING, 21 | 3 => POWER_SUPPLY_STATUS_FULL, 22 | _ => POWER_SUPPLY_STATUS_NOT_CHARGING, 23 | }; 24 | return new BatteryUpdateReturn(batPercent, status, mv); 25 | } 26 | 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /LGSTrayHID/Features/Battery1000.cs: -------------------------------------------------------------------------------- 1 | using LGSTrayPrimitives; 2 | using static LGSTrayPrimitives.PowerSupplyStatus; 3 | 4 | namespace LGSTrayHID.Features 5 | { 6 | public static class Battery1000 7 | { 8 | public static async Task GetBatteryAsync(HidppDevice device) 9 | { 10 | Hidpp20 buffer = new byte[7] { 0x10, device.DeviceIdx, device.FeatureMap[0x1000], 0x00 | HidppDevices.SW_ID, 0x00, 0x00, 0x00 }; 11 | Hidpp20 ret = await device.Parent.WriteRead20(device.Parent.DevShort, buffer); 12 | 13 | if (ret.Length == 0) { return null; } 14 | 15 | int mv = -1; 16 | double batPercent = ret.GetParam(0); 17 | var status = ret.GetParam(2) switch 18 | { 19 | 0 => POWER_SUPPLY_STATUS_DISCHARGING, 20 | 1 or 2 => POWER_SUPPLY_STATUS_CHARGING, 21 | 3 => POWER_SUPPLY_STATUS_FULL, 22 | 4 => POWER_SUPPLY_STATUS_CHARGING, 23 | _ => POWER_SUPPLY_STATUS_NOT_CHARGING, 24 | }; 25 | return new BatteryUpdateReturn(batPercent, status, mv); 26 | } 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /.github/workflows/nightly-builds.yml: -------------------------------------------------------------------------------- 1 | name: Nightly Builds 2 | 3 | on: 4 | workflow_dispatch: 5 | 6 | jobs: 7 | build: 8 | runs-on: windows-latest 9 | 10 | steps: 11 | - name: Checkout 12 | uses: actions/checkout@v3 13 | with: 14 | fetch-depth: 0 15 | 16 | - uses: actions/setup-dotnet@v3 17 | with: 18 | dotnet-version: 8 19 | 20 | - uses: actions/setup-python@v5 21 | with: 22 | python-version: '3.11' 23 | 24 | - name: python .\publish.py 25 | run: | 26 | $commit_ts=git show --no-patch --format=%at 27 | $commit_ds=(([System.DateTimeOffset]::FromUnixTimeSeconds($commit_ts)).DateTime).ToString("yyyyMMdd") 28 | python .\publish.py --version-suffix="-nightly+$commit_ds" 29 | 30 | - name: upload nightly build 31 | env: 32 | GH_TOKEN: ${{ secrets.NIGHTLY_TOKEN }} 33 | run: | 34 | $commit_ts=git show --no-patch --format=%at 35 | $commit_ds=(([System.DateTimeOffset]::FromUnixTimeSeconds($commit_ts)).DateTime).ToString("yyyyMMdd") 36 | gh release create -R "andyvorld/LGSTrayBattery-nightly" ` 37 | $commit_ds ` 38 | (get-item ./bin/Release/publish/*.zip) -------------------------------------------------------------------------------- /LGSTrayUI/App.config: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 |
6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | False 19 | 20 | 21 | 22 | -------------------------------------------------------------------------------- /LGSTrayUI/ThemeBrushConverter.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Globalization; 3 | using System.Windows.Data; 4 | using System.Windows.Media; 5 | 6 | namespace LGSTrayUI; 7 | 8 | public class ThemeBrushConverter : IValueConverter 9 | { 10 | private static readonly SolidColorBrush Black = new(Color.FromRgb(0x2e, 0x2e, 0x2e)); 11 | private static readonly SolidColorBrush BlackText = new(Colors.Black); 12 | private static readonly SolidColorBrush White = new(Color.FromRgb(0xd0, 0xd0, 0xd0)); 13 | private static readonly SolidColorBrush WhiteTest = new(Colors.White); 14 | 15 | public object Convert(object value, Type targetType, object parameter, CultureInfo culture) 16 | { 17 | if (value is not bool lightTheme) return Black; 18 | string? param = parameter as string; 19 | 20 | return lightTheme switch 21 | { 22 | true when param == "Text" => BlackText, 23 | false when param == "Text" => WhiteTest, 24 | true => White, 25 | false => Black, 26 | }; 27 | } 28 | 29 | public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) 30 | { 31 | throw new NotImplementedException(); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /LGSTrayHID/Hidpp20.cs: -------------------------------------------------------------------------------- 1 | namespace LGSTrayHID 2 | { 3 | public readonly struct Hidpp20 4 | { 5 | private readonly byte[] _data; 6 | 7 | public Hidpp20(byte[] data) 8 | { 9 | this._data = data; 10 | } 11 | 12 | public static explicit operator byte[](Hidpp20 msg) => msg._data; 13 | 14 | public static implicit operator Hidpp20(byte[] data) => new(data); 15 | 16 | public byte this[int index] => _data[index]; 17 | 18 | public int Length => _data.Length; 19 | 20 | public byte GetDeviceIdx() 21 | { 22 | return _data[1]; 23 | } 24 | 25 | public byte GetFeatureIndex() 26 | { 27 | return _data[2]; 28 | } 29 | 30 | public byte GetFunctionId() 31 | { 32 | return (byte)((_data[3] & 0xF0) >> 4); 33 | } 34 | 35 | public byte GetSoftwareId() 36 | { 37 | return (byte)(_data[3] & 0x0F); 38 | } 39 | 40 | public Span GetParams() 41 | { 42 | return _data.AsSpan(4); 43 | } 44 | 45 | public byte GetParam(int paramIdx) 46 | { 47 | return _data[4 + paramIdx]; 48 | } 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /LGSTrayPrimitives/AppSettings.cs: -------------------------------------------------------------------------------- 1 | namespace LGSTrayPrimitives; 2 | 3 | public class AppSettings 4 | { 5 | public UISettings UI { get; set; } = null!; 6 | 7 | public HttpServerSettings HTTPServer { get; set; } = null!; 8 | 9 | public IDeviceManagerSettings GHub { get; set; } = null!; 10 | 11 | public NativeDeviceManagerSettings Native { get; set; } = null!; 12 | } 13 | 14 | public class UISettings 15 | { 16 | public bool EnableRichToolTips { get; set; } 17 | } 18 | 19 | public class HttpServerSettings 20 | { 21 | public bool Enabled { get; set; } 22 | public int Port { get; set; } 23 | 24 | private string _addr = null!; 25 | public string Addr 26 | { 27 | get => _addr; 28 | set => _addr = (value == "0.0.0.0") ? "+" : value; 29 | } 30 | 31 | public bool UseIpv6 { get; set; } 32 | 33 | public string UrlPrefix => $"http://{Addr}:{Port}"; 34 | } 35 | 36 | public class IDeviceManagerSettings 37 | { 38 | public bool Enabled { get; set; } 39 | } 40 | 41 | public class NativeDeviceManagerSettings : IDeviceManagerSettings 42 | { 43 | public int RetryTime { get; set; } = 10; 44 | public int PollPeriod { get; set; } = 600; 45 | 46 | public IEnumerable DisabledDevices { get; set; } = []; 47 | } 48 | -------------------------------------------------------------------------------- /LGSTrayUI/AppExtensions.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Diagnostics; 3 | using Winmdroot = Windows.Win32; 4 | 5 | namespace LGSTrayUI; 6 | 7 | public static class AppExtensions 8 | { 9 | public static unsafe void EnableEfficiencyMode() 10 | { 11 | if (OperatingSystem.IsWindowsVersionAtLeast(8)) 12 | { 13 | var handle = Process.GetCurrentProcess().SafeHandle; 14 | Winmdroot.PInvoke.SetPriorityClass(handle, Winmdroot.System.Threading.PROCESS_CREATION_FLAGS.IDLE_PRIORITY_CLASS); 15 | 16 | Winmdroot.System.Threading.PROCESS_POWER_THROTTLING_STATE state = new() 17 | { 18 | Version = Winmdroot.PInvoke.PROCESS_POWER_THROTTLING_CURRENT_VERSION, 19 | ControlMask = Winmdroot.PInvoke.PROCESS_POWER_THROTTLING_EXECUTION_SPEED, 20 | StateMask = Winmdroot.PInvoke.PROCESS_POWER_THROTTLING_EXECUTION_SPEED, 21 | }; 22 | 23 | Winmdroot.PInvoke.SetProcessInformation( 24 | handle, 25 | Winmdroot.System.Threading.PROCESS_INFORMATION_CLASS.ProcessPowerThrottling, 26 | &state, 27 | (uint)sizeof(Winmdroot.System.Threading.PROCESS_POWER_THROTTLING_STATE) 28 | ); 29 | } 30 | } 31 | 32 | } 33 | -------------------------------------------------------------------------------- /LGSTrayHID/HidppManagerService.cs: -------------------------------------------------------------------------------- 1 | using LGSTrayPrimitives.MessageStructs; 2 | using MessagePipe; 3 | using Microsoft.Extensions.Hosting; 4 | 5 | namespace LGSTrayHID 6 | { 7 | public class HidppManagerService : IHostedService 8 | { 9 | private readonly IDistributedPublisher _publisher; 10 | 11 | public HidppManagerService(IDistributedPublisher publisher) 12 | { 13 | _publisher = publisher; 14 | 15 | HidppManagerContext.Instance.HidppDeviceEvent += async (type, message) => 16 | { 17 | #if DEBUG 18 | if (message is InitMessage initMessage) 19 | { 20 | Console.WriteLine(initMessage.deviceName); 21 | } 22 | #endif 23 | 24 | await _publisher.PublishAsync(type, message); 25 | }; 26 | } 27 | 28 | public Task StartAsync(CancellationToken cancellationToken) 29 | { 30 | HidppManagerContext.Instance.Start(cancellationToken); 31 | 32 | return Task.CompletedTask; 33 | } 34 | 35 | public Task StopAsync(CancellationToken cancellationToken) 36 | { 37 | return Task.CompletedTask; 38 | } 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /LGSTrayHID/LGSTrayHID.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | WinExe 5 | 6 | 7 | Exe 8 | 9 | 10 | 11 | net8.0 12 | enable 13 | enable 14 | true 15 | true 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | PreserveNewest 32 | %(Filename)%(Extension) 33 | 34 | 35 | 36 | 37 | 38 | -------------------------------------------------------------------------------- /LGSTrayHID/HidApi/HidDeviceInfoHelpers.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Runtime.InteropServices; 5 | using System.Text; 6 | using System.Threading.Tasks; 7 | 8 | namespace LGSTrayHID.HidApi 9 | { 10 | public enum HidppMessageType : short 11 | { 12 | NONE = 0, 13 | SHORT, 14 | LONG, 15 | VERY_LONG 16 | } 17 | 18 | internal static class HidDeviceInfoHelpers 19 | { 20 | internal static string GetPath(this HidDeviceInfo deviceInfo) 21 | { 22 | unsafe 23 | { 24 | return Marshal.PtrToStringAnsi((nint)deviceInfo.Path)!; 25 | } 26 | } 27 | 28 | internal static HidppMessageType GetHidppMessageType(this HidDeviceInfo deviceInfo) 29 | { 30 | unsafe 31 | { 32 | if ((deviceInfo.UsagePage & 0xFF00) == 0xFF00) 33 | { 34 | return deviceInfo.Usage switch 35 | { 36 | 0x0001 => HidppMessageType.SHORT, 37 | 0x0002 => HidppMessageType.LONG, 38 | _ => HidppMessageType.NONE, 39 | }; 40 | } 41 | else 42 | { 43 | return HidppMessageType.NONE; 44 | } 45 | } 46 | } 47 | 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /LGSTrayCore/IServiceExtension.cs: -------------------------------------------------------------------------------- 1 | using LGSTrayCore.HttpServer; 2 | using LGSTrayCore.Managers; 3 | using LGSTrayPrimitives; 4 | using Microsoft.Extensions.Configuration; 5 | using Microsoft.Extensions.DependencyInjection; 6 | using Microsoft.Extensions.Hosting; 7 | 8 | namespace LGSTrayCore; 9 | 10 | public static class IServiceExtension 11 | { 12 | public static void AddWebserver(this IServiceCollection services, IConfiguration configs) 13 | { 14 | var settings = configs.Get()!; 15 | if (!settings.HTTPServer.Enabled) return; 16 | 17 | services.AddSingleton(); 18 | services.AddHostedService(); 19 | } 20 | 21 | public static void AddIDeviceManager(this IServiceCollection services, IConfiguration configs) where T : class, IDeviceManager, IHostedService 22 | { 23 | var settings = configs.Get()!; 24 | bool isEnabled = typeof(T) switch 25 | { 26 | { } when typeof(T) == typeof(GHubManager) => settings.GHub.Enabled, 27 | { } when typeof(T) == typeof(LGSTrayHIDManager) => settings.Native.Enabled, 28 | _ => false 29 | }; 30 | if (!isEnabled) return; 31 | 32 | services.AddSingleton(); 33 | services.AddSingleton(p => p.GetRequiredService()); 34 | services.AddSingleton(p => p.GetRequiredService()); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /LGSTrayUI/UserSettingsWrapper.cs: -------------------------------------------------------------------------------- 1 | using CommunityToolkit.Mvvm.ComponentModel; 2 | using System.Collections.Specialized; 3 | 4 | namespace LGSTrayUI 5 | { 6 | public partial class UserSettingsWrapper : ObservableObject 7 | { 8 | [System.Diagnostics.CodeAnalysis.SuppressMessage("Performance", "CA1822:Mark members as static", Justification = "")] 9 | public StringCollection SelectedDevices => Properties.Settings.Default.SelectedDevices; 10 | 11 | public bool NumericDisplay 12 | { 13 | get => Properties.Settings.Default.NumericDisplay; 14 | set 15 | { 16 | Properties.Settings.Default.NumericDisplay = value; 17 | Properties.Settings.Default.Save(); 18 | 19 | OnPropertyChanged(); 20 | } 21 | } 22 | 23 | public void AddDevice(string deviceId) 24 | { 25 | if (Properties.Settings.Default.SelectedDevices.Contains(deviceId)) 26 | { 27 | return; 28 | } 29 | 30 | Properties.Settings.Default.SelectedDevices.Add(deviceId); 31 | Properties.Settings.Default.Save(); 32 | 33 | OnPropertyChanged(nameof(SelectedDevices)); 34 | } 35 | 36 | public void RemoveDevice(string deviceId) 37 | { 38 | Properties.Settings.Default.SelectedDevices.Remove(deviceId); 39 | Properties.Settings.Default.Save(); 40 | 41 | OnPropertyChanged(nameof(SelectedDevices)); 42 | } 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /LGSTrayPrimitives/IPC/MessageStructs.cs: -------------------------------------------------------------------------------- 1 | using MessagePack; 2 | 3 | namespace LGSTrayPrimitives.MessageStructs; 4 | 5 | public enum IPCMessageType : byte 6 | { 7 | HEARTBEAT = 0, 8 | INIT, 9 | UPDATE 10 | } 11 | 12 | public enum IPCMessageRequestType : byte 13 | { 14 | BATTERY_UPDATE_REQUEST = 0 15 | } 16 | 17 | [Union(0, typeof(InitMessage))] 18 | [Union(1, typeof(UpdateMessage))] 19 | public abstract class IPCMessage(string deviceId) 20 | { 21 | [Key(0)] 22 | public string deviceId = deviceId; 23 | } 24 | 25 | [MessagePackObject] 26 | public class InitMessage(string deviceId, string deviceName, bool hasBattery, DeviceType deviceType) : IPCMessage(deviceId) 27 | { 28 | [Key(1)] 29 | public string deviceName = deviceName; 30 | 31 | [Key(2)] 32 | public bool hasBattery = hasBattery; 33 | 34 | [Key(3)] 35 | public DeviceType deviceType = deviceType; 36 | } 37 | 38 | [MessagePackObject] 39 | public class UpdateMessage( 40 | string deviceId, 41 | double batteryPercentage, 42 | PowerSupplyStatus powerSupplyStatus, 43 | int batteryMVolt, 44 | DateTimeOffset updateTime, 45 | double mileage = -1 46 | ) : IPCMessage(deviceId) 47 | { 48 | [Key(1)] 49 | public double batteryPercentage = batteryPercentage; 50 | 51 | [Key(2)] 52 | public PowerSupplyStatus powerSupplyStatus = powerSupplyStatus; 53 | 54 | [Key(3)] 55 | public int batteryMVolt = batteryMVolt; 56 | 57 | [Key(4)] 58 | public DateTimeOffset updateTime = updateTime; 59 | 60 | [Key(5)] 61 | public double Mileage = mileage; 62 | } 63 | 64 | [MessagePackObject] 65 | public class BatteryUpdateRequestMessage() 66 | { 67 | [Key(0)] 68 | public int id; 69 | } 70 | -------------------------------------------------------------------------------- /LGSTrayUI/LogiDeviceIcon.xaml: -------------------------------------------------------------------------------- 1 | 12 | 15 | 16 | 17 | 22 | 23 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | -------------------------------------------------------------------------------- /LGSTrayHID/Program.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Extensions.Hosting; 2 | using System.Diagnostics; 3 | using Microsoft.Extensions.DependencyInjection; 4 | using LGSTrayPrimitives.IPC; 5 | using Microsoft.Extensions.Configuration; 6 | using LGSTrayPrimitives; 7 | using Tommy.Extensions.Configuration; 8 | 9 | namespace LGSTrayHID 10 | { 11 | internal static class GlobalSettings 12 | { 13 | public static NativeDeviceManagerSettings settings = new(); 14 | } 15 | 16 | internal class Program 17 | { 18 | static async Task Main(string[] args) 19 | { 20 | var builder = Host.CreateEmptyApplicationBuilder(null); 21 | builder.Configuration.AddTomlFile("appsettings.toml"); 22 | 23 | GlobalSettings.settings = builder.Configuration.GetSection("Native") 24 | .Get() ?? GlobalSettings.settings; 25 | 26 | builder.Services.AddLGSMessagePipe(); 27 | builder.Services.AddHostedService(); 28 | 29 | var host = builder.Build(); 30 | 31 | _ = Task.Run(async () => 32 | { 33 | bool ret = int.TryParse(args.ElementAtOrDefault(0), out int parentPid); 34 | if (!ret) { 35 | #if DEBUG 36 | return; 37 | #else 38 | // Started without a parent, assume invalid. 39 | Environment.Exit(0); 40 | #endif 41 | } 42 | 43 | await Process.GetProcessById(parentPid).WaitForExitAsync(); 44 | 45 | CancellationTokenSource cts = new(5000); 46 | await host.StopAsync(cts.Token); 47 | 48 | Environment.Exit(0); 49 | }); 50 | 51 | await host.RunAsync(); 52 | } 53 | } 54 | } -------------------------------------------------------------------------------- /LGSTrayHID/HidApi/HidDevicePtr.cs: -------------------------------------------------------------------------------- 1 | #define PRINT 2 | using System.Threading.Channels; 3 | using static LGSTrayHID.HidApi.HidApi; 4 | 5 | namespace LGSTrayHID.HidApi 6 | { 7 | public readonly struct HidDevicePtr 8 | { 9 | private readonly nint _ptr; 10 | 11 | private HidDevicePtr(nint ptr) 12 | { 13 | _ptr = ptr; 14 | } 15 | 16 | public static implicit operator nint(HidDevicePtr ptr) => ptr._ptr; 17 | 18 | public static implicit operator HidDevicePtr(nint ptr) => new(ptr); 19 | 20 | public Task WriteAsync(byte[] buffer) 21 | { 22 | #if DEBUG && PRINT 23 | PrintBuffer($"0x{_ptr:X} - W", buffer); 24 | #endif 25 | var ret = HidWrite(this, buffer, (nuint)buffer.Length); 26 | 27 | return Task.FromResult(ret); 28 | } 29 | 30 | public int Read(byte[] buffer, int count, int timeout) 31 | { 32 | var ret = HidReadTimeOut(this, buffer, (nuint)count, timeout); 33 | #if DEBUG && PRINT 34 | PrintBuffer($"0x{_ptr:X} - R", buffer, ret < 1); 35 | #endif 36 | return ret; 37 | } 38 | 39 | #if DEBUG && PRINT 40 | private static int count = 0; 41 | private static readonly Channel _channel = Channel.CreateUnbounded(); 42 | 43 | static HidDevicePtr() 44 | { 45 | Thread t1 = new(async () => 46 | { 47 | while (true) 48 | { 49 | var str = await _channel.Reader.ReadAsync(); 50 | Console.WriteLine(str); 51 | } 52 | }); 53 | t1.Start(); 54 | } 55 | 56 | private static void PrintBuffer(string prefix, byte[] buffer, bool ignore = false) 57 | { 58 | if (ignore) 59 | { 60 | return; 61 | } 62 | 63 | var arr = string.Join(" ", Array.ConvertAll(buffer, x => x.ToString("X02"))); 64 | var str = $"{count:d04} - {prefix}: {arr}"; 65 | _channel.Writer.TryWrite(str); 66 | 67 | count++; 68 | } 69 | #endif 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /LGSTrayUI/MainTaskbarIconWrapper.cs: -------------------------------------------------------------------------------- 1 | using Hardcodet.Wpf.TaskbarNotification; 2 | using System; 3 | using System.Windows; 4 | 5 | namespace LGSTrayUI; 6 | 7 | public class MainTaskBarIcon : TaskbarIcon 8 | { 9 | public MainTaskBarIcon() : base() 10 | { 11 | ContextMenu = (System.Windows.Controls.ContextMenu) Application.Current.FindResource("SysTrayMenu"); 12 | BatteryIconDrawing.DrawUnknown(this); 13 | } 14 | } 15 | 16 | public class MainTaskbarIconWrapper : IDisposable 17 | { 18 | #region IDisposable 19 | private bool disposedValue; 20 | 21 | protected virtual void Dispose(bool disposing) 22 | { 23 | if (!disposedValue) 24 | { 25 | if (disposing) 26 | { 27 | _taskbarIcon?.Dispose(); 28 | LogiDeviceIcon.RefCountChanged -= OnRefCountChanged; 29 | } 30 | 31 | // TODO: free unmanaged resources (unmanaged objects) and override finalizer 32 | // TODO: set large fields to null 33 | disposedValue = true; 34 | } 35 | } 36 | 37 | // // TODO: override finalizer only if 'Dispose(bool disposing)' has code to free unmanaged resources 38 | // ~MainTaskbarIconWrapper() 39 | // { 40 | // // Do not change this code. Put cleanup code in 'Dispose(bool disposing)' method 41 | // Dispose(disposing: false); 42 | // } 43 | 44 | public void Dispose() 45 | { 46 | // Do not change this code. Put cleanup code in 'Dispose(bool disposing)' method 47 | Dispose(disposing: true); 48 | GC.SuppressFinalize(this); 49 | } 50 | #endregion 51 | 52 | private TaskbarIcon? _taskbarIcon = new MainTaskBarIcon(); 53 | 54 | public MainTaskbarIconWrapper() 55 | { 56 | LogiDeviceIcon.RefCountChanged += OnRefCountChanged; 57 | OnRefCountChanged(LogiDeviceIcon.RefCount); 58 | } 59 | 60 | private void OnRefCountChanged(int refCount) 61 | { 62 | if (refCount == 0) 63 | { 64 | _taskbarIcon ??= new MainTaskBarIcon(); 65 | } 66 | else 67 | { 68 | _taskbarIcon?.Dispose(); 69 | _taskbarIcon = null; 70 | } 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /LGSTrayHID/HidApi/HidApiHotPlug.cs: -------------------------------------------------------------------------------- 1 | global using HidHotPlugCallbackHandle = System.Int32; 2 | 3 | using System; 4 | using System.Collections.Generic; 5 | using System.Linq; 6 | using System.Runtime.InteropServices; 7 | using System.Text; 8 | using System.Threading.Tasks; 9 | 10 | namespace LGSTrayHID.HidApi 11 | { 12 | [Flags] 13 | internal enum HidApiHotPlugEvent 14 | { 15 | /** A device has been plugged in and is ready to use */ 16 | HID_API_HOTPLUG_EVENT_DEVICE_ARRIVED = (1 << 0), 17 | 18 | /** A device has left and is no longer available. 19 | It is the user's responsibility to call hid_close with a disconnected device. 20 | */ 21 | HID_API_HOTPLUG_EVENT_DEVICE_LEFT = (1 << 1) 22 | } 23 | 24 | [Flags] 25 | internal enum HidApiHotPlugFlag 26 | { 27 | NONE = 0, 28 | /** Arm the callback and fire it for all matching currently attached devices. */ 29 | HID_API_HOTPLUG_ENUMERATE = (1 << 0) 30 | } 31 | 32 | internal unsafe delegate int HidApiHotPlugEventCallbackFn(HidHotPlugCallbackHandle callbackHandle, HidDeviceInfo* device, HidApiHotPlugEvent hidApiHotPlugEvent, nint userData); 33 | 34 | internal static partial class HidApiHotPlug 35 | { 36 | [LibraryImport("hidapi", EntryPoint = "hid_hotplug_register_callback")] 37 | internal static unsafe partial int HidHotplugRegisterCallback(ushort vendor_id, 38 | ushort product_id, 39 | HidApiHotPlugEvent events, 40 | HidApiHotPlugFlag flags, 41 | HidApiHotPlugEventCallbackFn callback, 42 | nint user_data, 43 | HidHotPlugCallbackHandle* callback_handle); 44 | 45 | [LibraryImport("hidapi", EntryPoint = "hid_hotplug_deregister_callback")] 46 | internal static unsafe partial int HidHotplugDeregisterCallback(HidHotPlugCallbackHandle callback_handle); 47 | 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /LGSTrayHID/HidApi/HidApi.cs: -------------------------------------------------------------------------------- 1 | using System.Runtime.InteropServices; 2 | 3 | namespace LGSTrayHID.HidApi 4 | { 5 | [StructLayout(LayoutKind.Sequential)] 6 | internal readonly struct HidApiVersion 7 | { 8 | readonly int Major; 9 | readonly int Minor; 10 | readonly int Patch; 11 | 12 | public override readonly string ToString() 13 | { 14 | return $"{Major}.{Minor}.{Patch}"; 15 | } 16 | } 17 | 18 | internal static partial class HidApi 19 | { 20 | [LibraryImport("hidapi", EntryPoint = "hid_init")] 21 | internal static partial int HidInit(); 22 | 23 | [LibraryImport("hidapi", EntryPoint = "hid_exit")] 24 | internal static partial int HidExit(); 25 | 26 | [LibraryImport("hidapi", EntryPoint = "hid_enumerate")] 27 | internal static unsafe partial HidDeviceInfo* HidEnumerate(ushort vendor_id, ushort product_id); 28 | 29 | [LibraryImport("hidapi", EntryPoint = "hid_free_enumeration")] 30 | internal static unsafe partial void HidFreeEnumeration(HidDeviceInfo* devs); 31 | 32 | [LibraryImport("hidapi", EntryPoint = "hid_open_path")] 33 | private static unsafe partial nint _HidOpenPath(byte* path); 34 | 35 | internal static unsafe nint HidOpenPath(ref HidDeviceInfo dev) 36 | { 37 | return _HidOpenPath(dev.Path); 38 | } 39 | 40 | [LibraryImport("hidapi", EntryPoint = "hid_close")] 41 | internal static unsafe partial void HidClose(nint dev); 42 | 43 | [LibraryImport("hidapi", EntryPoint = "hid_write")] 44 | internal static unsafe partial int HidWrite(nint dev, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2), In] byte[] data, nuint length); 45 | 46 | [LibraryImport("hidapi", EntryPoint = "hid_read_timeout")] 47 | internal static unsafe partial int HidReadTimeOut(nint dev, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2), Out] byte[] data, nuint length, int milliseconds); 48 | 49 | [LibraryImport("hidapi", EntryPoint = "hid_version")] 50 | private static unsafe partial HidApiVersion* _HidVersion(); 51 | 52 | internal unsafe static HidApiVersion HidVersion() 53 | { 54 | return *_HidVersion(); 55 | } 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /LGSTrayUI/CheckTheme.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Win32; 2 | using System.ComponentModel; 3 | using System.Globalization; 4 | using System.Management; 5 | using System.Security.Principal; 6 | 7 | namespace LGSTrayUI 8 | { 9 | public static class CheckTheme 10 | { 11 | private const string RegistryKeyPath = @"Software\Microsoft\Windows\CurrentVersion\Themes\Personalize"; 12 | private const string RegistryValueName = "SystemUsesLightTheme"; 13 | 14 | private static bool _lightTheme = true; 15 | public static bool LightTheme => _lightTheme; 16 | 17 | public static string ThemeSuffix 18 | { 19 | get 20 | { 21 | return LightTheme ? "" : "_dark"; 22 | } 23 | } 24 | 25 | public static event PropertyChangedEventHandler? StaticPropertyChanged; 26 | 27 | static CheckTheme() 28 | { 29 | var currentUser = WindowsIdentity.GetCurrent(); 30 | string query = string.Format( 31 | CultureInfo.InvariantCulture, 32 | @"SELECT * FROM RegistryValueChangeEvent WHERE Hive = 'HKEY_USERS' AND KeyPath = '{0}\\{1}' AND ValueName = '{2}'", 33 | currentUser.User!.Value, 34 | RegistryKeyPath.Replace(@"\", @"\\"), 35 | RegistryValueName); 36 | 37 | try 38 | { 39 | var watcher = new ManagementEventWatcher(query); 40 | watcher.EventArrived += Watcher_EventArrived; 41 | 42 | watcher.Start(); 43 | UpdateThemeStatus(); 44 | } 45 | catch 46 | { 47 | // Fails on Win7 48 | _lightTheme = false; 49 | } 50 | 51 | } 52 | 53 | private static void UpdateThemeStatus() 54 | { 55 | var regPath = Registry.CurrentUser.OpenSubKey(RegistryKeyPath, false); 56 | int regFlag = (int)regPath!.GetValue(RegistryValueName, 0); 57 | 58 | _lightTheme = regFlag != 0; 59 | StaticPropertyChanged?.Invoke(typeof(CheckTheme), new(nameof(LightTheme))); 60 | } 61 | 62 | private static void Watcher_EventArrived(object sender, EventArrivedEventArgs e) 63 | { 64 | UpdateThemeStatus(); 65 | } 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /LGSTrayUI/NotifyIconResources.xaml: -------------------------------------------------------------------------------- 1 | 5 | 6 | 7 | 8 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 41 | 42 | -------------------------------------------------------------------------------- /LGSTrayUI/Properties/Settings.Designer.cs: -------------------------------------------------------------------------------- 1 | //------------------------------------------------------------------------------ 2 | // 3 | // This code was generated by a tool. 4 | // Runtime Version:4.0.30319.42000 5 | // 6 | // Changes to this file may cause incorrect behavior and will be lost if 7 | // the code is regenerated. 8 | // 9 | //------------------------------------------------------------------------------ 10 | 11 | namespace LGSTrayUI.Properties { 12 | 13 | 14 | [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] 15 | [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "17.6.0.0")] 16 | internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase { 17 | 18 | private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); 19 | 20 | public static Settings Default { 21 | get { 22 | return defaultInstance; 23 | } 24 | } 25 | 26 | [global::System.Configuration.UserScopedSettingAttribute()] 27 | [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] 28 | [global::System.Configuration.DefaultSettingValueAttribute("\r\n\r\n \r\n")] 31 | public global::System.Collections.Specialized.StringCollection SelectedDevices { 32 | get { 33 | return ((global::System.Collections.Specialized.StringCollection)(this["SelectedDevices"])); 34 | } 35 | set { 36 | this["SelectedDevices"] = value; 37 | } 38 | } 39 | 40 | [global::System.Configuration.UserScopedSettingAttribute()] 41 | [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] 42 | [global::System.Configuration.DefaultSettingValueAttribute("False")] 43 | public bool NumericDisplay { 44 | get { 45 | return ((bool)(this["NumericDisplay"])); 46 | } 47 | set { 48 | this["NumericDisplay"] = value; 49 | } 50 | } 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /LGSTrayUI/LogiDeviceViewModel.cs: -------------------------------------------------------------------------------- 1 | using CommunityToolkit.Mvvm.ComponentModel; 2 | using Hardcodet.Wpf.TaskbarNotification; 3 | using LGSTrayCore; 4 | using LGSTrayPrimitives.MessageStructs; 5 | using System; 6 | 7 | namespace LGSTrayUI 8 | { 9 | public class LogiDeviceViewModelFactory 10 | { 11 | private readonly LogiDeviceIconFactory _logiDeviceIconFactory; 12 | 13 | public LogiDeviceViewModelFactory(LogiDeviceIconFactory logiDeviceIconFactory) 14 | { 15 | _logiDeviceIconFactory = logiDeviceIconFactory; 16 | } 17 | 18 | public LogiDeviceViewModel CreateViewModel(Action? config = null) 19 | { 20 | LogiDeviceViewModel output = new(_logiDeviceIconFactory); 21 | config?.Invoke(output); 22 | 23 | return output; 24 | } 25 | } 26 | 27 | public partial class LogiDeviceViewModel : LogiDevice 28 | { 29 | private readonly LogiDeviceIconFactory _logiDeviceIconFactory; 30 | 31 | [ObservableProperty] 32 | private bool _isChecked = false; 33 | 34 | private LogiDeviceIcon? taskbarIcon; 35 | 36 | public LogiDeviceViewModel(LogiDeviceIconFactory logiDeviceIconFactory) 37 | { 38 | _logiDeviceIconFactory = logiDeviceIconFactory; 39 | } 40 | 41 | partial void OnIsCheckedChanged(bool oldValue, bool newValue) 42 | { 43 | if (newValue) 44 | { 45 | taskbarIcon ??= _logiDeviceIconFactory.CreateDeviceIcon(this); 46 | } 47 | else 48 | { 49 | taskbarIcon?.Dispose(); 50 | taskbarIcon = null; 51 | } 52 | } 53 | 54 | public void UpdateState(InitMessage initMessage) 55 | { 56 | if (string.IsNullOrEmpty(DeviceId) || DeviceId == NOT_FOUND) 57 | { 58 | DeviceId = initMessage.deviceId; 59 | } 60 | 61 | DeviceName = initMessage.deviceName; 62 | HasBattery = initMessage.hasBattery; 63 | DeviceType = initMessage.deviceType; 64 | } 65 | 66 | public void UpdateState(UpdateMessage updateMessage) 67 | { 68 | BatteryPercentage = updateMessage.batteryPercentage; 69 | PowerSupplyStatus = updateMessage.powerSupplyStatus; 70 | BatteryVoltage = updateMessage.batteryMVolt / 1000.0; 71 | BatteryMileage = updateMessage.Mileage; 72 | LastUpdate = updateMessage.updateTime; 73 | } 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /LGSTrayHID/Features/Battery1001.cs: -------------------------------------------------------------------------------- 1 | using LGSTrayPrimitives; 2 | using static LGSTrayPrimitives.PowerSupplyStatus; 3 | 4 | namespace LGSTrayHID.Features 5 | { 6 | public static class Battery1001 7 | { 8 | static readonly int[] _mvLUT = [ 9 | 4186, 4156, 4143, 4133, 4122, 4113, 4103, 4094, 4086, 4075, 10 | 4067, 4059, 4051, 4043, 4035, 4027, 4019, 4011, 4003, 3997, 11 | 3989, 3983, 3976, 3969, 3961, 3955, 3949, 3942, 3935, 3929, 12 | 3922, 3916, 3909, 3902, 3896, 3890, 3883, 3877, 3870, 3865, 13 | 3859, 3853, 3848, 3842, 3837, 3833, 3828, 3824, 3819, 3815, 14 | 3811, 3808, 3804, 3800, 3797, 3793, 3790, 3787, 3784, 3781, 15 | 3778, 3775, 3772, 3770, 3767, 3764, 3762, 3759, 3757, 3754, 16 | 3751, 3748, 3744, 3741, 3737, 3734, 3730, 3726, 3724, 3720, 17 | 3717, 3714, 3710, 3706, 3702, 3697, 3693, 3688, 3683, 3677, 18 | 3671, 3666, 3662, 3658, 3654, 3646, 3633, 3612, 3579, 3537 19 | ]; 20 | 21 | private static double LookupBatPercent(int mv) 22 | { 23 | for (int i = 0; i < _mvLUT.Length; i++) 24 | { 25 | if (mv > _mvLUT[i]) 26 | { 27 | return _mvLUT.Length - i; 28 | } 29 | } 30 | 31 | return 0; 32 | } 33 | 34 | public static async Task GetBatteryAsync(HidppDevice device) 35 | { 36 | Hidpp20 buffer = new byte[7] { 0x10, device.DeviceIdx, device.FeatureMap[0x1001], 0x00 | HidppDevices.SW_ID, 0x00, 0x00, 0x00 }; 37 | Hidpp20 ret = await device.Parent.WriteRead20(device.Parent.DevShort, buffer); 38 | 39 | if (ret.Length == 0) { return null; } 40 | 41 | int mv = (ret.GetParam(0) << 8) + ret.GetParam(1); 42 | double batPercent = LookupBatPercent(mv); 43 | byte flags = ret.GetParam(2); 44 | 45 | PowerSupplyStatus status; 46 | if ((flags & 0x80) > 0) 47 | { 48 | status = (flags & 0x07) switch 49 | { 50 | 0 => POWER_SUPPLY_STATUS_CHARGING, 51 | 1 => POWER_SUPPLY_STATUS_FULL, 52 | 2 => POWER_SUPPLY_STATUS_NOT_CHARGING, 53 | _ => POWER_SUPPLY_STATUS_UNKNOWN, 54 | }; 55 | } 56 | else 57 | { 58 | status = POWER_SUPPLY_STATUS_DISCHARGING; 59 | } 60 | 61 | return new BatteryUpdateReturn(batPercent, status, mv); 62 | } 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | ############################################################################### 2 | # Set default behavior to automatically normalize line endings. 3 | ############################################################################### 4 | * text=auto 5 | 6 | ############################################################################### 7 | # Set default behavior for command prompt diff. 8 | # 9 | # This is need for earlier builds of msysgit that does not have it on by 10 | # default for csharp files. 11 | # Note: This is only used by command line 12 | ############################################################################### 13 | #*.cs diff=csharp 14 | 15 | ############################################################################### 16 | # Set the merge driver for project and solution files 17 | # 18 | # Merging from the command prompt will add diff markers to the files if there 19 | # are conflicts (Merging from VS is not affected by the settings below, in VS 20 | # the diff markers are never inserted). Diff markers may cause the following 21 | # file extensions to fail to load in VS. An alternative would be to treat 22 | # these files as binary and thus will always conflict and require user 23 | # intervention with every merge. To do so, just uncomment the entries below 24 | ############################################################################### 25 | #*.sln merge=binary 26 | #*.csproj merge=binary 27 | #*.vbproj merge=binary 28 | #*.vcxproj merge=binary 29 | #*.vcproj merge=binary 30 | #*.dbproj merge=binary 31 | #*.fsproj merge=binary 32 | #*.lsproj merge=binary 33 | #*.wixproj merge=binary 34 | #*.modelproj merge=binary 35 | #*.sqlproj merge=binary 36 | #*.wwaproj merge=binary 37 | 38 | ############################################################################### 39 | # behavior for image files 40 | # 41 | # image files are treated as binary by default. 42 | ############################################################################### 43 | #*.jpg binary 44 | #*.png binary 45 | #*.gif binary 46 | 47 | ############################################################################### 48 | # diff behavior for common document formats 49 | # 50 | # Convert binary document formats to text before diffing them. This feature 51 | # is only available from the command line. Turn it on by uncommenting the 52 | # entries below. 53 | ############################################################################### 54 | #*.doc diff=astextplain 55 | #*.DOC diff=astextplain 56 | #*.docx diff=astextplain 57 | #*.DOCX diff=astextplain 58 | #*.dot diff=astextplain 59 | #*.DOT diff=astextplain 60 | #*.pdf diff=astextplain 61 | #*.PDF diff=astextplain 62 | #*.rtf diff=astextplain 63 | #*.RTF diff=astextplain 64 | -------------------------------------------------------------------------------- /publish.py: -------------------------------------------------------------------------------- 1 | from multiprocessing import Process 2 | import argparse 3 | import glob 4 | import os 5 | import os.path 6 | import subprocess 7 | import xml.etree.ElementTree as ET 8 | import zipfile 9 | 10 | PUB_PROFILES = [ 11 | ('Standalone', '-standalone'), 12 | ('Framedep', '') 13 | ] 14 | 15 | FILE_TYPES = [ 16 | '*.exe', 17 | '*.pdb', 18 | '*.dll', 19 | '*.toml' 20 | ] 21 | 22 | TARGET_PROJ = 'LGSTrayUI' 23 | PROJ_FILE = f'./{TARGET_PROJ}/{TARGET_PROJ}.csproj' 24 | TARGET_VER = ET.parse(PROJ_FILE).getroot() \ 25 | .findall('./PropertyGroup/VersionPrefix')[0].text 26 | 27 | def file_list(zipFolder): 28 | for fileType in FILE_TYPES: 29 | yield from glob.glob(os.path.join(zipFolder, fileType), recursive=True) 30 | 31 | def create_zip(zipPath, zipFolder): 32 | with zipfile.ZipFile(zipPath, 'w', zipfile.ZIP_DEFLATED) as zip: 33 | for file in file_list(zipFolder): 34 | zip.write(file, os.path.basename(file)) 35 | 36 | class PublishHelper: 37 | def __init__(self, publish_root, no_zip): 38 | self.zip_threads = [] 39 | 40 | self.publish_root = publish_root 41 | self.no_zip = no_zip 42 | 43 | def join(self): 44 | for p in self.zip_threads: 45 | p.join() 46 | 47 | def publish_profile(self, profile, zip_suffix): 48 | safe_ver = TARGET_VER.replace('.', '_') 49 | 50 | for proj in ["LGSTrayHID", "LGSTrayUI"]: 51 | subprocess.run( 52 | ["dotnet", "publish", f"{proj}/{proj}.csproj", f"/p:PublishProfile={profile}", f"/p:Version={TARGET_VER}"], 53 | shell=False 54 | ) 55 | 56 | if self.no_zip: 57 | return 58 | 59 | zipName = f'Release_v{safe_ver}{zip_suffix}.zip' 60 | 61 | zipPath = os.path.join(self.publish_root, "..", zipName) 62 | zipFolder = os.path.join(self.publish_root, profile) 63 | 64 | print("\n---") 65 | print(f"Zipping {profile} ...") 66 | p = Process(target=create_zip, args=(zipPath, zipFolder)) 67 | p.start() 68 | self.zip_threads.append(p) 69 | print("---") 70 | 71 | def main(no_zip, version_suffix): 72 | global TARGET_VER 73 | TARGET_VER += version_suffix 74 | 75 | publish_root = os.path.join('./bin/Release/Publish/win-x64') 76 | 77 | helper = PublishHelper(publish_root, no_zip) 78 | for profile, zip_suffix in PUB_PROFILES: 79 | helper.publish_profile(profile, zip_suffix) 80 | 81 | helper.join() 82 | 83 | if __name__ == "__main__": 84 | parser = argparse.ArgumentParser( 85 | prog='publish.py', 86 | description='Publish helper' 87 | ) 88 | parser.add_argument('--no-zip', action='store_true') 89 | parser.add_argument('--version-suffix', default='') 90 | 91 | args = parser.parse_args() 92 | 93 | main(**vars(args)) 94 | print("\nPackaging done.") -------------------------------------------------------------------------------- /LGSTrayCore/HttpServer/HttpServer.cs: -------------------------------------------------------------------------------- 1 | using EmbedIO; 2 | using EmbedIO.Net; 3 | using EmbedIO.WebApi; 4 | using LGSTrayPrimitives; 5 | using Microsoft.Extensions.Hosting; 6 | using Microsoft.Extensions.Options; 7 | 8 | namespace LGSTrayCore.HttpServer 9 | { 10 | public class HttpServer : IHostedService, IDisposable 11 | { 12 | #region IDisposable 13 | private bool disposedValue; 14 | 15 | protected virtual void Dispose(bool disposing) 16 | { 17 | if (!disposedValue) 18 | { 19 | if (disposing) 20 | { 21 | _server.Dispose(); 22 | } 23 | 24 | // TODO: free unmanaged resources (unmanaged objects) and override finalizer 25 | // TODO: set large fields to null 26 | disposedValue = true; 27 | } 28 | } 29 | 30 | // // TODO: override finalizer only if 'Dispose(bool disposing)' has code to free unmanaged resources 31 | // ~WebServer() 32 | // { 33 | // // Do not change this code. Put cleanup code in 'Dispose(bool disposing)' method 34 | // Dispose(disposing: false); 35 | // } 36 | 37 | public void Dispose() 38 | { 39 | // Do not change this code. Put cleanup code in 'Dispose(bool disposing)' method 40 | Dispose(disposing: true); 41 | GC.SuppressFinalize(this); 42 | } 43 | #endregion 44 | 45 | private readonly AppSettings _appSettings; 46 | private readonly HttpControllerFactory _httpControllerFactory; 47 | 48 | private CancellationTokenSource _serverCts = null!; 49 | private WebServer _server = null!; 50 | 51 | public HttpServer(IOptions appSettings, HttpControllerFactory httpControllerFactory) 52 | { 53 | _appSettings = appSettings.Value; 54 | _httpControllerFactory = httpControllerFactory; 55 | } 56 | 57 | public Task StartAsync(CancellationToken cancellationToken) 58 | { 59 | _serverCts = new(); 60 | _server = CreateServer(_appSettings, _httpControllerFactory); 61 | _server.RunAsync(_serverCts.Token); 62 | 63 | return Task.CompletedTask; 64 | } 65 | 66 | public Task StopAsync(CancellationToken cancellationToken) 67 | { 68 | _serverCts.Cancel(); 69 | 70 | return Task.CompletedTask; 71 | } 72 | 73 | private static WebServer CreateServer(AppSettings appSettings, HttpControllerFactory httpControllerFactory) 74 | { 75 | EndPointManager.UseIpv6 = appSettings.HTTPServer.UseIpv6; 76 | 77 | var server = new WebServer(o => o.WithUrlPrefix(appSettings.HTTPServer.UrlPrefix)) 78 | .WithWebApi("/", m => m.WithController(httpControllerFactory.CreateController)); 79 | 80 | return server; 81 | } 82 | } 83 | } 84 | -------------------------------------------------------------------------------- /LGSTrayCore/LogiDevice.cs: -------------------------------------------------------------------------------- 1 | using CommunityToolkit.Mvvm.ComponentModel; 2 | using LGSTrayPrimitives; 3 | 4 | namespace LGSTrayCore 5 | { 6 | public partial class LogiDevice : ObservableObject 7 | { 8 | public const string NOT_FOUND = "NOT FOUND"; 9 | 10 | [ObservableProperty] 11 | private DeviceType _deviceType; 12 | 13 | [ObservableProperty] 14 | private string _deviceId = NOT_FOUND; 15 | 16 | [ObservableProperty] 17 | [NotifyPropertyChangedFor(nameof(ToolTipString))] 18 | private string _deviceName = NOT_FOUND; 19 | 20 | [ObservableProperty] 21 | private bool _hasBattery = true; 22 | 23 | [ObservableProperty] 24 | [NotifyPropertyChangedFor(nameof(ToolTipString))] 25 | private double _batteryPercentage = -1; 26 | 27 | [ObservableProperty] 28 | [NotifyPropertyChangedFor(nameof(ToolTipString))] 29 | private double _batteryVoltage; 30 | 31 | [ObservableProperty] 32 | [NotifyPropertyChangedFor(nameof(ToolTipString))] 33 | private double _batteryMileage; 34 | 35 | 36 | [ObservableProperty] 37 | private PowerSupplyStatus _powerSupplyStatus; 38 | 39 | [ObservableProperty] 40 | [NotifyPropertyChangedFor(nameof(ToolTipString))] 41 | private DateTimeOffset _lastUpdate = DateTimeOffset.MinValue; 42 | 43 | public string ToolTipString 44 | { 45 | get 46 | { 47 | #if DEBUG 48 | return $"{DeviceName}, {BatteryPercentage:f2}% - {LastUpdate}"; 49 | #else 50 | return $"{DeviceName}, {BatteryPercentage:f2}%"; 51 | #endif 52 | } 53 | } 54 | 55 | public Func? UpdateBatteryFunc; 56 | public async Task UpdateBatteryAsync() 57 | { 58 | if (UpdateBatteryFunc != null) 59 | { 60 | await UpdateBatteryFunc.Invoke(); 61 | } 62 | } 63 | 64 | partial void OnLastUpdateChanged(DateTimeOffset value) 65 | { 66 | Console.WriteLine(ToolTipString); 67 | } 68 | 69 | public string GetXmlData() 70 | { 71 | return 72 | $"" + 73 | $"" + 74 | $"{DeviceId}" + 75 | $"{DeviceName}" + 76 | $"{DeviceType}" + 77 | $"{BatteryPercentage:f2}" + 78 | $"{BatteryVoltage:f2}" + 79 | $"{BatteryMileage:f2}" + 80 | $"{PowerSupplyStatus == PowerSupplyStatus.POWER_SUPPLY_STATUS_CHARGING}" + 81 | $"{LastUpdate}" + 82 | $"" 83 | ; 84 | } 85 | } 86 | } 87 | -------------------------------------------------------------------------------- /LGSTrayCore/HttpServer/HttpController.cs: -------------------------------------------------------------------------------- 1 | using EmbedIO.Routing; 2 | using EmbedIO; 3 | using EmbedIO.WebApi; 4 | using System.Reflection; 5 | 6 | namespace LGSTrayCore.HttpServer; 7 | 8 | public class HttpControllerFactory 9 | { 10 | private readonly ILogiDeviceCollection _logiDeviceCollection; 11 | 12 | public HttpControllerFactory(ILogiDeviceCollection logiDeviceCollection) 13 | { 14 | _logiDeviceCollection = logiDeviceCollection; 15 | } 16 | 17 | public HttpController CreateController() 18 | { 19 | return new HttpController(_logiDeviceCollection); 20 | } 21 | } 22 | 23 | public class HttpController : WebApiController 24 | { 25 | private static readonly string _assemblyVersion = Assembly.GetEntryAssembly()?.GetCustomAttribute()?.InformationalVersion!; 26 | private readonly ILogiDeviceCollection _logiDeviceCollection; 27 | 28 | public HttpController(ILogiDeviceCollection logiDeviceCollection) 29 | { 30 | _logiDeviceCollection = logiDeviceCollection; 31 | } 32 | 33 | private void DefaultResponse(string contentType = "text/html") 34 | { 35 | Response.ContentType = contentType; 36 | Response.DisableCaching(); 37 | Response.KeepAlive = false; 38 | Response.Headers.Add("Access-Control-Allow-Origin", "*"); 39 | } 40 | 41 | [Route(HttpVerbs.Get, "/")] 42 | [Route(HttpVerbs.Get, "/devices")] 43 | public void GetDevices() 44 | { 45 | DefaultResponse(); 46 | 47 | using var tw = HttpContext.OpenResponseText(); 48 | tw.Write(""); 49 | 50 | tw.Write("By Device ID
"); 51 | foreach (var logiDevice in _logiDeviceCollection.GetDevices()) 52 | { 53 | tw.Write($"{logiDevice.DeviceName} : {logiDevice.DeviceId}
"); 54 | } 55 | 56 | tw.Write("
By Device Name
"); 57 | foreach (var logiDevice in _logiDeviceCollection.GetDevices()) 58 | { 59 | tw.Write($"{logiDevice.DeviceName}
"); 60 | } 61 | 62 | tw.Write("

"); 63 | tw.Write($"LGSTray version: {_assemblyVersion}
"); 64 | tw.Write(""); 65 | 66 | return; 67 | } 68 | 69 | [Route(HttpVerbs.Get, "/device/{deviceIden}")] 70 | public void GetDevice(string deviceIden) 71 | { 72 | var logiDevice = _logiDeviceCollection.GetDevices().FirstOrDefault(x => x.DeviceId == deviceIden); 73 | logiDevice ??= _logiDeviceCollection.GetDevices().FirstOrDefault(x => x.DeviceName == deviceIden); 74 | 75 | using var tw = HttpContext.OpenResponseText(); 76 | if (logiDevice == null) 77 | { 78 | HttpContext.Response.StatusCode = 404; 79 | tw.Write($"{deviceIden} not found."); 80 | return; 81 | } 82 | 83 | DefaultResponse("text/xml"); 84 | 85 | tw.Write(logiDevice.GetXmlData()); 86 | } 87 | } 88 | -------------------------------------------------------------------------------- /LGSTrayBattery.sln: -------------------------------------------------------------------------------- 1 | 2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 17 4 | VisualStudioVersion = 17.0.31903.59 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "LGSTrayHID", "LGSTrayHID\LGSTrayHID.csproj", "{EEA4B09D-17A7-486B-B570-72751D0D6071}" 7 | ProjectSection(ProjectDependencies) = postProject 8 | {F85B7D61-5588-4BC1-8A46-E2A6899CFBC0} = {F85B7D61-5588-4BC1-8A46-E2A6899CFBC0} 9 | EndProjectSection 10 | EndProject 11 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "LGSTrayCore", "LGSTrayCore\LGSTrayCore.csproj", "{FAF4FA85-B52C-4587-92E7-0D55645625AB}" 12 | ProjectSection(ProjectDependencies) = postProject 13 | {F85B7D61-5588-4BC1-8A46-E2A6899CFBC0} = {F85B7D61-5588-4BC1-8A46-E2A6899CFBC0} 14 | EndProjectSection 15 | EndProject 16 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "LGSTrayUI", "LGSTrayUI\LGSTrayUI.csproj", "{2C80ABC3-6A95-4ED6-9265-D901CC6607BF}" 17 | EndProject 18 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "LGSTrayPrimitives", "LGSTrayPrimitives\LGSTrayPrimitives.csproj", "{F85B7D61-5588-4BC1-8A46-E2A6899CFBC0}" 19 | EndProject 20 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{9951E942-59D1-42A5-ABE3-7E6BAEDCDCEA}" 21 | ProjectSection(SolutionItems) = preProject 22 | .editorconfig = .editorconfig 23 | EndProjectSection 24 | EndProject 25 | Global 26 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 27 | Debug|Any CPU = Debug|Any CPU 28 | Release|Any CPU = Release|Any CPU 29 | EndGlobalSection 30 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 31 | {EEA4B09D-17A7-486B-B570-72751D0D6071}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 32 | {EEA4B09D-17A7-486B-B570-72751D0D6071}.Debug|Any CPU.Build.0 = Debug|Any CPU 33 | {EEA4B09D-17A7-486B-B570-72751D0D6071}.Release|Any CPU.ActiveCfg = Release|Any CPU 34 | {EEA4B09D-17A7-486B-B570-72751D0D6071}.Release|Any CPU.Build.0 = Release|Any CPU 35 | {FAF4FA85-B52C-4587-92E7-0D55645625AB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 36 | {FAF4FA85-B52C-4587-92E7-0D55645625AB}.Debug|Any CPU.Build.0 = Debug|Any CPU 37 | {FAF4FA85-B52C-4587-92E7-0D55645625AB}.Release|Any CPU.ActiveCfg = Release|Any CPU 38 | {FAF4FA85-B52C-4587-92E7-0D55645625AB}.Release|Any CPU.Build.0 = Release|Any CPU 39 | {2C80ABC3-6A95-4ED6-9265-D901CC6607BF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 40 | {2C80ABC3-6A95-4ED6-9265-D901CC6607BF}.Debug|Any CPU.Build.0 = Debug|Any CPU 41 | {2C80ABC3-6A95-4ED6-9265-D901CC6607BF}.Release|Any CPU.ActiveCfg = Release|Any CPU 42 | {2C80ABC3-6A95-4ED6-9265-D901CC6607BF}.Release|Any CPU.Build.0 = Release|Any CPU 43 | {F85B7D61-5588-4BC1-8A46-E2A6899CFBC0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 44 | {F85B7D61-5588-4BC1-8A46-E2A6899CFBC0}.Debug|Any CPU.Build.0 = Debug|Any CPU 45 | {F85B7D61-5588-4BC1-8A46-E2A6899CFBC0}.Release|Any CPU.ActiveCfg = Release|Any CPU 46 | {F85B7D61-5588-4BC1-8A46-E2A6899CFBC0}.Release|Any CPU.Build.0 = Release|Any CPU 47 | EndGlobalSection 48 | GlobalSection(SolutionProperties) = preSolution 49 | HideSolutionNode = FALSE 50 | EndGlobalSection 51 | GlobalSection(ExtensibilityGlobals) = postSolution 52 | SolutionGuid = {435417D2-E9A4-4795-9AAB-4B5E4D881D40} 53 | EndGlobalSection 54 | EndGlobal 55 | -------------------------------------------------------------------------------- /LGSTrayUI/LGSTrayUI.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | WinExe 4 | 5 | 6 | Exe 7 | 8 | 9 | 10 | net8.0-windows 11 | enable 12 | true 13 | true 14 | true 15 | 3.0.3 16 | LGSTray 17 | Resources\logo_black.ico 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | all 33 | runtime; build; native; contentfiles; analyzers; buildtransitive 34 | 35 | 36 | 37 | 38 | 39 | all 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | True 55 | True 56 | Resources.resx 57 | 58 | 59 | True 60 | True 61 | Settings.settings 62 | 63 | 64 | 65 | 66 | 67 | ResXFileCodeGenerator 68 | Resources.Designer.cs 69 | 70 | 71 | 72 | 73 | 74 | Always 75 | 76 | 77 | SettingsSingleFileGenerator 78 | Settings.Designer.cs 79 | 80 | 81 | 82 | 83 | -------------------------------------------------------------------------------- /LGSTrayUI/LogiDeviceCollection.cs: -------------------------------------------------------------------------------- 1 | using LGSTrayCore; 2 | using LGSTrayPrimitives.MessageStructs; 3 | using MessagePipe; 4 | using System; 5 | using System.Collections.Generic; 6 | using System.Collections.ObjectModel; 7 | using System.Diagnostics.CodeAnalysis; 8 | using System.Linq; 9 | using System.Windows; 10 | 11 | namespace LGSTrayUI 12 | { 13 | public class LogiDeviceCollection : ILogiDeviceCollection 14 | { 15 | private readonly UserSettingsWrapper _userSettings; 16 | private readonly LogiDeviceViewModelFactory _logiDeviceViewModelFactory; 17 | private readonly ISubscriber _subscriber; 18 | 19 | public ObservableCollection Devices { get; } = []; 20 | public IEnumerable GetDevices() => Devices; 21 | 22 | public LogiDeviceCollection( 23 | UserSettingsWrapper userSettings, 24 | LogiDeviceViewModelFactory logiDeviceViewModelFactory, 25 | ISubscriber subscriber 26 | ) 27 | { 28 | _userSettings = userSettings; 29 | _logiDeviceViewModelFactory = logiDeviceViewModelFactory; 30 | _subscriber = subscriber; 31 | 32 | _subscriber.Subscribe(x => 33 | { 34 | if (x is InitMessage initMessage) 35 | { 36 | OnInitMessage(initMessage); 37 | } 38 | else if (x is UpdateMessage updateMessage) 39 | { 40 | OnUpdateMessage(updateMessage); 41 | } 42 | }); 43 | 44 | LoadPreviouslySelectedDevices(); 45 | } 46 | 47 | private void LoadPreviouslySelectedDevices() 48 | { 49 | foreach (var deviceId in _userSettings.SelectedDevices) 50 | { 51 | if (string.IsNullOrEmpty(deviceId)) 52 | { 53 | continue; 54 | } 55 | 56 | Devices.Add( 57 | _logiDeviceViewModelFactory.CreateViewModel((x) => 58 | { 59 | x.DeviceId = deviceId!; 60 | x.DeviceName = "Not Initialised"; 61 | x.IsChecked = true; 62 | }) 63 | ); 64 | } 65 | } 66 | 67 | public bool TryGetDevice(string deviceId, [NotNullWhen(true)] out LogiDevice? device) 68 | { 69 | device = Devices.SingleOrDefault(x => x.DeviceId == deviceId); 70 | 71 | return device != null; 72 | } 73 | 74 | public void OnInitMessage(InitMessage initMessage) 75 | { 76 | LogiDeviceViewModel? dev = Devices.SingleOrDefault(x => x.DeviceId == initMessage.deviceId); 77 | if (dev != null) 78 | { 79 | Application.Current.Dispatcher.BeginInvoke(() => dev.UpdateState(initMessage)); 80 | 81 | return; 82 | } 83 | 84 | dev = _logiDeviceViewModelFactory.CreateViewModel((x) => x.UpdateState(initMessage)); 85 | 86 | Application.Current.Dispatcher.BeginInvoke(() => Devices.Add(dev)); 87 | } 88 | 89 | public void OnUpdateMessage(UpdateMessage updateMessage) 90 | { 91 | Application.Current.Dispatcher.BeginInvoke(() => 92 | { 93 | var device = Devices.FirstOrDefault(dev => dev.DeviceId == updateMessage.deviceId); 94 | if (device == null) { return; } 95 | 96 | device.UpdateState(updateMessage); 97 | }); 98 | } 99 | } 100 | } 101 | -------------------------------------------------------------------------------- /LGSTrayUI/App.xaml.cs: -------------------------------------------------------------------------------- 1 | using LGSTrayCore; 2 | using LGSTrayCore.Managers; 3 | using Microsoft.Extensions.DependencyInjection; 4 | using Microsoft.Extensions.Hosting; 5 | using System.Windows; 6 | using System; 7 | using LGSTrayPrimitives.IPC; 8 | using System.Globalization; 9 | using System.IO; 10 | using System.Threading; 11 | using LGSTrayPrimitives; 12 | using Tommy.Extensions.Configuration; 13 | 14 | using static LGSTrayUI.AppExtensions; 15 | using System.Threading.Tasks; 16 | 17 | namespace LGSTrayUI; 18 | 19 | /// 20 | /// Interaction logic for App.xaml 21 | /// 22 | public partial class App : Application 23 | { 24 | protected override async void OnStartup(StartupEventArgs e) 25 | { 26 | base.OnStartup(e); 27 | 28 | Directory.SetCurrentDirectory(AppContext.BaseDirectory); 29 | Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture; 30 | CultureInfo.DefaultThreadCurrentCulture = CultureInfo.InvariantCulture; 31 | AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CrashHandler); 32 | 33 | EnableEfficiencyMode(); 34 | 35 | var builder = Host.CreateEmptyApplicationBuilder(null); 36 | await LoadAppSettings(builder.Configuration); 37 | 38 | builder.Services.Configure(builder.Configuration); 39 | builder.Services.AddLGSMessagePipe(true); 40 | builder.Services.AddSingleton(); 41 | 42 | builder.Services.AddSingleton(); 43 | builder.Services.AddSingleton(); 44 | 45 | builder.Services.AddWebserver(builder.Configuration); 46 | 47 | builder.Services.AddIDeviceManager(builder.Configuration); 48 | builder.Services.AddIDeviceManager(builder.Configuration); 49 | builder.Services.AddSingleton(); 50 | 51 | builder.Services.AddSingleton(); 52 | builder.Services.AddHostedService(); 53 | 54 | var host = builder.Build(); 55 | await host.RunAsync(); 56 | Dispatcher.InvokeShutdown(); 57 | } 58 | 59 | static async Task LoadAppSettings(Microsoft.Extensions.Configuration.ConfigurationManager config) 60 | { 61 | try 62 | { 63 | config.AddTomlFile("appsettings.toml"); 64 | } 65 | catch (Exception ex) 66 | { 67 | if (ex is FileNotFoundException || ex is InvalidDataException) 68 | { 69 | var msgBoxRet = MessageBox.Show( 70 | "Failed to read settings, do you want reset to default?", 71 | "LGSTray - Settings Load Error", 72 | MessageBoxButton.YesNo, MessageBoxImage.Error, MessageBoxResult.No 73 | ); 74 | 75 | if (msgBoxRet == MessageBoxResult.Yes) 76 | { 77 | await File.WriteAllBytesAsync( 78 | Path.Combine(AppContext.BaseDirectory, "appsettings.toml"), 79 | LGSTrayUI.Properties.Resources.defaultAppsettings 80 | ); 81 | } 82 | 83 | config.AddTomlFile("appsettings.toml"); 84 | } 85 | else 86 | { 87 | throw; 88 | } 89 | } 90 | } 91 | 92 | private void CrashHandler(object sender, UnhandledExceptionEventArgs args) 93 | { 94 | Exception e = (Exception)args.ExceptionObject; 95 | long unixTime = DateTimeOffset.Now.ToUnixTimeSeconds(); 96 | 97 | using StreamWriter writer = new($"./crashlog_{unixTime}.log", false); 98 | writer.WriteLine(e.ToString()); 99 | } 100 | } -------------------------------------------------------------------------------- /LGSTrayUI/LogiDeviceIcon.xaml.cs: -------------------------------------------------------------------------------- 1 | using Hardcodet.Wpf.TaskbarNotification; 2 | using LGSTrayCore; 3 | using LGSTrayPrimitives; 4 | using Microsoft.Extensions.Options; 5 | using System; 6 | using System.ComponentModel; 7 | using System.Windows.Controls; 8 | 9 | namespace LGSTrayUI 10 | { 11 | public class LogiDeviceIconFactory 12 | { 13 | private readonly AppSettings _appSettings; 14 | private readonly UserSettingsWrapper _userSettings; 15 | 16 | public LogiDeviceIconFactory(IOptions appSettings, UserSettingsWrapper userSettings) 17 | { 18 | _appSettings = appSettings.Value; 19 | _userSettings = userSettings; 20 | } 21 | 22 | public LogiDeviceIcon CreateDeviceIcon(LogiDevice device, Action? config = null) 23 | { 24 | LogiDeviceIcon output = new(device, _appSettings, _userSettings); 25 | config?.Invoke(output); 26 | 27 | return output; 28 | } 29 | } 30 | 31 | public partial class LogiDeviceIcon : UserControl, IDisposable 32 | { 33 | #region IDisposable 34 | private bool disposedValue; 35 | protected virtual void Dispose(bool disposing) 36 | { 37 | if (!disposedValue) 38 | { 39 | if (disposing) 40 | { 41 | // TODO: dispose managed state (managed objects) 42 | SubRef(); 43 | } 44 | 45 | // TODO: free unmanaged resources (unmanaged objects) and override finalizer 46 | // TODO: set large fields to null 47 | disposedValue = true; 48 | taskbarIcon.Dispose(); 49 | } 50 | } 51 | 52 | // // TODO: override finalizer only if 'Dispose(bool disposing)' has code to free unmanaged resources 53 | // ~LogiDeviceIcon() 54 | // { 55 | // // Do not change this code. Put cleanup code in 'Dispose(bool disposing)' method 56 | // Dispose(disposing: false); 57 | // } 58 | 59 | public void Dispose() 60 | { 61 | // Do not change this code. Put cleanup code in 'Dispose(bool disposing)' method 62 | Dispose(disposing: true); 63 | GC.SuppressFinalize(this); 64 | } 65 | #endregion 66 | 67 | private static int _refCount = 0; 68 | public static int RefCount => _refCount; 69 | 70 | public static void AddRef() 71 | { 72 | _refCount++; 73 | RefCountChanged?.Invoke(RefCount); 74 | } 75 | 76 | public static void SubRef() 77 | { 78 | _refCount--; 79 | RefCountChanged?.Invoke(RefCount); 80 | } 81 | 82 | public static event Action? RefCountChanged; 83 | 84 | private Action _drawBatteryIcon; 85 | 86 | public LogiDeviceIcon(LogiDevice device, AppSettings appSettings, UserSettingsWrapper userSettings) 87 | { 88 | InitializeComponent(); 89 | 90 | if (!appSettings.UI.EnableRichToolTips) 91 | taskbarIcon.TrayToolTip = null; 92 | 93 | AddRef(); 94 | 95 | DataContext = device; 96 | 97 | device.PropertyChanged += LogiDevicePropertyChanged; 98 | userSettings.PropertyChanged += NotifyIconViewModelPropertyChanged; 99 | CheckTheme.StaticPropertyChanged += (_, _) => DrawBatteryIcon(); 100 | _drawBatteryIcon = userSettings.NumericDisplay ? BatteryIconDrawing.DrawNumeric : BatteryIconDrawing.DrawIcon; 101 | DrawBatteryIcon(); 102 | } 103 | 104 | private void NotifyIconViewModelPropertyChanged(object? s, PropertyChangedEventArgs e) 105 | { 106 | if (s is not UserSettingsWrapper userSettings) 107 | { 108 | return; 109 | } 110 | 111 | if (e.PropertyName == nameof(UserSettingsWrapper.NumericDisplay)) 112 | { 113 | _drawBatteryIcon = userSettings.NumericDisplay ? BatteryIconDrawing.DrawNumeric : BatteryIconDrawing.DrawIcon; 114 | DrawBatteryIcon(); 115 | } 116 | } 117 | 118 | private void LogiDevicePropertyChanged(object? s, PropertyChangedEventArgs e) 119 | { 120 | if (s is not LogiDevice) 121 | { 122 | return; 123 | } 124 | else if (e.PropertyName is nameof(LogiDevice.BatteryPercentage) or nameof(LogiDevice.PowerSupplyStatus)) 125 | { 126 | DrawBatteryIcon(); 127 | } 128 | } 129 | 130 | private void DrawBatteryIcon() 131 | { 132 | _ = Dispatcher.BeginInvoke(() => _drawBatteryIcon(taskbarIcon, (LogiDevice)DataContext)); 133 | } 134 | } 135 | } 136 | -------------------------------------------------------------------------------- /LGSTrayHID/HidppManagerContext.cs: -------------------------------------------------------------------------------- 1 | using static LGSTrayHID.HidApi.HidApi; 2 | using static LGSTrayHID.HidApi.HidApiWinApi; 3 | using static LGSTrayHID.HidApi.HidApiHotPlug; 4 | using LGSTrayHID.HidApi; 5 | using System.Collections.Concurrent; 6 | using LGSTrayPrimitives.MessageStructs; 7 | 8 | namespace LGSTrayHID 9 | { 10 | public sealed class HidppManagerContext 11 | { 12 | public static readonly HidppManagerContext _instance = new(); 13 | public static HidppManagerContext Instance => _instance; 14 | 15 | private readonly Dictionary _containerMap = []; 16 | private readonly Dictionary _deviceMap = []; 17 | private readonly BlockingCollection _deviceQueue = []; 18 | 19 | public delegate void HidppDeviceEventHandler(IPCMessageType messageType, IPCMessage message); 20 | 21 | public event HidppDeviceEventHandler? HidppDeviceEvent; 22 | 23 | private HidppManagerContext() 24 | { 25 | 26 | } 27 | 28 | static HidppManagerContext() 29 | { 30 | _ = HidInit(); 31 | } 32 | 33 | public void SignalDeviceEvent(IPCMessageType messageType, IPCMessage message) 34 | { 35 | HidppDeviceEvent?.Invoke(messageType, message); 36 | } 37 | 38 | private unsafe int EnqueueDevice(HidHotPlugCallbackHandle _, HidDeviceInfo* device, HidApiHotPlugEvent hidApiHotPlugEvent, nint __) 39 | { 40 | if (hidApiHotPlugEvent == HidApiHotPlugEvent.HID_API_HOTPLUG_EVENT_DEVICE_ARRIVED) 41 | { 42 | _deviceQueue.Add(*device); 43 | } 44 | 45 | return 0; 46 | } 47 | 48 | private async Task InitDevice(HidDeviceInfo deviceInfo) 49 | { 50 | var messageType = (deviceInfo).GetHidppMessageType(); 51 | switch (messageType) 52 | { 53 | case HidppMessageType.NONE: 54 | case HidppMessageType.VERY_LONG: 55 | return 0; 56 | } 57 | 58 | string devPath = (deviceInfo).GetPath(); 59 | 60 | HidDevicePtr dev = HidOpenPath(ref deviceInfo); 61 | _ = HidWinApiGetContainerId(dev, out Guid containerId); 62 | 63 | #if DEBUG 64 | Console.WriteLine(devPath); 65 | Console.WriteLine(containerId.ToString()); 66 | Console.WriteLine("x{0:X04}", (deviceInfo).Usage); 67 | Console.WriteLine("x{0:X04}", (deviceInfo).UsagePage); 68 | Console.WriteLine(); 69 | #endif 70 | 71 | if (!_deviceMap.TryGetValue(containerId, out HidppDevices? value)) 72 | { 73 | value = new(); 74 | _deviceMap[containerId] = value; 75 | _containerMap[devPath] = containerId; 76 | } 77 | 78 | switch (messageType) 79 | { 80 | case HidppMessageType.SHORT: 81 | await value.SetDevShort(dev); 82 | break; 83 | case HidppMessageType.LONG: 84 | await value.SetDevLong(dev); 85 | break; 86 | } 87 | 88 | return 0; 89 | } 90 | 91 | private unsafe int DeviceLeft(HidHotPlugCallbackHandle callbackHandle, HidDeviceInfo* deviceInfo, HidApiHotPlugEvent hidApiHotPlugEvent, nint userData) 92 | { 93 | string devPath = (*deviceInfo).GetPath(); 94 | 95 | if (_containerMap.TryGetValue(devPath, out var containerId)) 96 | { 97 | _deviceMap[containerId].Dispose(); 98 | _deviceMap.Remove(containerId); 99 | _containerMap.Remove(devPath); 100 | } 101 | 102 | return 0; 103 | } 104 | 105 | public void Start(CancellationToken cancellationToken) 106 | { 107 | new Thread(async () => 108 | { 109 | while (!cancellationToken.IsCancellationRequested) 110 | { 111 | var dev = _deviceQueue.Take(); 112 | if (cancellationToken.IsCancellationRequested) 113 | { 114 | break; 115 | } 116 | 117 | await InitDevice(dev); 118 | } 119 | }).Start(); 120 | 121 | unsafe 122 | { 123 | HidHotplugRegisterCallback(0x046D, 0x00, HidApiHotPlugEvent.HID_API_HOTPLUG_EVENT_DEVICE_ARRIVED, HidApiHotPlugFlag.HID_API_HOTPLUG_ENUMERATE, EnqueueDevice, IntPtr.Zero, (int*)IntPtr.Zero); 124 | HidHotplugRegisterCallback(0x046D, 0x00, HidApiHotPlugEvent.HID_API_HOTPLUG_EVENT_DEVICE_LEFT, HidApiHotPlugFlag.NONE, DeviceLeft, IntPtr.Zero, (int*)IntPtr.Zero); 125 | } 126 | } 127 | 128 | public async Task ForceBatteryUpdates() 129 | { 130 | foreach (var (_, hidppDevice) in _deviceMap) 131 | { 132 | var tasks = hidppDevice.DeviceCollection 133 | .Select(x => x.Value) 134 | .Select(x => x.UpdateBattery(true)); 135 | 136 | await Task.WhenAll(tasks); 137 | } 138 | } 139 | } 140 | } 141 | -------------------------------------------------------------------------------- /LGSTrayUI/NotifyIconViewModel.cs: -------------------------------------------------------------------------------- 1 | using CommunityToolkit.Mvvm.ComponentModel; 2 | using CommunityToolkit.Mvvm.Input; 3 | using LGSTrayCore; 4 | using LGSTrayCore.Managers; 5 | using Microsoft.Extensions.Hosting; 6 | using Microsoft.Win32; 7 | using System; 8 | using System.Collections.Generic; 9 | using System.Collections.ObjectModel; 10 | using System.IO; 11 | using System.Reflection; 12 | using System.Threading; 13 | using System.Threading.Tasks; 14 | using System.Windows; 15 | using System.Windows.Controls; 16 | 17 | namespace LGSTrayUI 18 | { 19 | public partial class NotifyIconViewModel : ObservableObject, IHostedService 20 | { 21 | private readonly MainTaskbarIconWrapper _mainTaskbarIconWrapper; 22 | 23 | [ObservableProperty] 24 | private ObservableCollection _logiDevices; 25 | 26 | private readonly UserSettingsWrapper _userSettings; 27 | public bool NumericDisplay 28 | { 29 | get 30 | { 31 | return _userSettings.NumericDisplay; 32 | } 33 | 34 | set 35 | { 36 | _userSettings.NumericDisplay = value; 37 | OnPropertyChanged(); 38 | } 39 | } 40 | 41 | public static string AssemblyVersion 42 | { 43 | get 44 | { 45 | return "v" + Assembly.GetEntryAssembly()?.GetCustomAttribute()?.InformationalVersion?.Split('+')[0] ?? "Missing"; 46 | } 47 | } 48 | 49 | private const string AutoStartRegKey = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Run"; 50 | private const string AutoStartRegKeyValue = "LGSTrayGUI"; 51 | private bool? _autoStart = null; 52 | public bool AutoStart 53 | { 54 | get 55 | { 56 | if (_autoStart == null) 57 | { 58 | RegistryKey? registryKey = Registry.CurrentUser.OpenSubKey(AutoStartRegKey, true); 59 | _autoStart = registryKey?.GetValue(AutoStartRegKeyValue) != null; 60 | } 61 | 62 | return _autoStart ?? false; 63 | } 64 | set 65 | { 66 | RegistryKey? registryKey = Registry.CurrentUser.OpenSubKey(AutoStartRegKey, true); 67 | 68 | if (registryKey == null) 69 | { 70 | return; 71 | } 72 | 73 | if (value) 74 | { 75 | registryKey.SetValue(AutoStartRegKeyValue, Path.Combine(AppContext.BaseDirectory, Environment.ProcessPath!)); 76 | } 77 | else 78 | { 79 | registryKey.DeleteValue(AutoStartRegKeyValue, false); 80 | } 81 | 82 | _autoStart = value; 83 | } 84 | } 85 | 86 | [ObservableProperty] 87 | private bool _rediscoverDevicesEnabled = true; 88 | 89 | private readonly IEnumerable _deviceManagers; 90 | 91 | public NotifyIconViewModel( 92 | MainTaskbarIconWrapper mainTaskbarIconWrapper, 93 | ILogiDeviceCollection logiDeviceCollection, 94 | UserSettingsWrapper userSettings, 95 | IEnumerable deviceManagers 96 | ) 97 | { 98 | _mainTaskbarIconWrapper = mainTaskbarIconWrapper; 99 | ((ContextMenu)Application.Current.FindResource("SysTrayMenu")).DataContext = this; 100 | 101 | _logiDevices = (logiDeviceCollection as LogiDeviceCollection)!.Devices; 102 | _userSettings = userSettings; 103 | _deviceManagers = deviceManagers; 104 | } 105 | 106 | [RelayCommand] 107 | private static void ExitApplication() 108 | { 109 | Environment.Exit(0); 110 | } 111 | 112 | [RelayCommand] 113 | private void DeviceClicked(object? sender) 114 | { 115 | if (sender is not MenuItem menuItem) 116 | { 117 | return; 118 | } 119 | 120 | LogiDevice logiDevice = (LogiDevice)menuItem.DataContext; 121 | 122 | if (menuItem.IsChecked) 123 | { 124 | _userSettings.AddDevice(logiDevice.DeviceId); 125 | } 126 | else 127 | { 128 | _userSettings.RemoveDevice(logiDevice.DeviceId); 129 | } 130 | } 131 | 132 | [RelayCommand] 133 | private async Task RediscoverDevices() 134 | { 135 | Console.WriteLine("Rediscover"); 136 | RediscoverDevicesEnabled = false; 137 | 138 | foreach (var manager in _deviceManagers) 139 | { 140 | manager.RediscoverDevices(); 141 | } 142 | 143 | await Task.Delay(10_000); 144 | 145 | RediscoverDevicesEnabled = true; 146 | } 147 | 148 | public Task StartAsync(CancellationToken cancellationToken) 149 | { 150 | return Task.CompletedTask; 151 | } 152 | 153 | public Task StopAsync(CancellationToken cancellationToken) 154 | { 155 | _mainTaskbarIconWrapper.Dispose(); 156 | return Task.CompletedTask; 157 | } 158 | } 159 | } 160 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | HIDPP_Bat_Mon/** 2 | 3 | # Native HID CPP daemon libs 4 | LGSTrayNative_cpp/** 5 | 6 | ## Ignore Visual Studio temporary files, build results, and 7 | ## files generated by popular Visual Studio add-ons. 8 | 9 | # User-specific files 10 | *.suo 11 | *.user 12 | *.userosscache 13 | *.sln.docstates 14 | 15 | # User-specific files (MonoDevelop/Xamarin Studio) 16 | *.userprefs 17 | 18 | # Build results 19 | [Dd]ebug/ 20 | [Dd]ebugPublic/ 21 | [Rr]elease/ 22 | [Rr]eleases/ 23 | x64/ 24 | x86/ 25 | bld/ 26 | [Bb]in/ 27 | [Oo]bj/ 28 | [Ll]og/ 29 | 30 | # Visual Studio 2015 cache/options directory 31 | .vs/ 32 | # Uncomment if you have tasks that create the project's static files in wwwroot 33 | #wwwroot/ 34 | 35 | # MSTest test Results 36 | [Tt]est[Rr]esult*/ 37 | [Bb]uild[Ll]og.* 38 | 39 | # NUNIT 40 | *.VisualState.xml 41 | TestResult.xml 42 | 43 | # Build Results of an ATL Project 44 | [Dd]ebugPS/ 45 | [Rr]eleasePS/ 46 | dlldata.c 47 | 48 | # DNX 49 | project.lock.json 50 | project.fragment.lock.json 51 | artifacts/ 52 | 53 | *_i.c 54 | *_p.c 55 | *_i.h 56 | *.ilk 57 | *.meta 58 | *.obj 59 | *.pch 60 | *.pdb 61 | *.pgc 62 | *.pgd 63 | *.rsp 64 | *.sbr 65 | *.tlb 66 | *.tli 67 | *.tlh 68 | *.tmp 69 | *.tmp_proj 70 | *.log 71 | *.vspscc 72 | *.vssscc 73 | .builds 74 | *.pidb 75 | *.svclog 76 | *.scc 77 | 78 | # Chutzpah Test files 79 | _Chutzpah* 80 | 81 | # Visual C++ cache files 82 | ipch/ 83 | *.aps 84 | *.ncb 85 | *.opendb 86 | *.opensdf 87 | *.sdf 88 | *.cachefile 89 | *.VC.db 90 | *.VC.VC.opendb 91 | 92 | # Visual Studio profiler 93 | *.psess 94 | *.vsp 95 | *.vspx 96 | *.sap 97 | 98 | # TFS 2012 Local Workspace 99 | $tf/ 100 | 101 | # Guidance Automation Toolkit 102 | *.gpState 103 | 104 | # ReSharper is a .NET coding add-in 105 | _ReSharper*/ 106 | *.[Rr]e[Ss]harper 107 | *.DotSettings.user 108 | 109 | # JustCode is a .NET coding add-in 110 | .JustCode 111 | 112 | # TeamCity is a build add-in 113 | _TeamCity* 114 | 115 | # DotCover is a Code Coverage Tool 116 | *.dotCover 117 | 118 | # NCrunch 119 | _NCrunch_* 120 | .*crunch*.local.xml 121 | nCrunchTemp_* 122 | 123 | # MightyMoose 124 | *.mm.* 125 | AutoTest.Net/ 126 | 127 | # Web workbench (sass) 128 | .sass-cache/ 129 | 130 | # Installshield output folder 131 | [Ee]xpress/ 132 | 133 | # DocProject is a documentation generator add-in 134 | DocProject/buildhelp/ 135 | DocProject/Help/*.HxT 136 | DocProject/Help/*.HxC 137 | DocProject/Help/*.hhc 138 | DocProject/Help/*.hhk 139 | DocProject/Help/*.hhp 140 | DocProject/Help/Html2 141 | DocProject/Help/html 142 | 143 | # Click-Once directory 144 | publish/ 145 | 146 | # Publish Web Output 147 | *.[Pp]ublish.xml 148 | *.azurePubxml 149 | # TODO: Comment the next line if you want to checkin your web deploy settings 150 | # but database connection strings (with potential passwords) will be unencrypted 151 | #*.pubxml 152 | *.publishproj 153 | 154 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 155 | # checkin your Azure Web App publish settings, but sensitive information contained 156 | # in these scripts will be unencrypted 157 | PublishScripts/ 158 | 159 | # NuGet Packages 160 | *.nupkg 161 | # The packages folder can be ignored because of Package Restore 162 | **/packages/* 163 | # except build/, which is used as an MSBuild target. 164 | !**/packages/build/ 165 | # Uncomment if necessary however generally it will be regenerated when needed 166 | #!**/packages/repositories.config 167 | # NuGet v3's project.json files produces more ignoreable files 168 | *.nuget.props 169 | *.nuget.targets 170 | 171 | # Microsoft Azure Build Output 172 | csx/ 173 | *.build.csdef 174 | 175 | # Microsoft Azure Emulator 176 | ecf/ 177 | rcf/ 178 | 179 | # Windows Store app package directories and files 180 | AppPackages/ 181 | BundleArtifacts/ 182 | Package.StoreAssociation.xml 183 | _pkginfo.txt 184 | 185 | # Visual Studio cache files 186 | # files ending in .cache can be ignored 187 | *.[Cc]ache 188 | # but keep track of directories ending in .cache 189 | !*.[Cc]ache/ 190 | 191 | # Others 192 | ClientBin/ 193 | ~$* 194 | *~ 195 | *.dbmdl 196 | *.dbproj.schemaview 197 | *.jfm 198 | *.pfx 199 | *.publishsettings 200 | node_modules/ 201 | orleans.codegen.cs 202 | 203 | # Since there are multiple workflows, uncomment next line to ignore bower_components 204 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 205 | #bower_components/ 206 | 207 | # RIA/Silverlight projects 208 | Generated_Code/ 209 | 210 | # Backup & report files from converting an old project file 211 | # to a newer Visual Studio version. Backup files are not needed, 212 | # because we have git ;-) 213 | _UpgradeReport_Files/ 214 | Backup*/ 215 | UpgradeLog*.XML 216 | UpgradeLog*.htm 217 | 218 | # SQL Server files 219 | *.mdf 220 | *.ldf 221 | 222 | # Business Intelligence projects 223 | *.rdl.data 224 | *.bim.layout 225 | *.bim_*.settings 226 | 227 | # Microsoft Fakes 228 | FakesAssemblies/ 229 | 230 | # GhostDoc plugin setting file 231 | *.GhostDoc.xml 232 | 233 | # Node.js Tools for Visual Studio 234 | .ntvs_analysis.dat 235 | 236 | # Visual Studio 6 build log 237 | *.plg 238 | 239 | # Visual Studio 6 workspace options file 240 | *.opt 241 | 242 | # Visual Studio LightSwitch build output 243 | **/*.HTMLClient/GeneratedArtifacts 244 | **/*.DesktopClient/GeneratedArtifacts 245 | **/*.DesktopClient/ModelManifest.xml 246 | **/*.Server/GeneratedArtifacts 247 | **/*.Server/ModelManifest.xml 248 | _Pvt_Extensions 249 | 250 | # Paket dependency manager 251 | .paket/paket.exe 252 | paket-files/ 253 | 254 | # FAKE - F# Make 255 | .fake/ 256 | 257 | # JetBrains Rider 258 | .idea/ 259 | *.sln.iml 260 | 261 | # CodeRush 262 | .cr/ 263 | 264 | # Python Tools for Visual Studio (PTVS) 265 | __pycache__/ 266 | *.pyc -------------------------------------------------------------------------------- /LGSTrayCore/Managers/LGSTrayHIDManager.cs: -------------------------------------------------------------------------------- 1 | using LGSTrayPrimitives.MessageStructs; 2 | using MessagePack.Resolvers; 3 | using MessagePipe; 4 | using Microsoft.Extensions.Hosting; 5 | using Microsoft.Extensions.Options; 6 | using System.Diagnostics; 7 | 8 | namespace LGSTrayCore.Managers 9 | { 10 | public class LGSTrayHIDManager : IDeviceManager, IHostedService, IDisposable 11 | { 12 | #region IDisposable 13 | private Func? _diposeSubs; 14 | private bool disposedValue; 15 | 16 | protected virtual void Dispose(bool disposing) 17 | { 18 | if (!disposedValue) 19 | { 20 | if (disposing) 21 | { 22 | _ = _diposeSubs?.Invoke(); 23 | _diposeSubs = null; 24 | } 25 | 26 | // TODO: free unmanaged resources (unmanaged objects) and override finalizer 27 | disposedValue = true; 28 | } 29 | } 30 | 31 | // // TODO: override finalizer only if 'Dispose(bool disposing)' has code to free unmanaged resources 32 | // ~LGSTrayHIDDaemon() 33 | // { 34 | // // Do not change this code. Put cleanup code in 'Dispose(bool disposing)' method 35 | // Dispose(disposing: false); 36 | // } 37 | 38 | public void Dispose() 39 | { 40 | // Do not change this code. Put cleanup code in 'Dispose(bool disposing)' method 41 | Dispose(disposing: true); 42 | GC.SuppressFinalize(this); 43 | } 44 | #endregion 45 | 46 | private readonly CancellationTokenSource _cts = new(); 47 | private CancellationTokenSource? _daemonCts; 48 | 49 | private readonly IDistributedSubscriber _subscriber; 50 | private readonly IPublisher _deviceEventBus; 51 | 52 | public LGSTrayHIDManager( 53 | IDistributedSubscriber subscriber, 54 | IPublisher deviceEventBus 55 | ) 56 | { 57 | _subscriber = subscriber; 58 | _deviceEventBus = deviceEventBus; 59 | } 60 | 61 | private async Task DaemonLoop() 62 | { 63 | _daemonCts = new(); 64 | 65 | using Process proc = new(); 66 | proc.StartInfo = new() 67 | { 68 | RedirectStandardError = false, 69 | RedirectStandardInput = false, 70 | RedirectStandardOutput = false, 71 | FileName = Path.Combine(AppContext.BaseDirectory, "LGSTrayHID.exe"), 72 | Arguments = Environment.ProcessId.ToString(), 73 | UseShellExecute = true, 74 | CreateNoWindow = true 75 | }; 76 | proc.Start(); 77 | 78 | try 79 | { 80 | using var cts = CancellationTokenSource.CreateLinkedTokenSource(_cts.Token, _daemonCts.Token); 81 | await proc.WaitForExitAsync(cts.Token); 82 | } 83 | catch (Exception) 84 | { 85 | if (!proc.HasExited) 86 | { 87 | proc.Kill(); 88 | } 89 | } 90 | finally 91 | { 92 | _daemonCts.Dispose(); 93 | _daemonCts = null; 94 | } 95 | 96 | await Task.Delay(1000); 97 | return proc.ExitCode; 98 | } 99 | 100 | public async Task StartAsync(CancellationToken cancellationToken) 101 | { 102 | var sub1 = await _subscriber.SubscribeAsync( 103 | IPCMessageType.INIT, 104 | x => 105 | { 106 | var initMessage = (InitMessage)x; 107 | //_logiDeviceCollection.OnInitMessage(initMessage); 108 | _deviceEventBus.Publish(initMessage); 109 | }, 110 | cancellationToken 111 | ); 112 | 113 | var sub2 = await _subscriber.SubscribeAsync( 114 | IPCMessageType.UPDATE, 115 | x => 116 | { 117 | var updateMessage = (UpdateMessage)x; 118 | //_logiDeviceCollection.OnUpdateMessage(updateMessage); 119 | _deviceEventBus.Publish(updateMessage); 120 | }, 121 | cancellationToken 122 | ); 123 | 124 | _diposeSubs = async () => 125 | { 126 | await sub1.DisposeAsync(); 127 | await sub2.DisposeAsync(); 128 | }; 129 | 130 | _ = Task.Run(async () => 131 | { 132 | int fastFailCount = 0; 133 | 134 | while (!_cts.Token.IsCancellationRequested) 135 | { 136 | DateTime then = DateTime.Now; 137 | int ret = await DaemonLoop(); 138 | 139 | // Daemon returns -1 on .Kill(), assume its user 140 | if ((ret != -1) || (DateTime.Now - then).TotalSeconds < 20) 141 | { 142 | fastFailCount++; 143 | } 144 | else 145 | { 146 | fastFailCount = 0; 147 | } 148 | 149 | if (fastFailCount > 3) 150 | { 151 | // Notify user? 152 | break; 153 | } 154 | } 155 | }, CancellationToken.None); 156 | 157 | return; 158 | } 159 | 160 | public Task StopAsync(CancellationToken cancellationToken) 161 | { 162 | _cts.Cancel(); 163 | 164 | return Task.CompletedTask; 165 | } 166 | 167 | public void RediscoverDevices() 168 | { 169 | _daemonCts?.Cancel(); 170 | } 171 | } 172 | } 173 | -------------------------------------------------------------------------------- /LGSTrayUI/BatteryIconDrawing.cs: -------------------------------------------------------------------------------- 1 | using LGSTrayCore; 2 | using LGSTrayUI.Properties; 3 | using System; 4 | using System.Drawing; 5 | using System.Drawing.Drawing2D; 6 | using System.Drawing.Imaging; 7 | using Hardcodet.Wpf.TaskbarNotification; 8 | using System.Runtime.InteropServices; 9 | using LGSTrayPrimitives; 10 | using Microsoft.Win32; 11 | 12 | namespace LGSTrayUI 13 | { 14 | public static partial class BatteryIconDrawing 15 | { 16 | [LibraryImport("user32.dll")] 17 | [return: MarshalAs(UnmanagedType.Bool)] 18 | private static partial bool DestroyIcon(IntPtr handle); 19 | 20 | private static Bitmap Mouse => CheckTheme.LightTheme ? Resources.Mouse : Resources.Mouse_dark; 21 | private static Bitmap Keyboard => CheckTheme.LightTheme ? Resources.Keyboard : Resources.Keyboard_dark; 22 | private static Bitmap Headset => CheckTheme.LightTheme ? Resources.Headset : Resources.Headset_dark; 23 | private static Bitmap Battery => CheckTheme.LightTheme ? Resources.Battery : Resources.Battery_dark; 24 | private static Bitmap Missing => CheckTheme.LightTheme ? Resources.Missing : Resources.Missing_dark; 25 | private static Bitmap Charging => CheckTheme.LightTheme ? Resources.Charging : Resources.Charging_dark; 26 | 27 | private static int ImageSize; 28 | 29 | static BatteryIconDrawing() 30 | { 31 | int dpi; 32 | 33 | try 34 | { 35 | var reg = Registry.CurrentUser.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\ThemeManager", false); 36 | var _dpi = (string?)reg?.GetValue("LastLoadedDPI"); 37 | if (!int.TryParse(_dpi, out dpi)) 38 | { 39 | dpi = 96; 40 | } 41 | } 42 | catch { dpi = 96; } 43 | var scale = dpi / 96f; 44 | 45 | ImageSize = (int)(32 * scale); 46 | } 47 | 48 | private static Bitmap GetDeviceIcon(LogiDevice device) => device.DeviceType switch 49 | { 50 | DeviceType.Keyboard => Keyboard, 51 | DeviceType.Headset => Headset, 52 | _ => Mouse, 53 | }; 54 | 55 | private static Color GetDeviceColor(LogiDevice device) => device.DeviceType switch 56 | { 57 | _ => CheckTheme.LightTheme ? Color.FromArgb(0x11, 0x11, 0x11) : Color.FromArgb(0xEE, 0xEE, 0xEE) 58 | 59 | //return device.DeviceType switch 60 | //{ 61 | // DeviceType.Keyboard => Color.FromArgb(0xA1, 0xE4, 0x4D), 62 | // DeviceType.Headset => Color.FromArgb(0xFA, 0x79, 0x21), 63 | // _ => Color.FromArgb(0xBB, 0x86, 0xFC), 64 | //}; 65 | }; 66 | 67 | private static Bitmap GetBatteryValue(LogiDevice device) => device.BatteryPercentage switch 68 | { 69 | { } when device.PowerSupplyStatus == PowerSupplyStatus.POWER_SUPPLY_STATUS_CHARGING => Charging, 70 | < 0 => Missing, 71 | < 10 => Resources.Indicator_10, 72 | < 50 => Resources.Indicator_30, 73 | < 85 => Resources.Indicator_50, 74 | _ => Resources.Indicator_100 75 | }; 76 | 77 | public static void DrawUnknown(TaskbarIcon taskbarIcon) 78 | { 79 | DrawIcon(taskbarIcon, new() 80 | { 81 | BatteryPercentage = -1, 82 | }); 83 | } 84 | 85 | public static void DrawIcon(TaskbarIcon taskbarIcon, LogiDevice device) 86 | { 87 | var destRect = new Rectangle(0, 0, ImageSize, ImageSize); 88 | using var b = new Bitmap(ImageSize, ImageSize); 89 | using var g = Graphics.FromImage(b); 90 | g.CompositingMode = CompositingMode.SourceOver; 91 | g.CompositingQuality = CompositingQuality.HighQuality; 92 | g.InterpolationMode = InterpolationMode.HighQualityBicubic; 93 | g.SmoothingMode = SmoothingMode.HighQuality; 94 | g.PixelOffsetMode = PixelOffsetMode.HighQuality; 95 | 96 | using var wrapMode = new ImageAttributes(); 97 | wrapMode.SetWrapMode(WrapMode.TileFlipXY); 98 | 99 | Bitmap[] layers = [ 100 | GetBatteryValue(device), 101 | Battery, 102 | GetDeviceIcon(device), 103 | ]; 104 | 105 | foreach (var image in layers) 106 | { 107 | g.DrawImage(image, destRect, 0, 0, image.Width, image.Height, GraphicsUnit.Pixel, wrapMode); 108 | image.Dispose(); 109 | } 110 | 111 | g.Save(); 112 | 113 | IntPtr iconHandle = b.GetHicon(); 114 | Icon tempManagedRes = Icon.FromHandle(iconHandle); 115 | taskbarIcon.Icon = (Icon)tempManagedRes.Clone(); 116 | tempManagedRes.Dispose(); 117 | DestroyIcon(iconHandle); 118 | } 119 | 120 | public static void DrawNumeric(TaskbarIcon taskbarIcon, LogiDevice device) 121 | { 122 | using Bitmap b = new(ImageSize, ImageSize); 123 | using Graphics g = Graphics.FromImage(b); 124 | 125 | string displayString = (device.BatteryPercentage < 0) ? "?" : $"{device.BatteryPercentage:f0}"; 126 | g.DrawString( 127 | displayString, 128 | new Font("Segoe UI", (int)(0.8 * ImageSize), GraphicsUnit.Pixel), 129 | new SolidBrush(GetDeviceColor(device)), 130 | ImageSize / 2, ImageSize / 2, 131 | new(StringFormatFlags.FitBlackBox, 0) 132 | { 133 | LineAlignment = StringAlignment.Center, 134 | Alignment = StringAlignment.Center, 135 | } 136 | ); 137 | g.CompositingMode = CompositingMode.SourceOver; 138 | g.CompositingQuality = CompositingQuality.HighQuality; 139 | g.InterpolationMode = InterpolationMode.HighQualityBicubic; 140 | g.SmoothingMode = SmoothingMode.HighQuality; 141 | g.PixelOffsetMode = PixelOffsetMode.HighQuality; 142 | 143 | IntPtr iconHandle = b.GetHicon(); 144 | Icon tempManagedRes = Icon.FromHandle(iconHandle); 145 | taskbarIcon.Icon = (Icon)tempManagedRes.Clone(); 146 | tempManagedRes.Dispose(); 147 | DestroyIcon(iconHandle); 148 | } 149 | } 150 | } 151 | -------------------------------------------------------------------------------- /readme.md: -------------------------------------------------------------------------------- 1 | # LGS Tray Battery 2 | 3 | A rewrite/combination of my two programs [LGSTrayBattery](https://github.com/andyvorld/LGSTrayBattery) and [LGSTrayBattery_GHUB](https://github.com/andyvorld/LGSTrayBattery_GHUB), which should allow for interaction via both the native HID and Logitech GaminG Hub websockets. 4 | 5 | ## How to install 6 | 7 | [![GitHub Release](https://img.shields.io/github/v/release/andyvorld/LGSTrayBattery?sort=semver)](https://github.com/andyvorld/LGSTrayBattery/releases/latest) 8 | 9 | 10 | Please, visit [the latest release page](https://github.com/andyvorld/LGSTrayBattery/releases/latest) and download the release zip files from assets. Builds with the `-standalone` suffix are pre-bundled with .Net 8 and does not require any further dependencies, the non-standalone version requires .Net 8 to be pre-installed (https://dotnet.microsoft.com/en-us/download/dotnet/8.0). 11 | 12 | ## Changes from V2 13 | *When migrating from earlier versions, device ids may have changed.* 14 | - Moved to .Net 8 15 | - Realtime reactive icons and rich tooltips 16 | - Light/Dark theme is now reactive in realtime 17 | - Rewritten to use hidapi directly for hotplug support 18 | - Wired/Wireless devices like the G403 should behave like a single device 19 | - Multi-device mode 20 | - Numerical Icons 21 | - HID.NET manager has been deprecated 22 | - Migrated to using a `.toml` for appsettings 23 | 24 | ## Features 25 | ### Tray Indicator 26 | ![image](https://user-images.githubusercontent.com/24492062/138280300-6966b6a4-ff6d-46e6-9698-d2c8d612eb11.png) 27 | 28 | Battery percentage and voltage (if supported) in a tray tooltip with notification icon. 29 | 30 | Right-click for more options. 31 | 32 | ### Multiple Icons 33 | ![image](Assets/multi_icon.png) 34 | 35 | Depending on the number of devices selected in the context menu, multiple devices can be seen simultatniously 36 | 37 | ### Numerical Icons 38 | ![image](Assets/numerical_icon.png) 39 | 40 | Display the current battery percentage as a number. 41 | 42 | *In numerical display mode, charging status will not be displayed* 43 | 44 | ### Reactive Icons 45 | ![image](https://user-images.githubusercontent.com/24492062/138284660-95949372-c59a-4569-9545-0cfe0506d1fb.png) 46 | 47 | *Icon changes to match devices type (Current supported: mouse, keyboard and headsets)* 48 | 49 | ![image](https://user-images.githubusercontent.com/24492062/138285048-ad229703-5c4e-430e-b107-c50eb341e46b.png) 50 | 51 | *Icon changes to match light/dark system theme* 52 | 53 | ![image](Assets/charging_icon.png) 54 | 55 | *Icon changes to reflect current charging status* 56 | 57 | ### Http/Web "server" api 58 | By default the running of the http server is enabled. The IP address and port used for bindings are under `addr` and `port` respectively with the defaults being `localhost` and `12321`. 59 | 60 | `addr` accepts either a hostname (`DESKTOP-1234`) or an IP address (`127.0.0.1`) to bind to, if you are not sure use `localhost` or if you have admin permission `0.0.0.0` to bind to all interfaces. 61 | 62 | IPv6 can also be disabled with `useIpv6` in the event that dual stack networking is causing issues. 63 | 64 | If any issues arise from running the server, it can be turned off by the `enable` value in `appsettings.toml` under `[HTTPServer]`. 65 | 66 | ![image](Assets/server_index.png) 67 | 68 | Visit `http://{addr}:{port}/` on your browser to view the list of devices available. 69 | 70 | ![image](https://user-images.githubusercontent.com/24492062/138281030-f40ba805-69bf-48ac-a126-6f58f9ca7828.png) 71 | 72 | With the `deviceID`, a HTTP/GET request to `{addr}:{port}/device/{deviceID}`, will result in an xml document of the name and battery status of the device. Devices that do not support `battery_voltage` will report 0.00. 73 | 74 | Device ids starting with `dev` originates from tapping into Logitech GHUB's own drivers, while random numbers are from the natively implement HID++ code. Thus, there are some fields that different between the two, 75 | 76 | | | GHUB* | Native | 77 | |-----------------|-------|---------| 78 | | device_id | ✔️ | ✔️ | 79 | | device_name | ✔️ | ✔️ | 80 | | device_type | ✔️ | ✔️ | 81 | | battery_percent | ✔️ | ✔️ | 82 | | battery_voltage | ❌ | ✔️** | 83 | | mileage*** | ✔️ | ❌ | 84 | | charging | ✔️ | ✔️ | 85 | 86 | \* - Requires Logitech G Hub Installed 87 | 88 | \** - Depends on the device 89 | 90 | \*** - Logitech G Hub's metric of estimated life left on the battery 91 | 92 | ## HID++ Device Sources 93 | As of v3.0.0, there are 2 sources in which the program will pull battery status, 94 | 95 | - Logitech G Hub via Websockets 96 | - Native HID, hidapi via PInvoke (Called "Native" in settings) 97 | 98 | These sources can be individually disabled/enabled before runtime via `appsettings.toml`, in the their respective sections, 99 | 100 | ``` 101 | [GHub] 102 | enabled = true 103 | 104 | [Native] 105 | enabled = true 106 | ``` 107 | 108 | *GHub is Logitech G Hub, Native is hidapi* 109 | 110 | ## appsettings.toml 111 | Refer to https://toml.io/en/ for a guide on toml syntax. 112 | 113 | *Note the `"` around strings* 114 | 115 | In the event of an invalid settings, at launch the app will prompt you for a reset to the default settings. 116 | 117 | 118 | ### `[Native]` settings 119 | - `retryTime` - The time in seconds to re-try a device on a failed device state query; usually the device is asleep. 120 | - `pollPeriod` - The time in seconds to request an update from the device, keep this as high as possible as it may interfere with the default power saving sleep modes of devices. 121 | - `disabledDevices` - If all else fails, and the addition of a new device has caused the app to be unusable. Adding a part of the device name into this list will prevent the device from being polled. E.g. The following will disable the G403 and G502, 122 | ``` 123 | disabledDevices = [ 124 | "G403", 125 | "G502" 126 | ] 127 | ``` 128 | 129 | ## Known Issues 130 | ### Common 131 | - Native HID and GHUB do not provide similar percentages, this is due to how native and GHUB calculates percentages from the device's voltages. Native uses an average curve of a 3.7V lipo battery, while GHUB will use a lookup table specific to the device. 132 | 133 | ### Native HID (hidapi) 134 | - Certain wired devices like the G403 when in wired mode does not report the number of HID devices connected and will respond to all request. Causing battery polls to occur 6x per request. 135 | - Device and protocol discovery changed from the previous method, some devices like the G533 headsets might not be detected, try the GHUB based manager. 136 | 137 | ### GHUB 138 | - Future GHUB version may change IPC protocol/endpoints (currently websocket) 139 | 140 | ## Working with 141 | - G403 Wireless 142 | - MX Anywhere 2 143 | 144 | ### Community Tested 145 | *HID Backend has changed, would need restesting of devices, please raise a PR to add to this list* 146 | 147 | 148 | ## How to Build project 149 | TBA 150 | 151 | ## Acknowledgements 152 | This project began as a task with me messing around with my mouse for battery tracking. 153 | 154 | - [Solaar](https://github.com/pwr-Solaar/Solaar), for the source code to base the HID++ paramters and reverse engineering of the protocol. 155 | - [XB1ControllerBatteryIndicator](https://github.com/NiyaShy/XB1ControllerBatteryIndicator), for the idea and base of the icons 156 | - [The Noun Project](https://thenounproject.com/), for base icons 157 | - Mouse, By projecthayat, ID, In the Technology & computer hardware Collection 158 | - Keyboard, By HideMaru, ID, In the Electronic BL.2 Collection 159 | - Headphones, By Peter Lakenbrink, DE, In the School and Online Learning Glyph Collection 160 | -------------------------------------------------------------------------------- /LGSTrayCore/Managers/GHubManager.cs: -------------------------------------------------------------------------------- 1 | using LGSTrayPrimitives; 2 | using LGSTrayPrimitives.MessageStructs; 3 | using MessagePipe; 4 | using Microsoft.Extensions.Hosting; 5 | using Newtonsoft.Json; 6 | using Newtonsoft.Json.Linq; 7 | using Swan; 8 | using System.Diagnostics; 9 | using System.Net.WebSockets; 10 | using System.Text.RegularExpressions; 11 | using Websocket.Client; 12 | 13 | namespace LGSTrayCore.Managers 14 | { 15 | file struct GHUBMsg 16 | { 17 | public string MsgId { get; set; } 18 | public string Verb { get; set; } 19 | public string Path { get; set; } 20 | public string Origin { get; set; } 21 | public JObject Result { get; set; } 22 | public JObject Payload { get; set; } 23 | 24 | public static GHUBMsg DeserializeJson(string json) 25 | { 26 | return JsonConvert.DeserializeObject(json); 27 | } 28 | } 29 | 30 | public partial class GHubManager : IDeviceManager, IHostedService, IDisposable 31 | { 32 | #region IDisposable 33 | private bool disposedValue; 34 | 35 | protected virtual void Dispose(bool disposing) 36 | { 37 | if (!disposedValue) 38 | { 39 | if (disposing) 40 | { 41 | _ws?.Dispose(); 42 | _ws = null; 43 | } 44 | 45 | // TODO: free unmanaged resources (unmanaged objects) and override finalizer 46 | // TODO: set large fields to null 47 | disposedValue = true; 48 | } 49 | } 50 | 51 | // // TODO: override finalizer only if 'Dispose(bool disposing)' has code to free unmanaged resources 52 | // ~GHubManager() 53 | // { 54 | // // Do not change this code. Put cleanup code in 'Dispose(bool disposing)' method 55 | // Dispose(disposing: false); 56 | // } 57 | 58 | public void Dispose() 59 | { 60 | // Do not change this code. Put cleanup code in 'Dispose(bool disposing)' method 61 | Dispose(disposing: true); 62 | GC.SuppressFinalize(this); 63 | } 64 | #endregion 65 | 66 | private const string WEBSOCKET_SERVER = "ws://localhost:9010"; 67 | 68 | [GeneratedRegex(@"\/battery\/dev[0-9a-zA-Z]+\/state")] 69 | private static partial Regex BatteryDeviceStateRegex(); 70 | 71 | private readonly IPublisher _deviceEventBus; 72 | 73 | protected WebsocketClient? _ws; 74 | 75 | public GHubManager(IPublisher deviceEventBus) 76 | { 77 | _deviceEventBus = deviceEventBus; 78 | } 79 | 80 | public async Task StartAsync(CancellationToken cancellationToken) 81 | { 82 | var url = new Uri(WEBSOCKET_SERVER); 83 | 84 | var factory = new Func(() => 85 | { 86 | var client = new ClientWebSocket(); 87 | client.Options.UseDefaultCredentials = false; 88 | client.Options.SetRequestHeader("Origin", "file://"); 89 | client.Options.SetRequestHeader("Pragma", "no-cache"); 90 | client.Options.SetRequestHeader("Cache-Control", "no-cache"); 91 | client.Options.SetRequestHeader("Sec-WebSocket-Extensions", "permessage-deflate; client_max_window_bits"); 92 | client.Options.SetRequestHeader("Sec-WebSocket-Protocol", "json"); 93 | client.Options.AddSubProtocol("json"); 94 | return client; 95 | }); 96 | 97 | _ws = new WebsocketClient(url, factory); 98 | _ws.MessageReceived.Subscribe(ParseSocketMsg); 99 | _ws.ErrorReconnectTimeout = TimeSpan.FromMilliseconds(500); 100 | _ws.ReconnectTimeout = null; 101 | 102 | Debug.WriteLine($"Trying to connect to LGHUB_agent, at {url}"); 103 | 104 | try 105 | { 106 | await _ws.Start(); 107 | } 108 | catch (Websocket.Client.Exceptions.WebsocketException) 109 | { 110 | Debug.WriteLine("Failed to connect to LGHUB_agent"); 111 | this.Dispose(); 112 | return; 113 | } 114 | 115 | Debug.WriteLine($"Connected to LGHUB_agent"); 116 | 117 | _ws.Send(JsonConvert.SerializeObject(new 118 | { 119 | msgId = "", 120 | verb = "SUBSCRIBE", 121 | path = "/devices/state/changed" 122 | })); 123 | 124 | _ws.Send(JsonConvert.SerializeObject(new 125 | { 126 | msgId = "", 127 | verb = "SUBSCRIBE", 128 | path = "/battery/state/changed" 129 | })); 130 | 131 | LoadDevices(); 132 | } 133 | 134 | public Task StopAsync(CancellationToken cancellationToken) 135 | { 136 | _ws?.Dispose(); 137 | 138 | return Task.CompletedTask; 139 | } 140 | 141 | public void LoadDevices() 142 | { 143 | _ws?.Send(JsonConvert.SerializeObject(new 144 | { 145 | msgId = "", 146 | verb = "GET", 147 | path = "/devices/list" 148 | })); 149 | } 150 | 151 | protected void ParseSocketMsg(ResponseMessage msg) 152 | { 153 | GHUBMsg ghubmsg = GHUBMsg.DeserializeJson(msg.Text!); 154 | 155 | switch (ghubmsg.Path) 156 | { 157 | case "/devices/list": 158 | { 159 | LoadDevices(ghubmsg.Payload); 160 | break; 161 | } 162 | case "/battery/state/changed": 163 | case { } when BatteryDeviceStateRegex().Match(ghubmsg.Path).Success: 164 | { 165 | Console.WriteLine(ghubmsg.Path); 166 | ParseBatteryUpdate(ghubmsg.Payload); 167 | break; 168 | } 169 | default: break; 170 | } 171 | } 172 | 173 | protected void LoadDevices(JObject payload) 174 | { 175 | try 176 | { 177 | foreach (var deviceToken in payload["deviceInfos"]!) 178 | { 179 | if (!Enum.TryParse(deviceToken["deviceType"]!.ToString(), true, out DeviceType deviceType)) 180 | { 181 | deviceType = DeviceType.Mouse; 182 | } 183 | 184 | string deviceId = deviceToken["id"]!.ToString(); 185 | _deviceEventBus.Publish(new InitMessage( 186 | deviceId, 187 | deviceToken["extendedDisplayName"]!.ToString(), 188 | (bool) deviceToken["capabilities"]!["hasBatteryStatus"]!, 189 | deviceType 190 | )); 191 | 192 | _ws?.Send(JsonConvert.SerializeObject(new 193 | { 194 | msgId = "", 195 | verb = "GET", 196 | path = $"/battery/{deviceId}/state" 197 | })); 198 | } 199 | } 200 | catch (Exception e) 201 | { 202 | if (e is NullReferenceException || e is JsonReaderException) 203 | { 204 | Debug.WriteLine("Failed to parse device list, LGHUB_agent is probably starting up"); 205 | } 206 | } 207 | } 208 | 209 | protected void ParseBatteryUpdate(JObject payload) 210 | { 211 | try 212 | { 213 | _deviceEventBus.Publish(new UpdateMessage( 214 | payload["deviceId"]!.ToString(), 215 | payload["percentage"]!.ToObject(), 216 | payload["charging"]!.ToBoolean() ? PowerSupplyStatus.POWER_SUPPLY_STATUS_CHARGING : PowerSupplyStatus.POWER_SUPPLY_STATUS_NOT_CHARGING, 217 | 0, 218 | DateTime.Now, 219 | payload["mileage"]!.ToObject() 220 | )); 221 | } 222 | catch { } 223 | } 224 | 225 | public async void RediscoverDevices() 226 | { 227 | using var cts = new CancellationTokenSource(); 228 | await StopAsync(cts.Token); 229 | await StartAsync(cts.Token); 230 | } 231 | } 232 | } 233 | -------------------------------------------------------------------------------- /LGSTrayHID/HidppDevice.cs: -------------------------------------------------------------------------------- 1 | using LGSTrayPrimitives; 2 | using LGSTrayPrimitives.MessageStructs; 3 | using LGSTrayHID.Features; 4 | using System.Text; 5 | 6 | using static LGSTrayHID.HidppDevices; 7 | 8 | #if DEBUG 9 | using Log = System.Console; 10 | #else 11 | using Log = System.Diagnostics.Debug; 12 | #endif 13 | 14 | namespace LGSTrayHID 15 | { 16 | public class HidppDevice 17 | { 18 | private readonly SemaphoreSlim _initSemaphore = new(1, 1); 19 | private Func>? _getBatteryAsync; 20 | 21 | public string DeviceName { get; private set; } = string.Empty; 22 | public int DeviceType { get; private set; } = 3; 23 | public string Identifier { get; private set; } = string.Empty; 24 | 25 | private BatteryUpdateReturn lastBatteryReturn; 26 | private DateTimeOffset lastUpdate = DateTimeOffset.MinValue; 27 | 28 | private readonly HidppDevices _parent; 29 | public HidppDevices Parent => _parent; 30 | 31 | private readonly byte _deviceIdx; 32 | public byte DeviceIdx => _deviceIdx; 33 | 34 | private readonly Dictionary _featureMap = []; 35 | public Dictionary FeatureMap => _featureMap; 36 | 37 | public HidppDevice(HidppDevices parent, byte deviceIdx) 38 | { 39 | _parent = parent; 40 | _deviceIdx = deviceIdx; 41 | } 42 | 43 | public async Task InitAsync() 44 | { 45 | await _initSemaphore.WaitAsync(); 46 | try 47 | { 48 | Hidpp20 ret; 49 | 50 | // Sync Ping 51 | int successCount = 0; 52 | int successThresh = 3; 53 | for (int i = 0; i < 10; i++) 54 | { 55 | var ping = await _parent.Ping20(_deviceIdx, 100); 56 | if (ping) 57 | { 58 | successCount++; 59 | } 60 | else 61 | { 62 | successCount = 0; 63 | } 64 | 65 | if (successCount >= successThresh) { break; } 66 | } 67 | 68 | if (successCount < successThresh) { return; } 69 | 70 | // Find 0x0001 IFeatureSet 71 | ret = await _parent.WriteRead20(_parent.DevShort, new byte[7] { 0x10, _deviceIdx, 0x00, 0x00 | SW_ID, 0x00, 0x01, 0x00 }); 72 | _featureMap[0x0001] = ret.GetParam(0); 73 | 74 | // Get Feature Count 75 | ret = await _parent.WriteRead20(_parent.DevShort, new byte[7] { 0x10, _deviceIdx, _featureMap[0x0001], 0x00 | SW_ID, 0x00, 0x00, 0x00 }); 76 | int featureCount = ret.GetParam(0); 77 | 78 | // Enumerate Features 79 | for (byte i = 0; i <= featureCount; i++) 80 | { 81 | ret = await _parent.WriteRead20(_parent.DevShort, new byte[7] { 0x10, _deviceIdx, _featureMap[0x0001], 0x10 | SW_ID, i, 0x00, 0x00 }); 82 | ushort featureId = (ushort)((ret.GetParam(0) << 8) + ret.GetParam(1)); 83 | 84 | _featureMap[featureId] = i; 85 | } 86 | 87 | await InitPopulateAsync(); 88 | } 89 | finally 90 | { 91 | _initSemaphore.Release(); 92 | } 93 | } 94 | 95 | [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0018:Inline variable declaration")] 96 | private async Task InitPopulateAsync() 97 | { 98 | Hidpp20 ret; 99 | byte featureId; 100 | 101 | // Device name 102 | if (_featureMap.TryGetValue(0x0005, out featureId)) 103 | { 104 | ret = await _parent.WriteRead20(_parent.DevShort, new byte[7] { 0x10, _deviceIdx, featureId, 0x00 | SW_ID, 0x00, 0x00, 0x00 }); 105 | int nameLength = ret.GetParam(0); 106 | 107 | string name = ""; 108 | 109 | while (name.Length < nameLength) 110 | { 111 | ret = await _parent.WriteRead20(_parent.DevShort, new byte[7] { 0x10, _deviceIdx, featureId, 0x10 | SW_ID, (byte)name.Length, 0x00, 0x00 }); 112 | name += Encoding.UTF8.GetString(ret.GetParams()); 113 | } 114 | 115 | DeviceName = name.TrimEnd('\0'); 116 | 117 | foreach (var tag in GlobalSettings.settings.DisabledDevices) 118 | { 119 | if (DeviceName.Contains(tag)) 120 | { 121 | Log.WriteLine($"{DeviceName} is marked as disabled"); 122 | return; 123 | } 124 | }; 125 | 126 | ret = await _parent.WriteRead20(_parent.DevShort, new byte[7] { 0x10, _deviceIdx, featureId, 0x20 | SW_ID, 0x00, 0x00, 0x00 }); 127 | DeviceType = ret.GetParam(0); 128 | } 129 | else 130 | { 131 | // Device does not have a name/Hidpp error ignore it 132 | return; 133 | } 134 | 135 | if (_featureMap.TryGetValue(0x0003, out featureId)) 136 | { 137 | ret = await _parent.WriteRead20(_parent.DevShort, new byte[7] { 0x10, _deviceIdx, featureId, 0x00 | SW_ID, 0x00, 0x00, 0x00 }); 138 | 139 | string unitId = BitConverter.ToString(ret.GetParams().ToArray(), 1, 4).Replace("-", string.Empty); 140 | string modelId = BitConverter.ToString(ret.GetParams().ToArray(), 7, 5).Replace("-", string.Empty); 141 | 142 | bool serialNumberSupported = (ret.GetParam(14) & 0x1) == 0x1; 143 | string? serialNumber = null; 144 | if (serialNumberSupported) 145 | { 146 | ret = await _parent.WriteRead20(_parent.DevShort, new byte[7] { 0x10, _deviceIdx, featureId, 0x20 | SW_ID, 0x00, 0x00, 0x00 }); 147 | serialNumber = BitConverter.ToString(ret.GetParams().ToArray(), 0, 11).Replace("-", string.Empty); 148 | } 149 | 150 | Identifier = serialNumber ?? $"{unitId}-{modelId}"; 151 | } 152 | else 153 | { 154 | // Device does not have a serial identifier the device name as a hash identifier 155 | Identifier = $"{DeviceName.GetHashCode():X04}"; 156 | } 157 | 158 | #if DEBUG 159 | Log.WriteLine("---"); 160 | Log.WriteLine(DeviceName + " Ready"); 161 | Log.WriteLine(Identifier); 162 | foreach ((ushort featureIdItr, string featureDesc) in new (ushort, string)[] 163 | { 164 | (0x1000, "Battery Unified Level"), 165 | (0x1001, "Battery Voltage"), 166 | (0x1004, "Unified Battery"), 167 | }) 168 | { 169 | if (_featureMap.ContainsKey(featureIdItr)) 170 | { 171 | Log.WriteLine($"0x{featureIdItr:X} - {featureDesc} Found"); 172 | } 173 | } 174 | Log.WriteLine("---"); 175 | #endif 176 | 177 | _getBatteryAsync = FeatureMap switch 178 | { 179 | { } when FeatureMap.ContainsKey(0x1000) => Battery1000.GetBatteryAsync, 180 | { } when FeatureMap.ContainsKey(0x1001) => Battery1001.GetBatteryAsync, 181 | { } when FeatureMap.ContainsKey(0x1004) => Battery1004.GetBatteryAsync, 182 | _ => null 183 | }; 184 | 185 | HidppManagerContext.Instance.SignalDeviceEvent( 186 | IPCMessageType.INIT, 187 | new InitMessage(Identifier, DeviceName, _getBatteryAsync != null, (DeviceType)DeviceType) 188 | ); 189 | 190 | await Task.Delay(1000); 191 | 192 | _ = Task.Run(async () => 193 | { 194 | if (_getBatteryAsync == null) { return; } 195 | 196 | while (true) 197 | { 198 | var now = DateTimeOffset.Now; 199 | #if DEBUG 200 | var expectedUpdateTime = lastUpdate.AddSeconds(1); 201 | #else 202 | var expectedUpdateTime = lastUpdate.AddSeconds(GlobalSettings.settings.PollPeriod); 203 | #endif 204 | if (now < expectedUpdateTime) 205 | { 206 | await Task.Delay((int)(expectedUpdateTime - now).TotalMilliseconds); 207 | } 208 | 209 | await UpdateBattery(); 210 | await Task.Delay(GlobalSettings.settings.RetryTime * 1000); 211 | } 212 | }); 213 | } 214 | 215 | public async Task UpdateBattery(bool forceIpcUpdate = false) 216 | { 217 | if (Parent.Disposed) { return; } 218 | if (_getBatteryAsync == null) { return; } 219 | 220 | var ret = await _getBatteryAsync.Invoke(this); 221 | 222 | if (ret == null) { return; } 223 | 224 | var batStatus = ret.Value; 225 | lastUpdate = DateTimeOffset.Now; 226 | 227 | if (forceIpcUpdate || (batStatus == lastBatteryReturn)) 228 | { 229 | // Don't report if no change 230 | return; 231 | } 232 | 233 | lastBatteryReturn = batStatus; 234 | HidppManagerContext.Instance.SignalDeviceEvent( 235 | IPCMessageType.UPDATE, 236 | new UpdateMessage(Identifier, batStatus.batteryPercentage, batStatus.status, batStatus.batteryMVolt, lastUpdate) 237 | ); 238 | } 239 | } 240 | } 241 | -------------------------------------------------------------------------------- /LGSTrayUI/Properties/Resources.Designer.cs: -------------------------------------------------------------------------------- 1 | //------------------------------------------------------------------------------ 2 | // 3 | // This code was generated by a tool. 4 | // Runtime Version:4.0.30319.42000 5 | // 6 | // Changes to this file may cause incorrect behavior and will be lost if 7 | // the code is regenerated. 8 | // 9 | //------------------------------------------------------------------------------ 10 | 11 | namespace LGSTrayUI.Properties { 12 | using System; 13 | 14 | 15 | /// 16 | /// A strongly-typed resource class, for looking up localized strings, etc. 17 | /// 18 | // This class was auto-generated by the StronglyTypedResourceBuilder 19 | // class via a tool like ResGen or Visual Studio. 20 | // To add or remove a member, edit your .ResX file then rerun ResGen 21 | // with the /str option, or rebuild your VS project. 22 | [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "17.0.0.0")] 23 | [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] 24 | [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] 25 | internal class Resources { 26 | 27 | private static global::System.Resources.ResourceManager resourceMan; 28 | 29 | private static global::System.Globalization.CultureInfo resourceCulture; 30 | 31 | [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] 32 | internal Resources() { 33 | } 34 | 35 | /// 36 | /// Returns the cached ResourceManager instance used by this class. 37 | /// 38 | [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] 39 | internal static global::System.Resources.ResourceManager ResourceManager { 40 | get { 41 | if (object.ReferenceEquals(resourceMan, null)) { 42 | global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("LGSTrayUI.Properties.Resources", typeof(Resources).Assembly); 43 | resourceMan = temp; 44 | } 45 | return resourceMan; 46 | } 47 | } 48 | 49 | /// 50 | /// Overrides the current thread's CurrentUICulture property for all 51 | /// resource lookups using this strongly typed resource class. 52 | /// 53 | [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] 54 | internal static global::System.Globalization.CultureInfo Culture { 55 | get { 56 | return resourceCulture; 57 | } 58 | set { 59 | resourceCulture = value; 60 | } 61 | } 62 | 63 | /// 64 | /// Looks up a localized resource of type System.Drawing.Bitmap. 65 | /// 66 | internal static System.Drawing.Bitmap Battery { 67 | get { 68 | object obj = ResourceManager.GetObject("Battery", resourceCulture); 69 | return ((System.Drawing.Bitmap)(obj)); 70 | } 71 | } 72 | 73 | /// 74 | /// Looks up a localized resource of type System.Drawing.Bitmap. 75 | /// 76 | internal static System.Drawing.Bitmap Battery_dark { 77 | get { 78 | object obj = ResourceManager.GetObject("Battery_dark", resourceCulture); 79 | return ((System.Drawing.Bitmap)(obj)); 80 | } 81 | } 82 | 83 | /// 84 | /// Looks up a localized resource of type System.Drawing.Bitmap. 85 | /// 86 | internal static System.Drawing.Bitmap Charging { 87 | get { 88 | object obj = ResourceManager.GetObject("Charging", resourceCulture); 89 | return ((System.Drawing.Bitmap)(obj)); 90 | } 91 | } 92 | 93 | /// 94 | /// Looks up a localized resource of type System.Drawing.Bitmap. 95 | /// 96 | internal static System.Drawing.Bitmap Charging_dark { 97 | get { 98 | object obj = ResourceManager.GetObject("Charging_dark", resourceCulture); 99 | return ((System.Drawing.Bitmap)(obj)); 100 | } 101 | } 102 | 103 | /// 104 | /// Looks up a localized resource of type System.Byte[]. 105 | /// 106 | internal static byte[] defaultAppsettings { 107 | get { 108 | object obj = ResourceManager.GetObject("defaultAppsettings", resourceCulture); 109 | return ((byte[])(obj)); 110 | } 111 | } 112 | 113 | /// 114 | /// Looks up a localized resource of type System.Drawing.Bitmap. 115 | /// 116 | internal static System.Drawing.Bitmap Headset { 117 | get { 118 | object obj = ResourceManager.GetObject("Headset", resourceCulture); 119 | return ((System.Drawing.Bitmap)(obj)); 120 | } 121 | } 122 | 123 | /// 124 | /// Looks up a localized resource of type System.Drawing.Bitmap. 125 | /// 126 | internal static System.Drawing.Bitmap Headset_dark { 127 | get { 128 | object obj = ResourceManager.GetObject("Headset_dark", resourceCulture); 129 | return ((System.Drawing.Bitmap)(obj)); 130 | } 131 | } 132 | 133 | /// 134 | /// Looks up a localized resource of type System.Drawing.Bitmap. 135 | /// 136 | internal static System.Drawing.Bitmap Indicator_10 { 137 | get { 138 | object obj = ResourceManager.GetObject("Indicator_10", resourceCulture); 139 | return ((System.Drawing.Bitmap)(obj)); 140 | } 141 | } 142 | 143 | /// 144 | /// Looks up a localized resource of type System.Drawing.Bitmap. 145 | /// 146 | internal static System.Drawing.Bitmap Indicator_100 { 147 | get { 148 | object obj = ResourceManager.GetObject("Indicator_100", resourceCulture); 149 | return ((System.Drawing.Bitmap)(obj)); 150 | } 151 | } 152 | 153 | /// 154 | /// Looks up a localized resource of type System.Drawing.Bitmap. 155 | /// 156 | internal static System.Drawing.Bitmap Indicator_30 { 157 | get { 158 | object obj = ResourceManager.GetObject("Indicator_30", resourceCulture); 159 | return ((System.Drawing.Bitmap)(obj)); 160 | } 161 | } 162 | 163 | /// 164 | /// Looks up a localized resource of type System.Drawing.Bitmap. 165 | /// 166 | internal static System.Drawing.Bitmap Indicator_50 { 167 | get { 168 | object obj = ResourceManager.GetObject("Indicator_50", resourceCulture); 169 | return ((System.Drawing.Bitmap)(obj)); 170 | } 171 | } 172 | 173 | /// 174 | /// Looks up a localized resource of type System.Drawing.Bitmap. 175 | /// 176 | internal static System.Drawing.Bitmap Keyboard { 177 | get { 178 | object obj = ResourceManager.GetObject("Keyboard", resourceCulture); 179 | return ((System.Drawing.Bitmap)(obj)); 180 | } 181 | } 182 | 183 | /// 184 | /// Looks up a localized resource of type System.Drawing.Bitmap. 185 | /// 186 | internal static System.Drawing.Bitmap Keyboard_dark { 187 | get { 188 | object obj = ResourceManager.GetObject("Keyboard_dark", resourceCulture); 189 | return ((System.Drawing.Bitmap)(obj)); 190 | } 191 | } 192 | 193 | /// 194 | /// Looks up a localized resource of type System.Drawing.Icon similar to (Icon). 195 | /// 196 | internal static System.Drawing.Icon logo_black { 197 | get { 198 | object obj = ResourceManager.GetObject("logo_black", resourceCulture); 199 | return ((System.Drawing.Icon)(obj)); 200 | } 201 | } 202 | 203 | /// 204 | /// Looks up a localized resource of type System.Drawing.Bitmap. 205 | /// 206 | internal static System.Drawing.Bitmap Missing { 207 | get { 208 | object obj = ResourceManager.GetObject("Missing", resourceCulture); 209 | return ((System.Drawing.Bitmap)(obj)); 210 | } 211 | } 212 | 213 | /// 214 | /// Looks up a localized resource of type System.Drawing.Bitmap. 215 | /// 216 | internal static System.Drawing.Bitmap Missing_dark { 217 | get { 218 | object obj = ResourceManager.GetObject("Missing_dark", resourceCulture); 219 | return ((System.Drawing.Bitmap)(obj)); 220 | } 221 | } 222 | 223 | /// 224 | /// Looks up a localized resource of type System.Drawing.Bitmap. 225 | /// 226 | internal static System.Drawing.Bitmap Mouse { 227 | get { 228 | object obj = ResourceManager.GetObject("Mouse", resourceCulture); 229 | return ((System.Drawing.Bitmap)(obj)); 230 | } 231 | } 232 | 233 | /// 234 | /// Looks up a localized resource of type System.Drawing.Bitmap. 235 | /// 236 | internal static System.Drawing.Bitmap Mouse_dark { 237 | get { 238 | object obj = ResourceManager.GetObject("Mouse_dark", resourceCulture); 239 | return ((System.Drawing.Bitmap)(obj)); 240 | } 241 | } 242 | } 243 | } 244 | -------------------------------------------------------------------------------- /LGSTrayUI/Properties/Resources.resx: -------------------------------------------------------------------------------- 1 | 2 | 3 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | text/microsoft-resx 110 | 111 | 112 | 2.0 113 | 114 | 115 | System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 116 | 117 | 118 | System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 119 | 120 | 121 | 122 | ..\Resources\Battery.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a 123 | 124 | 125 | ..\Resources\Battery_dark.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a 126 | 127 | 128 | ..\Resources\Charging.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a 129 | 130 | 131 | ..\Resources\Charging_dark.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a 132 | 133 | 134 | ..\appsettings.toml;System.Byte[], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 135 | 136 | 137 | ..\Resources\Headset.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a 138 | 139 | 140 | ..\Resources\Headset_dark.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a 141 | 142 | 143 | ..\Resources\Indicator_10.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a 144 | 145 | 146 | ..\Resources\Indicator_100.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a 147 | 148 | 149 | ..\Resources\Indicator_30.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a 150 | 151 | 152 | ..\Resources\Indicator_50.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a 153 | 154 | 155 | ..\Resources\Keyboard.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a 156 | 157 | 158 | ..\Resources\Keyboard_dark.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a 159 | 160 | 161 | ..\Resources\logo_black.ico;System.Drawing.Icon, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a 162 | 163 | 164 | ..\Resources\Missing.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a 165 | 166 | 167 | ..\Resources\Missing_dark.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a 168 | 169 | 170 | ..\Resources\Mouse.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a 171 | 172 | 173 | ..\Resources\Mouse_dark.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a 174 | 175 | -------------------------------------------------------------------------------- /LGSTrayHID/HidppDevices.cs: -------------------------------------------------------------------------------- 1 | using LGSTrayHID.HidApi; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Collections.Immutable; 5 | using System.Data; 6 | using System.Linq; 7 | using System.Reflection.Metadata.Ecma335; 8 | using System.Text; 9 | using System.Threading.Channels; 10 | using System.Threading.Tasks; 11 | 12 | using static LGSTrayHID.HidApi.HidApi; 13 | 14 | namespace LGSTrayHID 15 | { 16 | public class HidppDevices : IDisposable 17 | { 18 | public const byte SW_ID = 0x0A; 19 | private byte PING_PAYLOAD = 0x55; 20 | 21 | private bool _isReading = true; 22 | private const int READ_TIMEOUT = 100; 23 | 24 | private readonly Dictionary _deviceCollection = []; 25 | public IReadOnlyDictionary DeviceCollection => _deviceCollection; 26 | 27 | private readonly SemaphoreSlim _semaphore = new(1, 1); 28 | private readonly Channel _channel = Channel.CreateBounded(new BoundedChannelOptions(5) 29 | { 30 | FullMode = BoundedChannelFullMode.DropOldest, 31 | SingleReader = true, 32 | SingleWriter = true, 33 | }); 34 | 35 | private HidDevicePtr _devShort = IntPtr.Zero; 36 | public HidDevicePtr DevShort 37 | { 38 | get => _devShort; 39 | } 40 | 41 | private HidDevicePtr _devLong = IntPtr.Zero; 42 | public HidDevicePtr DevLong 43 | { 44 | get => _devLong; 45 | } 46 | 47 | private int _disposeCount = 0; 48 | public bool Disposed => _disposeCount > 0; 49 | 50 | public HidppDevices() { } 51 | 52 | public void Dispose() 53 | { 54 | Dispose(disposing: true); 55 | GC.SuppressFinalize(this); 56 | } 57 | 58 | protected virtual void Dispose(bool disposing) 59 | { 60 | if (Interlocked.Increment(ref _disposeCount) == 1) 61 | { 62 | _isReading = false; 63 | 64 | _devShort = IntPtr.Zero; 65 | _devLong = IntPtr.Zero; 66 | } 67 | } 68 | 69 | ~HidppDevices() 70 | { 71 | Dispose(disposing: false); 72 | } 73 | 74 | public async Task SetDevShort(nint devShort) 75 | { 76 | if (_devShort != IntPtr.Zero) 77 | { 78 | throw new ReadOnlyException(); 79 | } 80 | _devShort = devShort; 81 | await SetUp(); 82 | } 83 | 84 | public async Task SetDevLong(nint devLong) 85 | { 86 | if (_devLong != IntPtr.Zero) 87 | { 88 | throw new ReadOnlyException(); 89 | } 90 | _devLong = devLong; 91 | await SetUp(); 92 | } 93 | 94 | private async Task ReadThread(HidDevicePtr dev, int bufferSize) 95 | { 96 | byte[] buffer = new byte[bufferSize]; 97 | while(_isReading) 98 | { 99 | var ret = dev.Read(buffer, bufferSize, READ_TIMEOUT); 100 | if (!_isReading) { break; } 101 | 102 | if (ret < 0) 103 | { 104 | break; 105 | } 106 | else if (ret == 0) 107 | { 108 | continue; 109 | } 110 | 111 | await ProcessMessgage(buffer); 112 | } 113 | 114 | HidClose(dev); 115 | } 116 | 117 | private async Task ProcessMessgage(byte[] buffer) 118 | { 119 | if ((buffer[2] == 0x41) && ((buffer[4] & 0x40) == 0)) 120 | { 121 | byte deviceIdx = buffer[1]; 122 | if (true || !_deviceCollection.ContainsKey(deviceIdx)) 123 | { 124 | _deviceCollection[deviceIdx] = new(this, deviceIdx); 125 | new Thread(async () => 126 | { 127 | try 128 | { 129 | await Task.Delay(1000); 130 | await _deviceCollection[deviceIdx].InitAsync(); 131 | } 132 | catch (Exception) { } 133 | }).Start(); 134 | } 135 | } 136 | else 137 | { 138 | await _channel.Writer.WriteAsync(buffer); 139 | } 140 | } 141 | 142 | public async Task WriteRead10(HidDevicePtr hidDevicePtr, byte[] buffer, int timeout = 100) 143 | { 144 | ObjectDisposedException.ThrowIf(_disposeCount > 0, this); 145 | 146 | bool locked = await _semaphore.WaitAsync(100); 147 | if (!locked) 148 | { 149 | return []; 150 | } 151 | 152 | try 153 | { 154 | await hidDevicePtr.WriteAsync((byte[])buffer); 155 | 156 | CancellationTokenSource cts = new(); 157 | cts.CancelAfter(timeout); 158 | 159 | byte[] ret; 160 | while (!cts.IsCancellationRequested) 161 | { 162 | try 163 | { 164 | ret = await _channel.Reader.ReadAsync(cts.Token); 165 | 166 | if ((ret[2] == 0x8F) || (ret[2] == buffer[2])) 167 | { 168 | return ret; 169 | } 170 | } 171 | catch (OperationCanceledException) { break; } 172 | } 173 | 174 | return []; 175 | } 176 | finally 177 | { 178 | _semaphore.Release(); 179 | } 180 | } 181 | 182 | public async Task WriteRead20(HidDevicePtr hidDevicePtr, Hidpp20 buffer, int timeout = 100, bool ignoreHID10 = true) 183 | { 184 | ObjectDisposedException.ThrowIf(_disposeCount > 0, this); 185 | 186 | bool locked = await _semaphore.WaitAsync(100); 187 | if (!locked) 188 | { 189 | return (Hidpp20)Array.Empty(); 190 | } 191 | 192 | try 193 | { 194 | await hidDevicePtr.WriteAsync((byte[]) buffer); 195 | 196 | CancellationTokenSource cts = new(); 197 | cts.CancelAfter(timeout); 198 | 199 | Hidpp20 ret; 200 | while (!cts.IsCancellationRequested) 201 | { 202 | try 203 | { 204 | ret = await _channel.Reader.ReadAsync(cts.Token); 205 | 206 | if (!ignoreHID10 && (ret.GetFeatureIndex() == 0x8F)) 207 | { 208 | // HID++ 1.0 response or timeout 209 | break; 210 | } 211 | 212 | if ((ret.GetFeatureIndex() == buffer.GetFeatureIndex()) && (ret.GetSoftwareId() == SW_ID)) 213 | { 214 | return ret; 215 | } 216 | } 217 | catch (OperationCanceledException) { break; } 218 | } 219 | 220 | return (Hidpp20) Array.Empty(); 221 | } 222 | finally 223 | { 224 | _semaphore.Release(); 225 | } 226 | } 227 | 228 | public async Task Ping20(byte deviceId, int timeout = 100, bool ignoreHIDPP10 = true) 229 | { 230 | ObjectDisposedException.ThrowIf(_disposeCount > 0, this); 231 | 232 | byte pingPayload = ++PING_PAYLOAD; 233 | Hidpp20 buffer = new byte[7] { 0x10, deviceId, 0x00, 0x10 | SW_ID, 0x00, 0x00, pingPayload }; 234 | Hidpp20 ret = await WriteRead20(_devShort, buffer, timeout, ignoreHIDPP10); 235 | if (ret.Length == 0) 236 | { 237 | return false; 238 | } 239 | 240 | return (ret.GetFeatureIndex() == 0x00) && (ret.GetSoftwareId() == SW_ID) && (ret.GetParam(2) == pingPayload); 241 | 242 | //bool locked = await _semaphore.WaitAsync(100); 243 | //if (!locked) 244 | //{ 245 | // return false; 246 | //} 247 | 248 | //try 249 | //{ 250 | // byte pingPayload = ++PING_PAYLOAD; 251 | // Hidpp20 buffer = new byte[7] { 0x10, deviceId, 0x00, 0x10 | SW_ID, 0x00, 0x00, pingPayload }; 252 | // await _devShort.WriteAsync((byte[])buffer); 253 | 254 | // CancellationTokenSource cts = new(); 255 | // cts.CancelAfter(timeout); 256 | 257 | // Hidpp20 ret; 258 | // while (!cts.IsCancellationRequested) 259 | // { 260 | // try 261 | // { 262 | // ret = await _channel.Reader.ReadAsync(cts.Token); 263 | 264 | // if (!ignoreHIDPP10 && (ret.GetFeatureIndex() == 0x8F)) 265 | // { 266 | // // HID++ 1.0 response or timeout 267 | // break; 268 | // } 269 | 270 | // if ((ret.GetFeatureIndex() == 0x00) && (ret.GetSoftwareId() == SW_ID) && (ret.GetParam(2) == pingPayload)) 271 | // { 272 | // return true; 273 | // } 274 | // } 275 | // catch (OperationCanceledException) { break; } 276 | // } 277 | 278 | // return false; 279 | //} 280 | //finally 281 | //{ 282 | // _semaphore.Release(); 283 | //} 284 | } 285 | 286 | private async Task SetUp() 287 | { 288 | if ((_devShort == IntPtr.Zero) || (_devLong == IntPtr.Zero)) 289 | { 290 | return; 291 | } 292 | 293 | #if DEBUG 294 | Console.WriteLine("Device ready"); 295 | #endif 296 | 297 | Thread t1 = new(async () => { await ReadThread(_devShort, 7); }) 298 | { 299 | Priority = ThreadPriority.BelowNormal 300 | }; 301 | t1.Start(); 302 | 303 | Thread t2 = new(async () => { await ReadThread(_devLong, 20); }) 304 | { 305 | Priority = ThreadPriority.BelowNormal 306 | }; 307 | t2.Start(); 308 | 309 | byte[] ret; 310 | 311 | // Read number of devices on reciever 312 | ret = await WriteRead10(_devShort, [0x10, 0xFF, 0x81, 0x02, 0x00, 0x00, 0x00], 1000); 313 | byte numDeviceFound = 0; 314 | if ((ret[2] == 0x81) && (ret[3] == 0x02)) 315 | { 316 | numDeviceFound = ret[5]; 317 | } 318 | 319 | if (numDeviceFound > 0) 320 | { 321 | // Force arrival announce 322 | ret = await WriteRead10(_devShort, [0x10, 0xFF, 0x80, 0x02, 0x02, 0x00, 0x00], 1000); 323 | } 324 | 325 | await Task.Delay(500); 326 | 327 | if (_deviceCollection.Count == 0) 328 | { 329 | // Fail to enumerate devices 330 | for (byte i = 1; i <= 6; i++) 331 | { 332 | var ping = await Ping20(i, 100, false); 333 | if (ping) 334 | { 335 | var deviceIdx = i; 336 | _deviceCollection[deviceIdx] = new(this, deviceIdx); 337 | } 338 | } 339 | 340 | foreach ((_, var device) in _deviceCollection) 341 | { 342 | await device.InitAsync(); 343 | } 344 | } 345 | } 346 | } 347 | } 348 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------