├── res ├── icon.ico ├── icon.png ├── ryzenadj.exe ├── icon_dark.png ├── icon_light.png ├── WinRing0x64.dll ├── WinRing0x64.sys ├── atrofac-cli.exe └── ChangeScreenResolution.exe ├── .gitattributes ├── data ├── res │ ├── icon.ico │ ├── icon.png │ ├── ryzenadj.exe │ ├── icon_dark.png │ ├── icon_light.png │ ├── WinRing0x64.dll │ ├── WinRing0x64.sys │ ├── atrofac-cli.exe │ └── ChangeScreenResolution.exe ├── stopROGkey.bat ├── restartGPUcmd.bat ├── restartGPU.ps1 └── config.yml ├── images ├── Create-Task-1.png ├── Create-Task-2.png ├── Create-Task-3.png └── Create-Task-4.png ├── install-without-reqs.bat ├── winusbpy ├── __init__.py ├── winusberror.py ├── winusb.py ├── winusbclasses.py ├── examples │ ├── winusbtest2.py │ └── winusbtest.py ├── winusbutils.py └── winusbpy.py ├── restartGPUcmd.bat ├── install.bat ├── testing files ├── toasttest.py ├── dicttest.py ├── windowspowerplans.py ├── powerplantest.py └── threadtest.py ├── requirements.txt ├── setup.py ├── AUTOSTART.md ├── pywinusb └── hid │ ├── __init__.py │ ├── helpers.py │ ├── tools.py │ ├── hid_pnp_mixin.py │ ├── wnd_hook_mixin.py │ └── winapi.py ├── G14ControlThreads.py ├── G14Data.py ├── tests.py ├── .gitignore ├── G14Utils.py ├── README.md ├── G14RunCommands.py ├── G14Control.pyw └── LICENSE /res/icon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aredden/G14ControlR3/HEAD/res/icon.ico -------------------------------------------------------------------------------- /res/icon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aredden/G14ControlR3/HEAD/res/icon.png -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | # Auto detect text files and perform LF normalization 2 | * text=auto 3 | -------------------------------------------------------------------------------- /res/ryzenadj.exe: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aredden/G14ControlR3/HEAD/res/ryzenadj.exe -------------------------------------------------------------------------------- /data/res/icon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aredden/G14ControlR3/HEAD/data/res/icon.ico -------------------------------------------------------------------------------- /data/res/icon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aredden/G14ControlR3/HEAD/data/res/icon.png -------------------------------------------------------------------------------- /res/icon_dark.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aredden/G14ControlR3/HEAD/res/icon_dark.png -------------------------------------------------------------------------------- /res/icon_light.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aredden/G14ControlR3/HEAD/res/icon_light.png -------------------------------------------------------------------------------- /data/res/ryzenadj.exe: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aredden/G14ControlR3/HEAD/data/res/ryzenadj.exe -------------------------------------------------------------------------------- /res/WinRing0x64.dll: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aredden/G14ControlR3/HEAD/res/WinRing0x64.dll -------------------------------------------------------------------------------- /res/WinRing0x64.sys: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aredden/G14ControlR3/HEAD/res/WinRing0x64.sys -------------------------------------------------------------------------------- /res/atrofac-cli.exe: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aredden/G14ControlR3/HEAD/res/atrofac-cli.exe -------------------------------------------------------------------------------- /data/res/icon_dark.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aredden/G14ControlR3/HEAD/data/res/icon_dark.png -------------------------------------------------------------------------------- /data/res/icon_light.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aredden/G14ControlR3/HEAD/data/res/icon_light.png -------------------------------------------------------------------------------- /data/res/WinRing0x64.dll: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aredden/G14ControlR3/HEAD/data/res/WinRing0x64.dll -------------------------------------------------------------------------------- /data/res/WinRing0x64.sys: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aredden/G14ControlR3/HEAD/data/res/WinRing0x64.sys -------------------------------------------------------------------------------- /data/res/atrofac-cli.exe: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aredden/G14ControlR3/HEAD/data/res/atrofac-cli.exe -------------------------------------------------------------------------------- /images/Create-Task-1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aredden/G14ControlR3/HEAD/images/Create-Task-1.png -------------------------------------------------------------------------------- /images/Create-Task-2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aredden/G14ControlR3/HEAD/images/Create-Task-2.png -------------------------------------------------------------------------------- /images/Create-Task-3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aredden/G14ControlR3/HEAD/images/Create-Task-3.png -------------------------------------------------------------------------------- /images/Create-Task-4.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aredden/G14ControlR3/HEAD/images/Create-Task-4.png -------------------------------------------------------------------------------- /res/ChangeScreenResolution.exe: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aredden/G14ControlR3/HEAD/res/ChangeScreenResolution.exe -------------------------------------------------------------------------------- /data/res/ChangeScreenResolution.exe: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aredden/G14ControlR3/HEAD/data/res/ChangeScreenResolution.exe -------------------------------------------------------------------------------- /data/stopROGkey.bat: -------------------------------------------------------------------------------- 1 | taskkill /IM "ArmouryCrateKeyControl.exe" /F 2 | ren C:\Windows\System32\ASUSACCI\ArmouryCrateKeyControl.exe ArmouryCrateKeyControl_disabled.exe -------------------------------------------------------------------------------- /install-without-reqs.bat: -------------------------------------------------------------------------------- 1 | python setup.py build 2 | xcopy build\exe.win32-3.8\ C:\G14control\ /E /C 3 | xcopy data\ C:\G14control\ /E /C 4 | xcopy pywinusb\ C:\G14control\lib\pywinusb\ /E /C -------------------------------------------------------------------------------- /winusbpy/__init__.py: -------------------------------------------------------------------------------- 1 | import os 2 | if os.name == 'nt': 3 | from .winusbpy import * 4 | from .winusb import * 5 | else: 6 | raise ImportError("WinUsbPy only works on Windows platform") 7 | -------------------------------------------------------------------------------- /data/restartGPUcmd.bat: -------------------------------------------------------------------------------- 1 | PowerShell -NoProfile -ExecutionPolicy Bypass -Command "& {Start-Process PowerShell -ArgumentList '-NoProfile -ExecutionPolicy Bypass -File ""C:\G14control\restartGPU.ps1""' -Verb RunAs}"; -------------------------------------------------------------------------------- /restartGPUcmd.bat: -------------------------------------------------------------------------------- 1 | PowerShell -NoProfile -ExecutionPolicy Bypass -Command "& {Start-Process PowerShell -ArgumentList '-NoProfile -ExecutionPolicy Bypass -File ""C:\Program Files\G14control\restartGPU.ps1""' -Verb RunAs}"; -------------------------------------------------------------------------------- /data/restartGPU.ps1: -------------------------------------------------------------------------------- 1 | Disable-PnpDevice -InstanceId (Get-PnpDevice -FriendlyName *"NVIDIA Geforce"* -Status OK).InstanceId -Confirm:$false 2 | 3 | Enable-PnpDevice -InstanceId (Get-PnpDevice -FriendlyName *"NVIDIA Geforce"* ).InstanceId -Confirm:$false -------------------------------------------------------------------------------- /install.bat: -------------------------------------------------------------------------------- 1 | pip install -r requirements.txt 2 | pip uninstall setuptools 3 | pip install setuptools==44.0.0 4 | python setup.py build 5 | xcopy build\exe.win32-3.8\ C:\G14control\ /E /C 6 | xcopy data\ C:\G14control\ /E /C 7 | xcopy pywinusb\ C:\G14control\lib\pywinusb\ /E /C -------------------------------------------------------------------------------- /testing files/toasttest.py: -------------------------------------------------------------------------------- 1 | from win10toast import ToastNotifier 2 | toaster = ToastNotifier() 3 | 4 | toaster.show_toast("Hello World!!!", 5 | "Python is 10 seconds awsm!", 6 | icon_path="res/icon.ico", 7 | duration=10) 8 | -------------------------------------------------------------------------------- /winusbpy/winusberror.py: -------------------------------------------------------------------------------- 1 | class WinUSBError(Exception): 2 | 3 | def __init__(self, reason, response=None): 4 | self.reason = reason 5 | self.response = response 6 | Exception.__init__(self, reason) 7 | 8 | def __str__(self): 9 | return self.reason 10 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | astroid==2.4.2 2 | colorama==0.4.3 3 | isort==4.3.21 4 | lazy-object-proxy==1.4.* 5 | mccabe==0.6.1 6 | Pillow==8.1.1 7 | pylint==2.5.3 8 | pypiwin32==223 9 | pystray==0.17.1 10 | pywin32==228 11 | PyYAML==5.4 12 | six==1.15.0 13 | toml==0.10.1 14 | wrapt==1.12.1 15 | psutil==5.7.0 16 | cx_Freeze==6.1 17 | keyboard==0.13.5 18 | pywinusb==0.4.2 19 | win10toast==0.9 -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | from cx_Freeze import * 2 | 3 | 4 | setup( 5 | name="G14Control", 6 | version="0.1", 7 | options={'build_exe': {'packages': ['resources', 'pystray._win32']}}, 8 | executables=[ 9 | Executable( 10 | script="G14Control.pyw", 11 | icon="res\icon.ico", 12 | base="Win32GUI" 13 | ) 14 | ] 15 | ) 16 | -------------------------------------------------------------------------------- /testing files/dicttest.py: -------------------------------------------------------------------------------- 1 | import os, re 2 | 3 | win_opts = re.findall(r"([0-9a-f\-]{36}) *\((.*)\) *\*?\n", os.popen("powercfg /l").read()) 4 | 5 | names:dict 6 | 7 | 8 | 9 | 10 | def thing(): 11 | global names 12 | print(names) 13 | 14 | 15 | 16 | def thing0(): 17 | 18 | names = {x[1]:False for x in win_opts} 19 | names['Balanced'] = True 20 | 21 | thing0() 22 | 23 | thing() -------------------------------------------------------------------------------- /testing files/windowspowerplans.py: -------------------------------------------------------------------------------- 1 | import os 2 | import re 3 | 4 | 5 | windows_power_options = list(map(lambda to_break: tuple(re.sub(r"^ +| +$", "", to_break).split(" ", maxsplit=1)), list( 6 | map(lambda x: re.sub(r"Power Scheme GUID: |[*()]|\n", "", x).replace(" ", " "), os.popen('powercfg /l').readlines()[3:])))) 7 | 8 | 9 | windows_power_options_cleaner = re.findall( 10 | r"([0-9a-f\-]{36}) *\((.*)\) *\*?\n", os.popen("powercfg /l").read()) 11 | 12 | startspace = re.compile("^ ") 13 | endspace = re.compile(' $') 14 | lines = os.popen('powercfg /l').readlines()[3:] 15 | 16 | print(windows_power_options) 17 | -------------------------------------------------------------------------------- /testing files/powerplantest.py: -------------------------------------------------------------------------------- 1 | import os 2 | import subprocess 3 | default_power_plan = "Balanced" 4 | dpp_GUID = "" 5 | alt_power_plan = "temp power plan" 6 | app_GUID = "" 7 | #print(subprocess.check_output(["powercfg", "-getactivescheme"])) 8 | all_plans = subprocess.check_output(["powercfg", "/l"]) 9 | print(str(all_plans).split('\\n')) 10 | for i in str(all_plans).split('\\n'): 11 | if i.find(default_power_plan) != -1: 12 | dpp_GUID = i.split(' ')[3] 13 | if i.find(alt_power_plan) != -1: 14 | app_GUID = i.split(' ')[3] 15 | print(dpp_GUID) 16 | print(app_GUID) 17 | #print(subprocess.check_output(["powercfg", "/s", "381b4222-f694-41f0-9685-ff5bb260df2e"])) 18 | #Power Scheme GUID: 381b4222-f694-41f0-9685-ff5bb260df2e (Balanced) 19 | #Power Scheme GUID: ce457de0-6c6b-4294-9262-02eaa222e48a (temp power plan) -------------------------------------------------------------------------------- /testing files/threadtest.py: -------------------------------------------------------------------------------- 1 | import threading 2 | import os 3 | import time 4 | import ctypes 5 | 6 | 7 | class PowerThreadTest(threading.Thread): 8 | def __init__(self): 9 | threading.Thread.__init__(self) 10 | 11 | def run(self): 12 | while True: 13 | print('running') 14 | time.sleep(1) 15 | 16 | def kill(self): 17 | print('trying to kill') 18 | res = ctypes.pythonapi.PyThreadState_SetAsyncExc(self.ident, 19 | ctypes.py_object(SystemExit)) 20 | if res > 1: 21 | ctypes.pythonapi.PyThreadState_SetAsyncExc(self.ident, 0) 22 | print('Exception raise failure') 23 | 24 | 25 | def starto(): 26 | thd = PowerThreadTest() 27 | thd.start() 28 | time.sleep(6) 29 | thd.kill() 30 | thd.join() 31 | print("ded") 32 | print(thd, thd.is_alive()) 33 | 34 | 35 | starto() 36 | -------------------------------------------------------------------------------- /AUTOSTART.md: -------------------------------------------------------------------------------- 1 | # G14Control 2 | 3 | ## How to start program on boot 4 | 5 | Prerequisite: Make sure G14Control folder is somewhere permanent, in this case it is in C:\Program Files\G14Control 6 | 7 | 1) Go to start menu and open 'Task Scheduler' 8 | 9 | 2) Create a new task 10 | 11 | ![Image1](images/Create-Task-1.png) 12 | 13 | 14 | 3) In the General Tab, Name it G14Control, make sure 'Run when user logged in' and 'Run with highest privileges' 15 | 16 | ![Image1](images/Create-Task-2.png) 17 | 18 | 19 | 4) On actions tab, create 'New' action. In Action window enter the following (in our example, your location of G14Control.exe may differ): 20 | - Program/script: %windir%\System32\cmd.exe 21 | - Add Arguments: /c start "G14Control" "C:\Program Files\G14Control\G14Control.exe" 22 | - Start in: C:\Program Files\G14Control\ 23 | 24 | ![Image1](images/Create-Task-3.png) 25 | 26 | 5) In conditions tab, uncheck 'Stop if switches to battery power' THEN 'start only if on ac' 27 | 28 | ![Image1](images/Create-Task-4.png) 29 | 30 | 6) Click OK to save. Try rebooting, a seconds to minutes after logging back in, you should see the G14 Tray icon appear! 31 | -------------------------------------------------------------------------------- /pywinusb/hid/__init__.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: latin-1 -*- 3 | """ 4 | ``pywinusb.hid`` -- A package that simplifies HID communications on Windows 5 | --------------------------------------------------------------------------- 6 | 7 | On Windows(TM), HID communications can be handled from user space 8 | applications, this means that no additional drivers are needed for simple 9 | HID interfacing. 10 | 11 | ``pywinusb.hid``, allows to find specific HID class devices, and unless 12 | most simple HID interfacing libraries, allows to work using *HID usages*. 13 | 14 | Usages are the 'spices' of HID communications, in summary a HID device 15 | provides descriptors describing the proper way to extract information from 16 | raw reports. 17 | 18 | Still ``pywinusb.hid`` allows to work at the low 'raw report' level, but 19 | the convenience provided by working on top level usages allows a cleaner 20 | interface. 21 | """ 22 | from __future__ import absolute_import 23 | 24 | __version__ = '0.4.1' 25 | __author__ = 'Rene F. Aguirre ' 26 | __url__ = 'https://github.com/rene-aguirre/pywinusb' 27 | __all__ = [] 28 | 29 | from . import core 30 | get_full_usage_id = core.get_full_usage_id 31 | get_usage_page_id = core.get_usage_page_id 32 | get_short_usage_id = core.get_short_usage_id 33 | hid_device_path_exists = core.hid_device_path_exists 34 | find_all_hid_devices = core.find_all_hid_devices 35 | HidDeviceFilter = core.HidDeviceFilter 36 | HidDevice = core.HidDevice 37 | HID_EVT_NONE = core.HID_EVT_NONE 38 | HID_EVT_ALL = core.HID_EVT_ALL 39 | HID_EVT_CHANGED = core.HID_EVT_CHANGED 40 | HID_EVT_PRESSED = core.HID_EVT_PRESSED 41 | HID_EVT_RELEASED = core.HID_EVT_RELEASED 42 | HID_EVT_SET = core.HID_EVT_SET 43 | HID_EVT_CLEAR = core.HID_EVT_CLEAR 44 | 45 | from . import helpers 46 | HIDError = helpers.HIDError 47 | 48 | from . import hid_pnp_mixin 49 | HidPnPWindowMixin = hid_pnp_mixin.HidPnPWindowMixin 50 | 51 | -------------------------------------------------------------------------------- /winusbpy/winusb.py: -------------------------------------------------------------------------------- 1 | from .winusberror import WinUSBError 2 | from .winusbutils import * 3 | 4 | 5 | class WinUSBApi(object): 6 | """ Facade class wrapping USB library WinUSB""" 7 | 8 | def __init__(self): 9 | 10 | try: 11 | self._kernel32 = windll.kernel32 12 | except WindowsError: 13 | raise WinUSBError("Kernel32 dll is not present. Are you really using Windows?") 14 | 15 | try: 16 | self._winusb = windll.winusb 17 | except WindowsError: 18 | raise WinUSBError("WinUsb dll is not present") 19 | 20 | try: 21 | self._setupapi = windll.SetupApi 22 | except WindowsError: 23 | raise WinUSBError("SetupApi dll is not present") 24 | 25 | self._winusb_functions_dict = get_winusb_functions(self._winusb) 26 | self._kernel32_functions_dict = get_kernel32_functions(self._kernel32) 27 | self._setupapi_functions_dict = get_setupapi_functions(self._setupapi) 28 | 29 | def exec_function_winusb(self, function_name, *args): 30 | function_caller = self._configure_ctype_function(self._winusb_functions_dict, function_name) 31 | return function_caller(args) 32 | 33 | def exec_function_kernel32(self, function_name, *args): 34 | function_caller = self._configure_ctype_function(self._kernel32_functions_dict, function_name) 35 | return function_caller(args) 36 | 37 | def exec_function_setupapi(self, function_name, *args): 38 | function_caller = self._configure_ctype_function(self._setupapi_functions_dict, function_name) 39 | return function_caller(args) 40 | 41 | def _configure_ctype_function(self, dll_dict_functions, function_name): 42 | def _function_caller(*args): 43 | function = dll_dict_functions["functions"][function_name] 44 | try: 45 | function.restype = dll_dict_functions["restypes"][function_name] 46 | function.argtypes = dll_dict_functions["argtypes"][function_name] 47 | except KeyError: 48 | pass 49 | return function(*args[0]) 50 | 51 | return _function_caller 52 | -------------------------------------------------------------------------------- /G14ControlThreads.py: -------------------------------------------------------------------------------- 1 | import threading 2 | import psutil 3 | import ctypes 4 | import time 5 | from G14RunCommands import RunCommands 6 | 7 | 8 | class PowerCheckThread(threading.Thread): 9 | def __init__( 10 | self, 11 | current_plan, 12 | default_ac_plan, 13 | default_dc_plan, 14 | config, 15 | main_cmds: RunCommands, 16 | ): 17 | threading.Thread.__init__(self) 18 | self.current_plan = current_plan 19 | self.default_ac_plan = default_ac_plan 20 | self.default_dc_plan = default_dc_plan 21 | self.config = config 22 | self.main_cmds = main_cmds 23 | 24 | def update_info(self, current_plan): 25 | if current_plan is not None: 26 | self.current_plan = current_plan 27 | 28 | def run(self): 29 | current_plan = self.current_plan 30 | default_ac_plan = self.default_ac_plan 31 | default_dc_plan = self.default_dc_plan 32 | main_cmds = self.main_cmds 33 | config = self.config 34 | # Only run while loop on startup if auto_power_switch is On (True) 35 | while True: 36 | # Check to user hasn't disabled auto_power_switch (i.e. by manually switching plans) 37 | ac = ( 38 | psutil.sensors_battery().power_plugged 39 | ) # Get the current AC power status 40 | # If on AC power, and not on the default_ac_plan, switch to that plan 41 | if ac and current_plan != default_ac_plan: 42 | for plan in config["plans"]: 43 | if plan["name"] == default_ac_plan: 44 | main_cmds.apply_plan(plan) 45 | break 46 | # If on DC power, and not on the default_dc_plan, switch to that plan 47 | if not ac and current_plan != default_dc_plan: 48 | for plan in config["plans"]: 49 | if plan["name"] == default_dc_plan: 50 | main_cmds.apply_plan(plan) 51 | break 52 | time.sleep(10) 53 | 54 | def kill(self): 55 | res = ctypes.pythonapi.PyThreadState_SetAsyncExc( 56 | self.ident, ctypes.py_object(SystemExit) 57 | ) 58 | if res > 1: 59 | ctypes.pythonapi.PyThreadState_SetAsyncExc(self.ident, 0) 60 | print("Exception raise failure") 61 | 62 | 63 | fans = psutil.sensors_fans() 64 | print(fans.values()) 65 | -------------------------------------------------------------------------------- /pywinusb/hid/helpers.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | """Helper classs, functions and decorators""" 4 | from __future__ import absolute_import 5 | from __future__ import print_function 6 | 7 | import sys 8 | if sys.version_info >= (3,): 9 | from collections import UserList # pylint: disable=no-name-in-module 10 | else: 11 | # python 2 12 | from UserList import UserList # pylint: disable=import-error 13 | 14 | class HIDError(Exception): 15 | "Main HID error exception class type" 16 | pass 17 | 18 | def simple_decorator(decorator): 19 | """This decorator can be used to turn simple functions 20 | into well-behaved decorators, so long as the decorators 21 | are fairly simple. If a decorator expects a function and 22 | returns a function (no descriptors), and if it doesn't 23 | modify function attributes or docstring, then it is 24 | eligible to use this. Simply apply @simple_decorator to 25 | your decorator and it will automatically preserve the 26 | docstring and function attributes of functions to which 27 | it is applied.""" 28 | def new_decorator(funct_target): 29 | """This will be modified""" 30 | decorated = decorator(funct_target) 31 | decorated.__name__ = funct_target.__name__ 32 | decorated.__doc__ = funct_target.__doc__ 33 | decorated.__dict__.update(funct_target.__dict__) 34 | return decorated 35 | # Now a few lines needed to make simple_decorator itself 36 | # be a well-behaved decorator. 37 | new_decorator.__name__ = decorator.__name__ 38 | new_decorator.__doc__ = decorator.__doc__ 39 | new_decorator.__dict__.update(decorator.__dict__) 40 | return new_decorator 41 | 42 | # 43 | # Sample Use: 44 | # 45 | @simple_decorator 46 | def logging_decorator(func): 47 | """Allow logging function calls""" 48 | def you_will_never_see_this_name(*args, **kwargs): 49 | """Neither this docstring""" 50 | print('calling %s ...' % func.__name__) 51 | result = func(*args, **kwargs) 52 | print('completed: %s' % func.__name__) 53 | return result 54 | return you_will_never_see_this_name 55 | 56 | def synchronized(lock): 57 | """ Synchronization decorator. 58 | Allos to set a mutex on any function 59 | """ 60 | @simple_decorator 61 | def wrap(function_target): 62 | """Decorator wrapper""" 63 | def new_function(*args, **kw): 64 | """Decorated function with Mutex""" 65 | lock.acquire() 66 | try: 67 | return function_target(*args, **kw) 68 | finally: 69 | lock.release() 70 | return new_function 71 | return wrap 72 | 73 | class ReadOnlyList(UserList): 74 | "Read only sequence wrapper" 75 | def __init__(self, any_list): 76 | UserList.__init__(self, any_list) 77 | def __setitem__(self, index, value): 78 | raise ValueError("Object is read-only") 79 | 80 | -------------------------------------------------------------------------------- /data/config.yml: -------------------------------------------------------------------------------- 1 | #boost modes: 0 = disabled, 2 = aggressive, 4 = efficient aggressive 2 | app_name: "G14ControlR3" # Name of the app, you can customize that as you wish! 3 | start_on_boot: true # Set to True to enable starting on boot which adds a windows registry entry 4 | notification_time: 5 # How long notifications will stay on the screen 5 | long_notification_time: 5 6 | check_power_every: 10 # Seconds in between checks to get the battery/ac status 7 | default_gaming_plan: "Performance Plus" # Example: "Extreme" 8 | default_gaming_plan_games: [] # Example list: ["7zFM.exe", "notepad++.exe"] 9 | default_starting_plan: "Silent (low-speed fan)" # G14control plan 10 | default_ac_plan: "Silent (low-speed fan)" # G14control plan 11 | default_dc_plan: "Silent (fanless)" # G14control plan 12 | default_power_plan: "Balanced" # Windows Plan 13 | alt_power_plan: "High performance" # Windows Plan 14 | power_switch_enabled: true # Automatically switch power plan to dc_plan when not on power cable 15 | temp_dir: 'C:\temp\' # MUST END with "\"!! 16 | rog_key: null # Rebind rog key to some executable ("C:\G14Control\G14Control.exe" for example) or null to keep as is. 17 | debug: true # true/false Don't change unless you know what you are doing!!! 18 | plans: 19 | - name: Silent (battery) 20 | plan: silent 21 | cpu_curve: "30c:0%,40c:0%,50c:0%,60c:0%,70c:31%,80c:49%,90c:56%,100c:56%" 22 | gpu_curve: "30c:0%,40c:0%,50c:0%,60c:0%,70c:34%,80c:51%,90c:61%,100c:61%" 23 | cpu_tdp: 15000 24 | boost: 0 25 | dgpu_enabled: false 26 | screen_hz: 60 27 | - name: Silent (fanless) 28 | plan: silent 29 | cpu_curve: "30c:0%,40c:0%,50c:0%,60c:0%,70c:31%,80c:49%,90c:56%,100c:56%" 30 | gpu_curve: "30c:0%,40c:0%,50c:0%,60c:0%,70c:34%,80c:51%,90c:61%,100c:61%" 31 | cpu_tdp: 25000 32 | boost: 0 33 | dgpu_enabled: true 34 | screen_hz: 120 35 | - name: Silent (low-speed fan) 36 | plan: silent 37 | cpu_curve: "30c:0%,40c:10%,50c:15%,60c:20%,70c:31%,80c:49%,90c:56%,100c:56%" 38 | gpu_curve: "30c:0%,40c:10%,50c:15%,60c:20%,70c:34%,80c:51%,90c:61%,100c:61%" 39 | cpu_tdp: 30000 40 | boost: 0 41 | dgpu_enabled: true 42 | screen_hz: 120 43 | - name: CPU Cooler 44 | plan: windows 45 | cpu_curve: "30c:20%,40c:50%,50c:50%,60c:50%,70c:70%,80c:70%,90c:80%,100c:90%" 46 | gpu_curve: "30c:20%,40c:50%,50c:50%,60c:50%,70c:70%,80c:70%,90c:80%,100c:90%" 47 | cpu_tdp: 30000 48 | boost: 0 49 | dgpu_enabled: true 50 | screen_hz: 120 51 | - name: Performance 52 | plan: performance 53 | cpu_curve: "30c:0%,40c:23%,50c:25%,60c:28%,70c:31%,80c:49%,90c:56%,100c:56%" 54 | gpu_curve: "30c:0%,40c:23%,50c:25%,60c:28%,70c:34%,80c:51%,90c:61%,100c:61%" 55 | cpu_tdp: 38000 56 | boost: 4 57 | dgpu_enabled: true 58 | screen_hz: 120 59 | - name: Performance Plus 60 | plan: turbo 61 | cpu_curve: "30c:0%,40c:23%,50c:25%,60c:28%,70c:31%,80c:49%,90c:56%,100c:56%" 62 | gpu_curve: "30c:0%,40c:23%,50c:25%,60c:28%,70c:34%,80c:51%,90c:61%,100c:61%" 63 | cpu_tdp: 45000 64 | boost: 2 65 | dgpu_enabled: true 66 | screen_hz: 120 67 | - name: Extreme 68 | plan: turbo 69 | cpu_curve: "30c:20%,40c:50%,50c:50%,60c:50%,70c:70%,80c:70%,90c:80%,100c:90%" 70 | gpu_curve: "30c:20%,40c:50%,50c:50%,60c:50%,70c:70%,80c:70%,90c:80%,100c:90%" 71 | cpu_tdp: 55000 72 | boost: 2 73 | dgpu_enabled: True 74 | screen_hz: 120 75 | -------------------------------------------------------------------------------- /G14Data.py: -------------------------------------------------------------------------------- 1 | from threading import Thread 2 | from G14RunCommands import RunCommands 3 | from G14Utils import ( 4 | get_app_path, 5 | get_active_plan_map, 6 | get_windows_plans, 7 | get_windows_theme, 8 | get_power_plans, 9 | get_windows_plan_map, 10 | ) 11 | import sys 12 | import os 13 | import yaml 14 | import time 15 | 16 | from win10toast import ToastNotifier 17 | 18 | toaster = ToastNotifier() 19 | 20 | 21 | def load_config( 22 | G14dir, 23 | ): # Small function to load the config and return it after parsing 24 | config_loc = "" 25 | # Sets the path accordingly whether it is a python script or a frozen .exe 26 | if getattr(sys, "frozen", False): 27 | # Set absolute path for config.yaml 28 | config_loc = os.path.join(str(G14dir), "config.yml") 29 | elif __file__: 30 | # Set absolute path for config.yaml 31 | config_loc = os.path.join(str(G14dir), "data/config.yml") 32 | 33 | with open(config_loc, "r") as config_file: 34 | return yaml.load(config_file, Loader=yaml.FullLoader) 35 | 36 | 37 | def notify(message, toast_time=5, wait=0): 38 | Thread(target=do_notify, args=(message, toast_time, wait), daemon=True).start() 39 | 40 | 41 | def do_notify(message, toast_time, wait): 42 | if wait > 0: 43 | time.sleep(wait) 44 | toaster.show_toast( 45 | "G14ControlR3", 46 | msg=message, 47 | icon_path="res/icon.ico", 48 | duration=toast_time, 49 | threaded=True, 50 | ) 51 | 52 | 53 | class G14_Data: 54 | def __init__(self): 55 | self.G14dir = get_app_path() 56 | self.config = load_config(self.G14dir) 57 | self.theme = get_windows_theme() 58 | self.windows_plans = get_windows_plans() 59 | self.dpp_GUID, self.app_GUID = get_power_plans(self.config) 60 | self.windows_plan_map = get_windows_plan_map(self.windows_plans) 61 | self.default_starting_plan = self.config["default_starting_plan"] 62 | self.default_power_plan = self.config["default_power_plan"] 63 | self.active_plan_map = get_active_plan_map( 64 | self.windows_plans, self.default_power_plan 65 | ) 66 | self.default_ac_plan = self.config["default_ac_plan"] 67 | self.default_dc_plan = self.config["default_dc_plan"] 68 | self.power_switch_enabled = self.config["power_switch_enabled"] 69 | self.default_gaming_plan = self.config["default_gaming_plan"] 70 | self.default_gaming_plan_games = self.config["default_gaming_plan_games"] 71 | self.auto_power_switch = bool(self.power_switch_enabled) 72 | self.rog_key = self.config["rog_key"] 73 | self.current_plan = self.default_starting_plan 74 | self.current_windows_plan = self.default_power_plan 75 | self.main_cmds = RunCommands( 76 | self.config, 77 | self.G14dir, 78 | self.app_GUID, 79 | self.dpp_GUID, 80 | notify, 81 | self.windows_plans, 82 | self.active_plan_map, 83 | ) 84 | self.registry_key_loc = r"Software\Microsoft\Windows\CurrentVersion\Run" 85 | 86 | self.game_running = False 87 | self.run_gaming_thread = None 88 | self.run_power_thread = None 89 | self.power_thread = None 90 | self.gaming_thread = None 91 | 92 | def update_win_plan(self, new_win_plan_name): 93 | mp = self.active_plan_map 94 | self.active_plan_map = { 95 | key: (new_win_plan_name == key) for key, val in mp.items() 96 | } 97 | -------------------------------------------------------------------------------- /winusbpy/winusbclasses.py: -------------------------------------------------------------------------------- 1 | from ctypes import * 2 | from ctypes.wintypes import * 3 | 4 | _ole32 = oledll.ole32 5 | 6 | _StringFromCLSID = _ole32.StringFromCLSID 7 | _CoTaskMemFree = windll.ole32.CoTaskMemFree 8 | 9 | 10 | """Flags controlling what is included in the device information set built by SetupDiGetClassDevs""" 11 | DIGCF_DEFAULT = 0x00000001 12 | DIGCF_PRESENT = 0x00000002 13 | DIGCF_ALLCLASSES = 0x00000004 14 | DIGCF_PROFILE = 0x00000008 15 | DIGCF_DEVICE_INTERFACE = 0x00000010 16 | 17 | """Flags controlling File acccess""" 18 | GENERIC_WRITE = (1073741824) 19 | GENERIC_READ = (-2147483648) 20 | FILE_SHARE_READ = 1 21 | FILE_SHARE_WRITE = 2 22 | OPEN_EXISTING = 3 23 | OPEN_ALWAYS = 4 24 | FILE_ATTRIBUTE_NORMAL = 128 25 | FILE_FLAG_OVERLAPPED = 1073741824 26 | 27 | INVALID_HANDLE_VALUE = HANDLE(-1) 28 | 29 | """ USB PIPE TYPE """ 30 | PIPE_TYPE_CONTROL = 0 31 | PIPE_TYPE_ISO = 1 32 | PIPE_TYPE_BULK = 2 33 | PIPE_TYPE_INTERRUPT = 3 34 | 35 | 36 | """ Errors """ 37 | ERROR_IO_INCOMPLETE = 996 38 | ERROR_IO_PENDING = 997 39 | 40 | 41 | class UsbSetupPacket(Structure): 42 | _fields_ = [("request_type", c_ubyte), ("request", c_ubyte), 43 | ("value", c_ushort), ("index", c_ushort), ("length", c_ushort)] 44 | 45 | 46 | class Overlapped(Structure): 47 | _fields_ = [('Internal', LPVOID), 48 | ('InternalHigh', LPVOID), 49 | ('Offset', DWORD), 50 | ('OffsetHigh', DWORD), 51 | ('Pointer', LPVOID), 52 | ('hEvent', HANDLE),] 53 | 54 | 55 | class UsbInterfaceDescriptor(Structure): 56 | _fields_ = [("b_length", c_ubyte), ("b_descriptor_type", c_ubyte), 57 | ("b_interface_number", c_ubyte), ("b_alternate_setting", c_ubyte), 58 | ("b_num_endpoints", c_ubyte), ("b_interface_class", c_ubyte), 59 | ("b_interface_sub_class", c_ubyte), ("b_interface_protocol", c_ubyte), 60 | ("i_interface", c_ubyte)] 61 | 62 | 63 | class PipeInfo(Structure): 64 | _fields_ = [("pipe_type", c_ulong,), ("pipe_id", c_ubyte), 65 | ("maximum_packet_size", c_ushort), ("interval", c_ubyte)] 66 | 67 | 68 | class LpSecurityAttributes(Structure): 69 | _fields_ = [("n_length", DWORD), ("lp_security_descriptor", c_void_p), 70 | ("b_Inherit_handle", BOOL)] 71 | 72 | 73 | class GUID(Structure): 74 | _fields_ = [("data1", DWORD), ("data2", WORD), 75 | ("data3", WORD), ("data4", c_byte * 8)] 76 | 77 | def __repr__(self): 78 | return u'GUID("%s")' % str(self) 79 | 80 | def __str__(self): 81 | p = c_wchar_p() 82 | _StringFromCLSID(byref(self), byref(p)) 83 | result = p.value 84 | _CoTaskMemFree(p) 85 | return result 86 | 87 | def __cmp__(self, other): 88 | if isinstance(other, GUID): 89 | a = bytes(self) 90 | b = bytes(other) 91 | return (a > b) - (a < b) 92 | return -1 93 | 94 | def __nonzero__(self): 95 | return self != GUID_null 96 | 97 | def __eq__(self, other): 98 | return isinstance(other, GUID) and \ 99 | bytes(self) == bytes(other) 100 | 101 | def __hash__(self): 102 | # We make GUID instances hashable, although they are mutable. 103 | return hash(bytes(self)) 104 | 105 | 106 | GUID_null = GUID() 107 | 108 | 109 | class SpDevinfoData(Structure): 110 | _fields_ = [("cb_size", DWORD), ("class_guid", GUID), 111 | ("dev_inst", DWORD), ("reserved", POINTER(c_ulong))] 112 | 113 | 114 | class SpDeviceInterfaceData(Structure): 115 | _fields_ = [("cb_size", DWORD), ("interface_class_guid", GUID), 116 | ("flags", DWORD), ("reserved", POINTER(c_ulong))] 117 | 118 | 119 | class SpDeviceInterfaceDetailData(Structure): 120 | _fields_ = [("cb_size", DWORD), ("device_path", WCHAR * 1)] # devicePath array!!! 121 | -------------------------------------------------------------------------------- /tests.py: -------------------------------------------------------------------------------- 1 | from G14Control import gaming_thread_impl, load_config 2 | import unittest 3 | import os 4 | import re 5 | from G14RunCommands import RunCommands 6 | import yaml 7 | import subprocess as sp 8 | import subprocess 9 | import sys 10 | import time 11 | 12 | config = {} 13 | windows_plans = [] 14 | current_windows_plan = "" 15 | app_GUID = "" 16 | dpp_GUID = "" 17 | active_plan_map = dict() 18 | G14dir = "" 19 | 20 | 21 | def get_power_plans(): 22 | global dpp_GUID, app_GUID 23 | all_plans = subprocess.check_output(["powercfg", "/l"]) 24 | for i in str(all_plans).split("\\n"): 25 | print(i) 26 | if i.find(config["default_power_plan"]) != -1: 27 | dpp_GUID = i.split(" ")[3] 28 | if i.find(config["alt_power_plan"]) != -1: 29 | app_GUID = i.split(" ")[3] 30 | 31 | 32 | def get_windows_plans(): 33 | global config, active_plan_map, current_windows_plan 34 | windows_power_options = re.findall( 35 | r"([0-9a-f\-]{36}) *\((.*)\) *\*?\n", os.popen("powercfg /l").read() 36 | ) 37 | active_plan_map = {x[1]: False for x in windows_power_options} 38 | active_plan_map[current_windows_plan] = True 39 | return windows_power_options 40 | 41 | 42 | """ 43 | Cannot be run before @get_windows_plans() 44 | """ 45 | 46 | 47 | def get_active_plan_map(): 48 | global windows_plans, active_plan_map 49 | try: 50 | active_plan_map["Balanced"] 51 | return active_plan_map 52 | except Exception: 53 | active_plan_map = {x[1]: False for x in windows_plans} 54 | active_plan_map[current_windows_plan] = True 55 | return active_plan_map 56 | 57 | 58 | def get_app_path(): 59 | global G14dir 60 | G14Dir = "" 61 | # Sets the path accordingly whether it is a python script or a frozen .exe 62 | if getattr(sys, "frozen", False): 63 | G14dir = os.path.dirname(os.path.realpath(sys.executable)) 64 | elif __file__: 65 | G14dir = os.path.dirname(os.path.realpath(__file__)) 66 | 67 | 68 | def loadConfig(): 69 | config = {} 70 | with open("data/config.yml") as file: 71 | config = yaml.load(file.read()) 72 | return config 73 | 74 | 75 | class RunCommandsTests(unittest.TestCase): 76 | def setUp(self): 77 | global config, windows_plans, active_plan_map, config, dpp_GUID, app_GUID, G14dir 78 | self.config = loadConfig() 79 | config = self.config 80 | get_power_plans() 81 | get_app_path() 82 | get_windows_plans() 83 | get_active_plan_map() 84 | self.main_cmds = RunCommands( 85 | self.config, 86 | G14dir=G14dir, 87 | app_GUID=app_GUID, 88 | dpp_GUID=dpp_GUID, 89 | notify=lambda x: print(x), 90 | windows_plans=windows_plans, 91 | active_plan_map=active_plan_map, 92 | ) 93 | 94 | def boost_test(self): 95 | startboost = self.main_cmds.get_boost() 96 | self.main_cmds.do_boost(2) 97 | boost = self.main_cmds.get_boost() 98 | self.assertEqual(2, int(boost, 16), "Boost not equal to boost that was set (2)") 99 | self.main_cmds.do_boost(4) 100 | boost = self.main_cmds.get_boost() 101 | self.assertEqual(4, int(boost, 16)) 102 | 103 | self.main_cmds.do_boost(0) 104 | boost = self.main_cmds.get_boost() 105 | self.assertEqual(0, int(boost, 16)) 106 | 107 | self.main_cmds.do_boost(int(startboost, 16)) 108 | 109 | def gamingthread_test(self): 110 | config = load_config("C:/Users/alexa/Documents/G14ControlR3") 111 | running = True 112 | global auto_power_switch 113 | auto_power_switch = True 114 | gaming = gaming_thread_impl(config, running) 115 | self.assertFalse(gaming.is_alive()) 116 | gaming.start() 117 | self.assertTrue(gaming.is_alive()) 118 | gaming.kill() 119 | while gaming.is_alive(): 120 | print("still alive...") 121 | time.sleep(1) 122 | 123 | 124 | def suite(): 125 | suite = unittest.TestSuite() 126 | suite.addTest(RunCommandsTests("boost_test")) 127 | return suite 128 | 129 | 130 | if __name__ == "__main__": 131 | runner = unittest.TextTestRunner() 132 | runner.run(suite()) 133 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Created by .ignore support plugin (hsz.mobi) 2 | ### Python template 3 | # Byte-compiled / optimized / DLL files 4 | __pycache__/ 5 | *.py[cod] 6 | *$py.class 7 | 8 | # C extensions 9 | *.so 10 | 11 | # Distribution / packaging 12 | .Python 13 | build/ 14 | develop-eggs/ 15 | dist/ 16 | downloads/ 17 | eggs/ 18 | .eggs/ 19 | lib/ 20 | lib64/ 21 | parts/ 22 | sdist/ 23 | var/ 24 | wheels/ 25 | pip-wheel-metadata/ 26 | share/python-wheels/ 27 | *.egg-info/ 28 | .installed.cfg 29 | *.egg 30 | MANIFEST 31 | 32 | # PyInstaller 33 | # Usually these files are written by a python script from a template 34 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 35 | *.manifest 36 | *.spec 37 | 38 | # Installer logs 39 | pip-log.txt 40 | pip-delete-this-directory.txt 41 | 42 | # Unit test / coverage reports 43 | htmlcov/ 44 | .tox/ 45 | .nox/ 46 | .coverage 47 | .coverage.* 48 | .cache 49 | nosetests.xml 50 | coverage.xml 51 | *.cover 52 | *.py,cover 53 | .hypothesis/ 54 | .pytest_cache/ 55 | cover/ 56 | 57 | # Translations 58 | *.mo 59 | *.pot 60 | 61 | # Django stuff: 62 | *.log 63 | local_settings.py 64 | db.sqlite3 65 | db.sqlite3-journal 66 | 67 | # Flask stuff: 68 | instance/ 69 | .webassets-cache 70 | 71 | # Scrapy stuff: 72 | .scrapy 73 | 74 | # Sphinx documentation 75 | docs/_build/ 76 | 77 | # PyBuilder 78 | .pybuilder/ 79 | target/ 80 | 81 | # Jupyter Notebook 82 | .ipynb_checkpoints 83 | 84 | # IPython 85 | profile_default/ 86 | ipython_config.py 87 | 88 | # pyenv 89 | # For a library or package, you might want to ignore these files since the code is 90 | # intended to run in multiple environments; otherwise, check them in: 91 | # .python-version 92 | 93 | # pipenv 94 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 95 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 96 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 97 | # install all needed dependencies. 98 | #Pipfile.lock 99 | 100 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow 101 | __pypackages__/ 102 | 103 | # Celery stuff 104 | celerybeat-schedule 105 | celerybeat.pid 106 | 107 | # SageMath parsed files 108 | *.sage.py 109 | 110 | # Environments 111 | .env 112 | .venv 113 | env/ 114 | venv/ 115 | ENV/ 116 | env.bak/ 117 | venv.bak/ 118 | g14env/ 119 | start38.bat 120 | start.bat 121 | 122 | # Spyder project settings 123 | .spyderproject 124 | .spyproject 125 | 126 | # Rope project settings 127 | .ropeproject 128 | 129 | # mkdocs documentation 130 | /site 131 | 132 | # mypy 133 | .mypy_cache/ 134 | .dmypy.json 135 | dmypy.json 136 | 137 | # Pyre type checker 138 | .pyre/ 139 | 140 | # pytype static type analyzer 141 | .pytype/ 142 | 143 | # Cython debug symbols 144 | cython_debug/ 145 | 146 | ### JetBrains template 147 | # Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio, WebStorm and Rider 148 | # Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 149 | 150 | # User-specific stuff 151 | .idea/**/workspace.xml 152 | .idea/**/tasks.xml 153 | .idea/**/usage.statistics.xml 154 | .idea/**/dictionaries 155 | .idea/**/shelf 156 | 157 | # Generated files 158 | .idea/**/contentModel.xml 159 | 160 | # Sensitive or high-churn files 161 | .idea/**/dataSources/ 162 | .idea/**/dataSources.ids 163 | .idea/**/dataSources.local.xml 164 | .idea/**/sqlDataSources.xml 165 | .idea/**/dynamic.xml 166 | .idea/**/uiDesigner.xml 167 | .idea/**/dbnavigator.xml 168 | 169 | # Gradle 170 | .idea/**/gradle.xml 171 | .idea/**/libraries 172 | 173 | # Gradle and Maven with auto-import 174 | # When using Gradle or Maven with auto-import, you should exclude module files, 175 | # since they will be recreated, and may cause churn. Uncomment if using 176 | # auto-import. 177 | # .idea/artifacts 178 | # .idea/compiler.xml 179 | # .idea/jarRepositories.xml 180 | # .idea/modules.xml 181 | # .idea/*.iml 182 | # .idea/modules 183 | # *.iml 184 | # *.ipr 185 | 186 | # CMake 187 | cmake-build-*/ 188 | 189 | # Mongo Explorer plugin 190 | .idea/**/mongoSettings.xml 191 | 192 | # File-based project format 193 | *.iws 194 | 195 | # IntelliJ 196 | out/ 197 | .idea 198 | 199 | # mpeltonen/sbt-idea plugin 200 | .idea_modules/ 201 | 202 | # JIRA plugin 203 | atlassian-ide-plugin.xml 204 | 205 | # Cursive Clojure plugin 206 | .idea/replstate.xml 207 | 208 | # Crashlytics plugin (for Android Studio and IntelliJ) 209 | com_crashlytics_export_strings.xml 210 | crashlytics.properties 211 | crashlytics-build.properties 212 | fabric.properties 213 | 214 | # Editor-based Rest Client 215 | .idea/httpRequests 216 | 217 | # Android studio 3.1+ serialized cache file 218 | .idea/caches/build_file_checksums.ser 219 | 220 | # VSCode 221 | *.code-workspace 222 | .vscode/settings.json 223 | .idea/G14Control.iml 224 | .idea/misc.xml 225 | .idea/ 226 | .vs/slnx.sqlite 227 | .vs/ 228 | random/ 229 | starto.ps1 230 | .vscode/launch.json 231 | config.DAT 232 | testing files/brightnesstest.py 233 | -------------------------------------------------------------------------------- /winusbpy/examples/winusbtest2.py: -------------------------------------------------------------------------------- 1 | """Test2: PL2303 serial port user-space driver using WINUSB high level api""" 2 | import time 3 | from winusbpy import * 4 | 5 | pl2303_vid = "2309" 6 | pl2303_pid = "0606" 7 | 8 | """ USB Setup Packets """ 9 | pkt1 = UsbSetupPacket(0xc0, 0x01, 0x8484, 0x00, 0x01) 10 | pkt2 = UsbSetupPacket(0x40, 0x01, 0x0404, 0x00, 0x00) 11 | pkt3 = UsbSetupPacket(0x40, 0x01, 0x0404, 0x00, 0x01) 12 | pkt4 = UsbSetupPacket(0xc0, 0x01, 0x8383, 0x00, 0x01) 13 | pkt5 = UsbSetupPacket(0xc0, 0x01, 0x8484, 0x00, 0x01) 14 | pkt6 = UsbSetupPacket(0x40, 0x01, 0x0404, 0x01, 0x00) 15 | pkt7 = UsbSetupPacket(0xc0, 0x01, 0x8484, 0x00, 0x01) 16 | pkt8 = UsbSetupPacket(0xc0, 0x01, 0x8383, 0x00, 0x01) 17 | pkt9 = UsbSetupPacket(0x40, 0x01, 0x0000, 0x01, 0x00) 18 | pkt10 = UsbSetupPacket(0x40, 0x01, 0x0001, 0x00, 0x00) 19 | pkt11 = UsbSetupPacket(0x40, 0x01, 0x0002, 0x44, 0x00) 20 | pkt12 = UsbSetupPacket(0x00, 0x01, 0x0001, 0x00, 0x00) 21 | 22 | pkt13 = UsbSetupPacket(0x21, 0x20, 0x0000, 0x00, 0x07) 23 | pkt14 = UsbSetupPacket(0x40, 0x01, 0x0505, 0x1311, 0x00) 24 | pkt15 = UsbSetupPacket(0x21, 0x22, 0x0001, 0x00, 0x00) 25 | pkt16 = UsbSetupPacket(0x40, 0x01, 0x0505, 0x1311, 0x00) 26 | pkt17 = UsbSetupPacket(0x21, 0x22, 0x0001, 0x00, 0x00) 27 | pkt18 = UsbSetupPacket(0xc0, 0x01, 0x0080, 0x00, 0x02) 28 | pkt19 = UsbSetupPacket(0xc0, 0x01, 0x0081, 0x00, 0x02) 29 | pkt20 = UsbSetupPacket(0x40, 0x01, 0x0000, 0x01, 0x00) 30 | 31 | """ USB Data """ 32 | hello = "Hello" 33 | header = b"\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x08\x00\x00\x01\x08\x01\x00\x00\x08\x01\x00\x00\x08\x01\x00\x00\x08\x01\x00\x00\x08\x01\x00\x00\x08\x01\x00\x00\x08\x01\x00\x00" 34 | tx1 = b"\x18" 35 | tx2 = b"\x08" 36 | tx3 = b"\x08" 37 | tx4 = b"\x14" 38 | tx5 = b"\x14" 39 | tx6 = b"\x22" 40 | tx7 = b"\x3e" 41 | tx8 = b"\x22" 42 | tx9 = b"\x77" 43 | tx10 = b"\x00" 44 | tx11 = b"\x00" 45 | tx12 = b"\x00" 46 | 47 | """ WinUsbPy """ 48 | 49 | api = WinUsbPy() 50 | result = api.list_usb_devices(deviceinterface=True, present=True) 51 | if result: 52 | if api.init_winusb_device(pl2303_vid, pl2303_pid): 53 | speed = api.query_device_info(query=1) 54 | if speed != -1: 55 | print("Device Speed: " + str(speed)) 56 | else: 57 | print("Device speed could not be obtained") 58 | 59 | interface_descriptor = api.query_interface_settings(0) 60 | 61 | if interface_descriptor != None: 62 | print("bLength: " + str(interface_descriptor.b_length)) 63 | print("bDescriptorType: " + str(interface_descriptor.b_descriptor_type)) 64 | print("bInterfaceNumber: " + str(interface_descriptor.b_interface_number)) 65 | print("bAlternateSetting: " + str(interface_descriptor.b_alternate_setting)) 66 | print("bNumEndpoints " + str(interface_descriptor.b_num_endpoints)) 67 | print("bInterfaceClass " + str(interface_descriptor.b_interface_class)) 68 | print("bInterfaceSubClass: " + str(interface_descriptor.b_interface_sub_class)) 69 | print("bInterfaceProtocol: " + str(interface_descriptor.b_interface_protocol)) 70 | print("iInterface: " + str(interface_descriptor.i_interface)) 71 | 72 | pipe_info_list = map(api.query_pipe, range(interface_descriptor.b_num_endpoints)) 73 | for item in pipe_info_list: 74 | print("PipeType: " + str(item.pipe_type)) 75 | print("PipeId: " + str(item.pipe_id)) 76 | print("MaximumPacketSize: " + str(item.maximum_packet_size)) 77 | print("Interval: " + str(item.interval)) 78 | 79 | """ 80 | buff = None -> Buffer length will be zero. No data expected 81 | """ 82 | api.control_transfer(pkt1, buff=[0]) 83 | api.control_transfer(pkt2, buff=None) 84 | api.control_transfer(pkt3, buff=[0]) 85 | api.control_transfer(pkt4, buff=[0]) 86 | api.control_transfer(pkt5, buff=[0]) 87 | api.control_transfer(pkt6, buff=None) 88 | api.control_transfer(pkt7, buff=[0]) 89 | api.control_transfer(pkt8, buff=[0]) 90 | api.control_transfer(pkt9, buff=None) 91 | api.control_transfer(pkt10, buff=None) 92 | api.control_transfer(pkt11, buff=None) 93 | api.control_transfer(pkt12, buff=None) 94 | api.control_transfer(pkt13, buff=[0xc0, 0x12, 0x00, 0x00, 0x00, 0x00, 0x08]) 95 | api.control_transfer(pkt14, buff=None) 96 | api.control_transfer(pkt15, buff=None) 97 | api.control_transfer(pkt16, buff=None) 98 | api.control_transfer(pkt17, buff=None) 99 | api.control_transfer(pkt18, buff=[0, 0]) 100 | api.control_transfer(pkt19, buff=[0, 0]) 101 | api.control_transfer(pkt20, buff=None) 102 | 103 | api.write(0x02, hello) 104 | time.sleep(0.045) 105 | api.write(0x02, header) 106 | time.sleep(0.380) 107 | api.write(0x02, tx1) 108 | time.sleep(0.380) 109 | api.write(0x02, tx2) 110 | time.sleep(0.380) 111 | api.write(0x02, tx3) 112 | time.sleep(0.380) 113 | api.write(0x02, tx4) 114 | time.sleep(0.380) 115 | api.write(0x02, tx5) 116 | time.sleep(0.380) 117 | api.write(0x02, tx6) 118 | time.sleep(0.380) 119 | api.write(0x02, tx7) 120 | time.sleep(0.380) 121 | api.write(0x02, tx8) 122 | time.sleep(0.380) 123 | api.write(0x02, tx9) 124 | time.sleep(0.380) 125 | api.write(0x02, tx10) 126 | time.sleep(0.380) 127 | api.write(0x02, tx11) 128 | time.sleep(0.380) 129 | api.write(0x02, tx12) 130 | 131 | 132 | else: 133 | print("PL2303 could not be init") 134 | 135 | else: 136 | print("No Usb devices connected") 137 | -------------------------------------------------------------------------------- /pywinusb/hid/tools.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Other helper functions. 4 | """ 5 | from __future__ import absolute_import 6 | 7 | from . import usage_pages, helpers, winapi 8 | from operator import attrgetter 9 | 10 | def write_documentation(self, output_file): 11 | "Issue documentation report on output_file file like object" 12 | if not self.is_opened(): 13 | raise helpers.HIDError("Device has to be opened to get documentation") 14 | #format 15 | class CompundVarDict(object): 16 | """Compound variables dictionary. 17 | Keys are strings mapping variables. 18 | If any string has a '.' on it, it means that is an 19 | object with an attribute. The attribute name will be 20 | used then as the returned item value. 21 | """ 22 | def __init__(self, parent): 23 | self.parent = parent 24 | def __getitem__(self, key): 25 | if '.' not in key: 26 | return self.parent[key] 27 | else: 28 | all_keys = key.split('.') 29 | curr_var = self.parent[all_keys[0]] 30 | for item in all_keys[1:]: 31 | new_var = getattr(curr_var, item) 32 | curr_var = new_var 33 | return new_var 34 | dev_vars = vars(self) 35 | dev_vars['main_usage_str'] = repr( 36 | usage_pages.HidUsage(self.hid_caps.usage_page, 37 | self.hid_caps.usage) ) 38 | output_file.write( """\n\ 39 | HID device documentation report 40 | =============================== 41 | 42 | Top Level Details 43 | ----------------- 44 | 45 | Manufacturer String: %(vendor_name)s 46 | Product Sting: %(product_name)s 47 | Serial Number: %(serial_number)s 48 | 49 | Vendor ID: 0x%(vendor_id)04x 50 | Product ID: 0x%(product_id)04x 51 | Version number: 0x%(version_number)04x 52 | 53 | Device Path: %(device_path)s 54 | Device Instance Id: %(instance_id)s 55 | Parent Instance Id: %(parent_instance_id)s 56 | 57 | Top level usage: Page=0x%(hid_caps.usage_page)04x, Usage=0x%(hid_caps.usage)02x 58 | Usage identification: %(main_usage_str)s 59 | Link collections: %(hid_caps.number_link_collection_nodes)d collection(s) 60 | 61 | Reports 62 | ------- 63 | 64 | Input Report 65 | ~~~~~~~~~~~~ 66 | Length: %(hid_caps.input_report_byte_length)d byte(s) 67 | Buttons: %(hid_caps.number_input_button_caps)d button(s) 68 | Values: %(hid_caps.number_input_value_caps)d value(s) 69 | 70 | Output Report 71 | ~~~~~~~~~~~~~ 72 | length: %(hid_caps.output_report_byte_length)d byte(s) 73 | Buttons: %(hid_caps.number_output_button_caps)d button(s) 74 | Values: %(hid_caps.number_output_value_caps)d value(s) 75 | 76 | Feature Report 77 | ~~~~~~~~~~~~~ 78 | Length: %(hid_caps.feature_report_byte_length)d byte(s) 79 | Buttons: %(hid_caps.number_feature_button_caps)d button(s) 80 | Values: %(hid_caps.number_feature_value_caps)d value(s) 81 | 82 | """ % CompundVarDict(dev_vars)) #better than vars()! 83 | #return 84 | # inspect caps 85 | for report_kind in [winapi.HidP_Input, 86 | winapi.HidP_Output, winapi.HidP_Feature]: 87 | all_usages = self.usages_storage.get(report_kind, []) 88 | if all_usages: 89 | output_file.write('*** %s Caps ***\n\n' % { 90 | winapi.HidP_Input : "Input", 91 | winapi.HidP_Output : "Output", 92 | winapi.HidP_Feature : "Feature" 93 | }[report_kind]) 94 | # normalize usages to allow sorting by usage or min range value 95 | for item in all_usages: 96 | if getattr(item, 'usage', None) != None: 97 | item.flat_id = item.usage 98 | elif getattr(item, 'usage_min', None) != None: 99 | item.flat_id = item.usage_min 100 | else: 101 | item.flat_id = None 102 | sorted(all_usages, key=attrgetter('usage_page', 'flat_id')) 103 | for usage_item in all_usages: 104 | # remove helper attribute 105 | del usage_item.flat_id 106 | 107 | all_items = usage_item.inspect() 108 | # sort first by 'usage_page'... 109 | usage_page = all_items["usage_page"] 110 | del all_items["usage_page"] 111 | if "usage" in all_items: 112 | usage = all_items["usage"] 113 | output_file.write(" Usage {0} ({0:#x}), "\ 114 | "Page {1:#x}\n".format(usage, usage_page)) 115 | output_file.write(" ({0})\n".format( 116 | repr(usage_pages.HidUsage(usage_page, usage))) ) 117 | del all_items["usage"] 118 | elif 'usage_min' in all_items: 119 | usage = (all_items["usage_min"], all_items["usage_max"]) 120 | output_file.write(" Usage Range {0}~{1} ({0:#x}~{1:#x})," 121 | " Page {2:#x} ({3})\n".format( 122 | usage[0], usage[1], usage_page, 123 | str(usage_pages.UsagePage(usage_page))) ) 124 | del all_items["usage_min"] 125 | del all_items["usage_max"] 126 | else: 127 | raise AttributeError("Expecting any usage id") 128 | attribs = list( all_items.keys() ) 129 | attribs.sort() 130 | for key in attribs: 131 | if 'usage' in key: 132 | output_file.write("{0}{1}: {2} ({2:#x})\n".format(' '*8, 133 | key, all_items[key])) 134 | else: 135 | output_file.write("{0}{1}: {2}\n".format(' '*8, 136 | key, all_items[key])) 137 | output_file.write('\n') 138 | 139 | -------------------------------------------------------------------------------- /pywinusb/hid/hid_pnp_mixin.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """PnP Window Mixing. 3 | 4 | Plug and Play nottifications are sent only to Window devices 5 | (devices that have a window handle. 6 | 7 | So regardless of the GUI toolkit used, the Mixin' classes 8 | expose here can be used. 9 | """ 10 | from __future__ import absolute_import 11 | from __future__ import print_function 12 | 13 | import ctypes 14 | from ctypes.wintypes import DWORD 15 | from . import wnd_hook_mixin 16 | from . import core 17 | from . import winapi 18 | 19 | WndProcHookMixin = wnd_hook_mixin.WndProcHookMixin 20 | #for PNP notifications 21 | class DevBroadcastDevInterface(ctypes.Structure): 22 | """DEV_BROADCAST_DEVICEINTERFACE ctypes structure wrapper""" 23 | _fields_ = [ 24 | # size of the members plus the actual length of the dbcc_name string 25 | ("dbcc_size", DWORD), 26 | ("dbcc_devicetype", DWORD), 27 | ("dbcc_reserved", DWORD), 28 | ("dbcc_classguid", winapi.GUID), 29 | ("dbcc_name", ctypes.c_wchar), 30 | ] 31 | def __init__(self): 32 | """Initialize the fields for device interface registration""" 33 | ctypes.Structure.__init__(self) 34 | self.dbcc_size = ctypes.sizeof(self) 35 | self.dbcc_devicetype = DBT_DEVTYP_DEVICEINTERFACE 36 | self.dbcc_classguid = winapi.GetHidGuid() 37 | 38 | #*********************************** 39 | # PnP definitions 40 | WM_DEVICECHANGE = 0x0219 41 | # PC docked or undocked 42 | DBT_CONFIGCHANGED = 0x0018 43 | # Device or piece of media has been inserted and is now available. 44 | DBT_DEVICEARRIVAL = 0x8000 45 | # Device or piece of media has been removed. 46 | DBT_DEVICEREMOVECOMPLETE = 0x8004 47 | 48 | RegisterDeviceNotification = ctypes.windll.user32.RegisterDeviceNotificationW 49 | RegisterDeviceNotification.restype = ctypes.wintypes.HANDLE 50 | RegisterDeviceNotification.argtypes = [ 51 | ctypes.wintypes.HANDLE, 52 | ctypes.wintypes.LPVOID, 53 | DWORD 54 | ] 55 | 56 | UnregisterDeviceNotification = ctypes.windll.user32.UnregisterDeviceNotification 57 | UnregisterDeviceNotification.restype = ctypes.wintypes.BOOL 58 | UnregisterDeviceNotification.argtypes = [ 59 | ctypes.wintypes.HANDLE, 60 | ] 61 | 62 | #dbcc_devicetype, device interface only used 63 | DBT_DEVTYP_DEVICEINTERFACE = 0x00000005 64 | DBT_DEVTYP_HANDLE = 0x00000006 65 | 66 | DEVICE_NOTIFY_WINDOW_HANDLE = 0x00000000 67 | DEVICE_NOTIFY_SERVICE_HANDLE = 0x00000001 68 | 69 | class HidPnPWindowMixin(WndProcHookMixin): 70 | """Base for receiving PnP notifications. 71 | Just call HidPnPWindowMixin.__init__(my_hwnd) being 72 | my_hwnd the OS window handle (most GUI toolkits 73 | allow to get the system window handle). 74 | """ 75 | def __init__(self, wnd_handle): 76 | """HidPnPWindowMixin initializer""" 77 | WndProcHookMixin.__init__(self, wnd_handle) 78 | self.__hid_hwnd = wnd_handle 79 | self.current_status = "unknown" 80 | #register hid notification msg handler 81 | self.__h_notify = self._register_hid_notification() 82 | if not self.__h_notify: 83 | raise core.HIDError("PnP notification setup failed!") 84 | else: 85 | WndProcHookMixin.add_msg_handler(self, WM_DEVICECHANGE, 86 | self._on_hid_pnp) 87 | # add capability to filter out windows messages 88 | WndProcHookMixin.hook_wnd_proc(self) 89 | 90 | def unhook_wnd_proc(self): 91 | "This function must be called to clean up system resources" 92 | WndProcHookMixin.unhook_wnd_proc(self) 93 | if self.__h_notify: 94 | self._unregister_hid_notification() #ignore result 95 | 96 | def _on_hid_pnp(self, w_param, l_param): 97 | "Process WM_DEVICECHANGE system messages" 98 | new_status = "unknown" 99 | if w_param == DBT_DEVICEARRIVAL: 100 | # hid device attached 101 | notify_obj = None 102 | if int(l_param): 103 | # Disable this error since pylint doesn't reconize 104 | # that from_address actually exists 105 | # pylint: disable=no-member 106 | notify_obj = DevBroadcastDevInterface.from_address(l_param) 107 | #confirm if the right message received 108 | if notify_obj and \ 109 | notify_obj.dbcc_devicetype == DBT_DEVTYP_DEVICEINTERFACE: 110 | #only connect if already disconnected 111 | new_status = "connected" 112 | elif w_param == DBT_DEVICEREMOVECOMPLETE: 113 | # hid device removed 114 | notify_obj = None 115 | if int(l_param): 116 | # Disable this error since pylint doesn't reconize 117 | # that from_address actually exists 118 | # pylint: disable=no-member 119 | notify_obj = DevBroadcastDevInterface.from_address(l_param) 120 | if notify_obj and \ 121 | notify_obj.dbcc_devicetype == DBT_DEVTYP_DEVICEINTERFACE: 122 | #only connect if already disconnected 123 | new_status = "disconnected" 124 | 125 | #verify if need to call event handler 126 | if new_status != "unknown" and new_status != self.current_status: 127 | self.current_status = new_status 128 | self.on_hid_pnp(self.current_status) 129 | # 130 | return True 131 | 132 | def _register_hid_notification(self): 133 | """Register HID notification events on any window (passed by window 134 | handler), returns a notification handler""" 135 | # create structure, self initialized 136 | notify_obj = DevBroadcastDevInterface() 137 | h_notify = RegisterDeviceNotification(self.__hid_hwnd, 138 | ctypes.byref(notify_obj), DEVICE_NOTIFY_WINDOW_HANDLE) 139 | # 140 | return int(h_notify) 141 | 142 | def _unregister_hid_notification(self): 143 | "Remove PnP notification handler" 144 | if not int(self.__h_notify): 145 | return #invalid 146 | result = UnregisterDeviceNotification(self.__h_notify) 147 | self.__h_notify = None 148 | return int(result) 149 | 150 | def on_hid_pnp(self, new_status): 151 | "'Virtual' like function to refresh update for connection status" 152 | print("HID:", new_status) 153 | return True 154 | 155 | -------------------------------------------------------------------------------- /pywinusb/hid/wnd_hook_mixin.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | """ 5 | This is a modification of the original WndProcHookMixin by Kevin Moore, 6 | modified to use ctypes only instead of pywin32, so it can be used with no 7 | additional dependencies in Python 2.5 8 | """ 9 | from __future__ import absolute_import 10 | from __future__ import print_function 11 | 12 | import platform 13 | import ctypes 14 | from ctypes.wintypes import HANDLE, LPVOID, LONG, LPARAM, WPARAM, UINT 15 | 16 | CallWindowProc = ctypes.windll.user32.CallWindowProcW 17 | if platform.architecture()[0].startswith('64'): 18 | CallWindowProc.restype = LONG 19 | CallWindowProc.argtypes = [ 20 | LPVOID, 21 | HANDLE, 22 | UINT, 23 | WPARAM, 24 | LPARAM, 25 | ] 26 | 27 | SetWindowLong = ctypes.windll.user32.SetWindowLongPtrW 28 | SetWindowLong.restype = LPVOID 29 | SetWindowLong.argtypes = [ 30 | HANDLE, 31 | ctypes.c_int, 32 | LPVOID, 33 | ] 34 | 35 | else: 36 | SetWindowLong = ctypes.windll.user32.SetWindowLongW 37 | 38 | GWL_WNDPROC = -4 39 | WM_DESTROY = 2 40 | 41 | # Create a type that will be used to cast a python callable to a c callback 42 | # function first arg is return type, the rest are the arguments 43 | if platform.architecture()[0].startswith('64'): 44 | WndProcType = ctypes.WINFUNCTYPE(LONG, HANDLE, UINT, WPARAM, LPARAM) 45 | else: 46 | WndProcType = ctypes.WINFUNCTYPE(ctypes.c_int, ctypes.c_long, ctypes.c_int, 47 | ctypes.c_int, ctypes.c_int) 48 | 49 | class WndProcHookMixin(object): 50 | """ 51 | This class can be mixed in with any window class in order to hook it's 52 | WndProc function. You supply a set of message handler functions with the 53 | function add_msg_handler. When the window receives that message, the 54 | specified handler function is invoked. If the handler explicitly returns 55 | False then the standard WindowProc will not be invoked with the message. 56 | You can really screw things up this way, so be careful. This is not the 57 | correct way to deal with standard windows messages in wxPython (i.e. button 58 | click, paint, etc) use the standard wxWindows method of binding events for 59 | that. This is really for capturing custom windows messages or windows 60 | messages that are outside of the wxWindows world. 61 | """ 62 | def __init__(self, wnd_handle): 63 | self.__msg_dict = {} 64 | ## We need to maintain a reference to the WndProcType wrapper 65 | ## because ctypes doesn't 66 | self.__local_wnd_proc_wrapped = None 67 | # keep window handle 68 | self.__local_win_handle = wnd_handle 69 | # empty class vars 70 | self.__local_wnd_proc_wrapped = None 71 | self.__old_wnd_proc = None 72 | 73 | def hook_wnd_proc(self): 74 | """Attach to OS Window message handler""" 75 | self.__local_wnd_proc_wrapped = WndProcType(self.local_wnd_proc) 76 | self.__old_wnd_proc = SetWindowLong(self.__local_win_handle, 77 | GWL_WNDPROC, 78 | self.__local_wnd_proc_wrapped) 79 | def unhook_wnd_proc(self): 80 | """Restore previous Window message handler""" 81 | if not self.__local_wnd_proc_wrapped: 82 | return 83 | SetWindowLong(self.__local_win_handle, 84 | GWL_WNDPROC, 85 | self.__old_wnd_proc) 86 | 87 | ## Allow the ctypes wrapper to be garbage collected 88 | self.__local_wnd_proc_wrapped = None 89 | 90 | def add_msg_handler(self, message_number, handler): 91 | """Add custom handler function to specific OS message number""" 92 | self.__msg_dict[message_number] = handler 93 | 94 | def local_wnd_proc(self, h_wnd, msg, w_param, l_param): 95 | """ 96 | Call the handler if one exists. 97 | """ 98 | # performance note: has_key is the fastest way to check for a key when 99 | # the key is unlikely to be found (which is the case here, since most 100 | # messages will not have handlers). This is called via a ctypes shim 101 | # for every single windows message so dispatch speed is important 102 | if msg in self.__msg_dict: 103 | # if the handler returns false, we terminate the message here Note 104 | # that we don't pass the hwnd or the message along Handlers should 105 | # be really, really careful about returning false here 106 | if self.__msg_dict[msg](w_param, l_param) == False: 107 | return 108 | 109 | # Restore the old WndProc on Destroy. 110 | if msg == WM_DESTROY: 111 | self.unhook_wnd_proc() 112 | 113 | return CallWindowProc(self.__old_wnd_proc, 114 | h_wnd, msg, w_param, l_param) 115 | 116 | # a simple example 117 | if __name__ == "__main__": 118 | def demo_module(): 119 | """Short demo showing filtering windows events""" 120 | try: 121 | import wx 122 | except: 123 | print("Need to install wxPython library") 124 | return 125 | 126 | class MyFrame(wx.Frame, WndProcHookMixin): 127 | """Demo frame""" 128 | def __init__(self, parent): 129 | frame_size = wx.Size(640, 480) 130 | wx.Frame.__init__(self, parent, -1, 131 | "Change my size and watch stdout", 132 | size = frame_size) 133 | # An error is reported here if wxPython isn't installed. 134 | # Supress this error for automated testing since pxPython 135 | # can't be installed through scripts since it is not in 136 | # PyPi. 137 | # pylint: disable=no-member 138 | WndProcHookMixin.__init__(self, self.GetHandle()) 139 | # this is for demo purposes only, use the wxPython method for 140 | # getting events on window size changes and other standard 141 | # windowing messages 142 | WM_SIZE = 5 143 | WndProcHookMixin.add_msg_handler(self, WM_SIZE, self.on_hooked_size) 144 | WndProcHookMixin.hook_wnd_proc(self) 145 | 146 | def on_hooked_size(self, w_param, l_param): 147 | """Custom WM_SIZE handler""" 148 | print("WM_SIZE [WPARAM:%i][LPARAM:%i]" % (w_param, l_param)) 149 | return True 150 | 151 | app = wx.App(False) 152 | frame = MyFrame(None) 153 | # An error is reported here if wxPython isn't installed. 154 | # Supress this error for automated testing since pxPython 155 | # can't be installed through scripts since it is not in 156 | # PyPi. 157 | # pylint: disable=no-member 158 | frame.Show() 159 | app.MainLoop() 160 | demo_module() 161 | -------------------------------------------------------------------------------- /G14Utils.py: -------------------------------------------------------------------------------- 1 | import ctypes 2 | import re 3 | 4 | from PIL import Image 5 | from pywinusb import hid 6 | import sys 7 | import winreg 8 | import os 9 | import subprocess as sp 10 | 11 | 12 | # # Adds G14Control.exe to the windows registry to start on boot/login 13 | # def registry_add(registry_key_loc, G14dir): 14 | # G14exe = "G14Control.exe" 15 | # G14dir = str(G14dir) 16 | # G14fileloc = os.path.join(G14dir, G14exe) 17 | # G14Key = winreg.OpenKey( 18 | # winreg.HKEY_CURRENT_USER, registry_key_loc, 0, winreg.KEY_SET_VALUE 19 | # ) 20 | # winreg.SetValueEx(G14Key, "G14Control", 1, winreg.REG_SZ, G14fileloc) 21 | # winreg.CloseKey(G14Key) 22 | 23 | 24 | # # Removes G14Control.exe from the windows registry 25 | # def registry_remove(registry_key_loc, G14dir): 26 | # G14dir = str(G14dir) 27 | # G14Key = winreg.OpenKey( 28 | # winreg.HKEY_CURRENT_USER, registry_key_loc, 0, winreg.KEY_ALL_ACCESS 29 | # ) 30 | # winreg.DeleteValue(G14Key, "G14Control") 31 | # winreg.CloseKey(G14Key) 32 | 33 | 34 | # Checks if G14Control registry entry exists already 35 | def registry_check(registry_key_loc, G14dir): 36 | G14exe = "G14Control.exe" 37 | G14dir = str(G14dir) 38 | G14fileloc = os.path.join(G14dir, G14exe) 39 | G14Key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, registry_key_loc) 40 | try: 41 | i = 0 42 | while 1: 43 | name, value, enumtype = winreg.EnumValue(G14Key, i) 44 | if name == "G14Control" and value == G14fileloc: 45 | return True 46 | i += 1 47 | except WindowsError: 48 | return False 49 | 50 | 51 | def get_app_path(): 52 | global G14dir 53 | G14dir = "" 54 | # Sets the path accordingly whether it is a python script or a frozen .exe 55 | if getattr(sys, "frozen", False): 56 | G14dir = os.path.dirname(os.path.realpath(sys.executable)) 57 | elif __file__: 58 | G14dir = os.path.dirname(os.path.realpath(__file__)) 59 | return G14dir 60 | 61 | 62 | def startup_checks(data): 63 | # Only enable auto_power_switch on boot if default power plans are enabled (not set to null): 64 | if ( 65 | data.default_ac_plan is not None 66 | and data.default_dc_plan is not None 67 | and data.config["power_switch_enabled"] is True 68 | ): 69 | data.auto_power_switch = True 70 | else: 71 | data.auto_power_switch = False 72 | # Adds registry entry if enabled in config, but not when in debug mode. 73 | # if not registry entry is already existing, 74 | # removes registry entry if registry exists but setting is disabled: 75 | # reg_run_enabled = registry_check(data.registry_key_loc, G14dir) 76 | 77 | # if ( 78 | # data.config["start_on_boot"] 79 | # and not data.config["debug"] 80 | # and not reg_run_enabled 81 | # ): 82 | # registry_add(data.registry_key_loc, G14dir) 83 | # if ( 84 | # not data.config["start_on_boot"] 85 | # and not data.config["debug"] 86 | # and reg_run_enabled 87 | # ): 88 | # registry_remove(data.registry_key_loc, data.G14dir) 89 | return data.auto_power_switch 90 | 91 | 92 | def change_target_brightness(target_guid, level): 93 | video = "SUB_VIDEEO" 94 | brightness_guid = "aded5e82-b909-4619-9949-f5d71dac0bcb" 95 | setacval = "/setacvalueindex" 96 | setdcval = "/setdcvalueindex" 97 | pcfg = "powercfg" 98 | sp.Popen([pcfg, setacval, target_guid, video, brightness_guid, level]) 99 | sp.Popen([pcfg, setdcval, target_guid, video, brightness_guid, level]) 100 | return 101 | 102 | 103 | def rog_keyset(config): 104 | if config["rog_key"] is not None: 105 | hid_filter = hid.HidDeviceFilter(vendor_id=0x0B05, product_id=0x1866) 106 | hid_device = hid_filter.get_devices() 107 | for i in hid_device: 108 | if str(i).find("col01"): 109 | device = i 110 | device.open() 111 | device.set_raw_data_handler(config, readData) 112 | return device 113 | 114 | 115 | def readData(config, data): 116 | if data[1] == 56: 117 | os.startfile(config["rog_key"]) 118 | return None 119 | 120 | 121 | def get_power_plans(config): 122 | dpp_GUID = "" 123 | app_GUID = "" 124 | all_plans = sp.check_output(["powercfg", "/l"]) 125 | for i in str(all_plans).split("\\n"): 126 | print(i) 127 | if i.find(config["default_power_plan"]) != -1: 128 | dpp_GUID = i.split(" ")[3] 129 | if i.find(config["alt_power_plan"]) != -1: 130 | app_GUID = i.split(" ")[3] 131 | return dpp_GUID, app_GUID 132 | 133 | 134 | def get_windows_plans(): 135 | windows_power_options = re.findall( 136 | r"([0-9a-f\-]{36}) *\((.*)\) *\*?\n", os.popen("powercfg /l").read() 137 | ) 138 | return windows_power_options 139 | 140 | 141 | def get_active_windows_plan(): 142 | plan_tuple = re.findall( 143 | r"([0-9a-f\-]{36}) *\((.*)\)", 144 | os.popen("powercfg /GETACTIVESCHEME").read(), 145 | ) 146 | plan = {plan_tuple[0][1]: plan_tuple[0][0]} 147 | return plan 148 | 149 | 150 | def get_active_plan_map(windows_plans, current_windows_plan): 151 | """ 152 | Cannot be run before @get_windows_plans() 153 | 154 | Prepares active windows plans map for icon_app menu *checked* statuses. 155 | """ 156 | active_plan_map = {x[1]: False for x in windows_plans} 157 | active_plan_map[current_windows_plan] = True 158 | return active_plan_map 159 | 160 | 161 | def get_windows_plan_map(windows_plans): 162 | windows_plan_map = {} 163 | windows_plan_map = {x[1]: x[0] for x in windows_plans} 164 | return windows_plan_map 165 | 166 | 167 | def is_admin(): 168 | try: 169 | # Returns true if the user launched the app as admin 170 | val = ctypes.windll.shell32.IsUserAnAdmin() 171 | print("is admin?:" + val) 172 | return ctypes.windll.shell32.IsUserAnAdmin() 173 | except Exception: 174 | return False 175 | 176 | 177 | def get_windows_theme(): 178 | # By default, this is the local registry 179 | key = winreg.ConnectRegistry(None, winreg.HKEY_CURRENT_USER) 180 | # Let's open the subkey 181 | sub_key = winreg.OpenKey( 182 | key, r"Software\Microsoft\Windows\CurrentVersion\Themes\Personalize" 183 | ) 184 | # Taskbar (where icon is displayed) uses the 'System' light theme key. Index 0 is the value, index 1 is the type of key 185 | value = winreg.QueryValueEx(sub_key, "SystemUsesLightTheme")[0] 186 | sub_key.Close() 187 | return value # 1 for light theme, 0 for dark theme 188 | 189 | 190 | def get_g14plan(current, config): 191 | plans = config["plans"] 192 | for p in plans: 193 | if p["name"] == current: 194 | return p 195 | 196 | 197 | def create_icon(config): 198 | if ( 199 | get_windows_theme() == 0 200 | ): # We will create the icon based on current windows theme 201 | return Image.open(os.path.join(config["temp_dir"], "icon_light.png")) 202 | else: 203 | return Image.open(os.path.join(config["temp_dir"], "icon_dark.png")) 204 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # NOTE: 2 | 3 | This is an upstream fork of https://github.com/thesacredmoocow/g14control-r2 which is an upstream fork of https://github.com/CappyT/g14control that has features and bug fixes that are not yet deemed stable for the official release, but that I have tested and are stable enough for my day-to-day use. There will be new EXEs bundled in the [releases](https://github.com/aredden/G14ControlR3/releases) section that will be released between official releases by me. For those that want the bleeding edge updates/testing branches (but testing and working). 4 | 5 | Some people have had issues with missing dependencies (errors saying they are missing MSVCP120.dll). This can be solved by installing Microsoft Visual C++ Redistributable 2013, version x86 and x64. Those can be installed here: https://www.microsoft.com/en-us/download/details.aspx?id=40784 6 | 7 | ## G14ControlR3 8 | 9 | ## A simple tray app to control Asus Zephyrus G14 Power options 10 | 11 | #### Background: 12 | 13 | If you are a user like me, you hate using a bunch of different apps to control all the power saving options of your laptop (sometimes even hidden in the registry) and prefer a simple, handy, tray app utility. The focus of this application is just that! 14 | It does combine all the option offered from other utilities into one, single, configurable TrayApp. 15 | 16 | #### What does it do? 17 | 18 | G14Control (you can even rename it) can control the current ASUS Power plan, Fan curve, Processor Boost Mode, Processor TDP, dGPU Activation and Screen refresh rate to your needs with a simple right click on the Windows taskbar. You can configure all the presets (and add new ones too) from the `config.yml` file via directly editing it during runtime using the `Edit config` button (which opens config.yml) and then pressing the `Reload config` button, or with your editor of choice from explorer. 19 | 20 | #### What about Linux? 21 | 22 | While is possible to port this app to Linux, at the moment is engineered to work only on Windows. 23 | 24 | ### Installation 25 | 26 | Before boost changes work, you must update the registry to allow modifications of the power option _`proccessor performance boost mode`_. Information for this can be found here: [reddit link](https://www.reddit.com/r/ZephyrusG14/comments/gho535/important_update_to_properly_disable_boosting/) 27 | 28 | Download the latest release zip from GitHub: https://github.com/aredden/G14ControlR3/releases 29 | 30 | Extract it to C:\G14Control 31 | 32 | Edit the config.yml with text editor as needed (see configuring below) 33 | 34 | ### Configuring 35 | 36 | All done in config.yaml within the root folder of the program. The program must be restarted for any changes to the config.yaml to take effect. 37 | 38 | #### `default_power_plan` and `alt_power_plan` MUST BE SET IN ORDER FOR POWER PLAN SETTINGS TO WORK (BOOST, dGPU toggling) 39 | 40 | By default, the default power plan is "Balanced" and the alt_power plan is "High performance". You need to set these to the names of your **windows** power plans, ie GameTurbo, Battery saver, etc. 41 | 42 | `app_name:` can be customized, this is what the hover text displays over the icon and the windows notification title 43 | 44 | `start_on_boot` Set this to `true` or `false`. Note this will create a Windows Registry entry to enable starting on login. Must have files extracted to a permanent location as above. Note: This will popup an administrator UAC prompt the first time you login after each boot. Setting back to false will remove registry key. 45 | 46 | Alternatively to make it run on boot WITHOUT UAC prompt, you will have to create a windows task, please see [our Autostart instructions](AUTOSTART.md) 47 | 48 | `default_starting_plan` set plan name you want on boot or on restart of the program 49 | 50 | `default_ac_plan` This plan name will automatically enable when AC adapter plugged in (set both default_ac_plan and default_dc_plan to `null` to disable this feature) 51 | 52 | `default_dc_plan` This plan name will automatically enable when on battery power (set both default_ac_plan and default_dc_plan to `null` to disable this feature) 53 | 54 | `default_gaming_plan` Enable this if you want the program to auto-switch plans based on games (or any program really) running. It will automatically switch to the plan specified here when the program is launched, and automatically switch back to the previous plan once it has closed. Set to `null` to disable. 55 | 56 | - WARNING: this may be more resource intensive as it polls running processes on your computer every 10 seconds. However I noticed little difference, and almost no score change on Heaven Benchmark (FPS +/- 2). 57 | 58 | `default_gaming_plan_games` This will be a list of exe's that you want to detect. Please check the exact name of the exe. For example, Steam is SteamService.exe. Example list: ["7zFM.exe", "notepad++.exe", "SteamService.exe"] 59 | 60 | `power_check_enabled` This will enable or disable the power switching for both gaming and battery. Possible values are `true` or `false`. 61 | 62 | ##### Notes on using Auto Power Switching: 63 | 64 | - Only available if `default_ac_plan` and `default_dc_plan` are set in config (set to `null` to disable) 65 | - Manually changing your plan thru the icon menu will DISABLE auto power switching. 66 | - To re-enable, click the "Re-Enable Auto Power Switching" option in the icon menu. 67 | 68 | ##### Configure plans 69 | 70 | _Removed the `plan: Armory Crate Plan` functionality because of issues with atrofac._ 71 | 72 | Under Plans, you can configure as many or few plans as you want. A plan includes: 73 | 74 | ``` 75 | - name: 76 | This is where you will enter the name you want to be displayed for that plan 77 | plan: 78 | --DEPRECIATED BUT STILL SHOWS IN CONFIG.YML-- 79 | Name of the ROG Armory plan you want it set on (`silent` or `windows` or `performance` or `turbo`). 80 | cpu_curve: 81 | An array of `temps_in_deg_C:fanspeed_percent` for custom fan curve such as "30c:0%,40c:0%,50c:0%,60c:0%,70c:34%,80c:51%,90c:61%,100c:61%". Otherwise use `null` for default 82 | gpu_curve: 83 | An array of `temps_in_deg_C:fanspeed_percent` for custom fan curve such as "30c:0%,40c:0%,50c:0%,60c:0%,70c:34%,80c:51%,90c:61%,100c:61%". Otherwise use `null` for default 84 | cpu_tdp: 85 | The tdp you want for the CPU expressed in mW, use `null` for default or numeric (45000 = 45W) 86 | boost: 87 | Whether you want the CPU to boost above it's 3.0Ghz base clock speed. 0 for no boost, 2 for aggressive boost, 4 for efficient aggressive boost (reccommended) 88 | dgpu_enabled: 89 | Whether you want the dedicated NVIDIA GPU enabled (uses more power, need for graphics/games), `true`, `false` 90 | screen_hz: 91 | The refresh rate of the screen. Can be 60 (numeric) or 120 (numeric) (for supported models) or null for default refresh rate of your screen 92 | ``` 93 | 94 | The config.yaml has many examples of plans included by default. Modify at will. 95 | 96 | ### Important Note about ASUS ROG Armory Crate 97 | 98 | The ASUS ROG Armory Crate program will automatically change plans on wake, AC unplug, AC plugin. This will override G14's plan setting, but It is important to keep Armory Crate for the power profiles so that it's easier to fix fan bugs from occuring due to atrofac-cli.exe. 99 | 100 | ### Downloads: 101 | 102 | Check the release tab! 103 | 104 | ### How to build: 105 | 106 | Make sure 32-bit python 3.8.x and pip are installed. Then (as admin, in the source folder) run install.bat 107 | 108 | The install directory is C:\G14Control, go there and modify the config.yml as needed. ensure that windows has at least two power plans. 109 | the default power plan will be selected 99% of the time, but will flip to the alternate plan for a bit to force a refresh of the power plan settings 110 | 111 | run G14control\G14Control.exe 112 | 113 | Optionally: create a task in task manager to have it start by itself 114 | 115 | ### Disclaimer 116 | 117 | Please note that this is an ALPHA version of this software, which is still undergoing testing and development. The software and all content found on GitHub related to it are provided “as is”. We do not give any warranties, whether express or implied, as to the safety, reliability, suitability or usability of the software or any of its content. 118 | 119 | We will not be held liable for any loss, whether such loss is direct, indirect, special or consequential, suffered by any party as a result of their use of the software or content. Any use of the software or scripts provided here is done at the user’s own risk and the user will be solely responsible for any damage to any computer system or loss of data that results from such activities. 120 | 121 | Should you encounter any bugs, glitches, lack of functionality or other problems with the software, please let us know in GitHub so we can look into addressing it. 122 | 123 | ### Contribute: 124 | 125 | You are very free to contribute with your code. I kinda suck at coding so any help is appreciated. Just submit a pull request, I will merge it or discuss it as soon as possible. 126 | 127 | ### TODO: 128 | 129 | - Automatic config generation 130 | - ~~Dynamic Menu generation based on configured profiles~~ Implemented 131 | - ~~atrofac commands integration~~ Implemented 132 | - ~~ryzenadj command integration~~ Implemented 133 | - ~~Parallel notification spawning (right now when notification is displayed the whole app locks until the notification disappears)~~ Implemented 134 | - Different options for AC/DC modes 135 | - Logging 136 | - Better binary storage 137 | - Better UI (?) 138 | - Better code comments 139 | - .... you tell us! 140 | - mode switching upon launching games 141 | 142 | ### Contributors: 143 | 144 | - https://github.com/FlyGoat/RyzenAdj (adjusting tdp) 145 | - https://github.com/cronosun/atrofac (fan profiles) 146 | - https://github.com/dedo1911 147 | - https://github.com/carverhaines (updated branch of original G14Control) 148 | - https://tools.taubenkorb.at/change-screen-resolution/ (change refresh rate) 149 | - https://github.com/thesacredmoocow/g14control-r2 (Source this version was built on top of) 150 | -------------------------------------------------------------------------------- /winusbpy/winusbutils.py: -------------------------------------------------------------------------------- 1 | from ctypes import * 2 | from ctypes.wintypes import * 3 | from .winusbclasses import UsbSetupPacket, Overlapped, UsbInterfaceDescriptor, LpSecurityAttributes, GUID, \ 4 | SpDevinfoData, SpDeviceInterfaceData, SpDeviceInterfaceDetailData, PipeInfo 5 | 6 | WinUsb_Initialize = "WinUsb_Initialize" 7 | WinUsb_ControlTransfer = "WinUsb_ControlTransfer" 8 | WinUsb_GetDescriptor = "WinUsb_GetDescriptor" 9 | WinUsb_GetOverlappedResult = "WinUsb_GetOverlappedResult" 10 | WinUsb_SetPipePolicy = "WinUsb_SetPipePolicy" 11 | WinUsb_ReadPipe = "WinUsb_ReadPipe" 12 | WinUsb_WritePipe = "WinUsb_WritePipe" 13 | WinUsb_FlushPipe = "WinUsb_FlushPipe" 14 | WinUsb_Free = "WinUsb_Free" 15 | WinUsb_QueryDeviceInformation = "WinUsb_QueryDeviceInformation" 16 | WinUsb_QueryInterfaceSettings = "WinUsb_QueryInterfaceSettings" 17 | WinUsb_GetAssociatedInterface = "WinUsb_GetAssociatedInterface" 18 | WinUsb_QueryPipe = "WinUsb_QueryPipe" 19 | # WinUsb_ControlTransfer = "WinUsb_ControlTransfer" 20 | # WinUsb_QueryPipe = "WinUsb_QueryPipe" 21 | Close_Handle = "CloseHandle" 22 | CreateFile = "CreateFileW" 23 | ReadFile = "ReadFile" 24 | CancelIo = "CancelIo" 25 | WriteFile = "WriteFile" 26 | SetEvent = "SetEvent" 27 | WaitForSingleObject = "WaitForSingleObject" 28 | GetLastError = "GetLastError" 29 | SetupDiGetClassDevs = "SetupDiGetClassDevs" 30 | SetupDiEnumDeviceInterfaces = "SetupDiEnumDeviceInterfaces" 31 | SetupDiGetDeviceInterfaceDetail = "SetupDiGetDeviceInterfaceDetail" 32 | SetupDiGetDeviceRegistryProperty = "SetupDiGetDeviceRegistryProperty" 33 | SetupDiEnumDeviceInfo = "SetupDiEnumDeviceInfo" 34 | 35 | SPDRP_HARDWAREID = 1 36 | SPDRP_FRIENDLYNAME = 12 37 | SPDRP_LOCATION_PATHS = 35 38 | SPDRP_MFG = 11 39 | 40 | 41 | def get_winusb_functions(windll): 42 | """ Functions availabe from WinUsb dll and their types""" 43 | winusb_dict = {} 44 | winusb_functions = {} 45 | winusb_restypes = {} 46 | winusb_argtypes = {} 47 | 48 | # BOOL __stdcall WinUsb_Initialize( _In_ HANDLE DeviceHandle,_Out_ PWINUSB_INTERFACE_HANDLE InterfaceHandle); 49 | winusb_functions[WinUsb_Initialize] = windll.WinUsb_Initialize 50 | winusb_restypes[WinUsb_Initialize] = BOOL 51 | winusb_argtypes[WinUsb_Initialize] = [HANDLE, POINTER(c_void_p)] 52 | 53 | # BOOL __stdcall WinUsb_ControlTransfer(_In_ WINUSB_INTERFACE_HANDLE InterfaceHandle,_In_ WINUSB_SETUP_PACKET SetupPacket, _Out_ PUCHAR Buffer,_In_ ULONG BufferLength,_Out_opt_ PULONG LengthTransferred,_In_opt_ LPOVERLAPPED Overlapped); 54 | winusb_functions[WinUsb_ControlTransfer] = windll.WinUsb_ControlTransfer 55 | # winusb_restypes[WinUsb_ControlTransfer] = BOOL 56 | # winusb_argtypes[WinUsb_ControlTransfer] = [c_void_p, UsbSetupPacket, POINTER(c_ubyte), c_ulong, POINTER(c_ulong), LpOverlapped] 57 | 58 | # BOOL __stdcall WinUsb_GetDescriptor(_In_ WINUSB_INTERFACE_HANDLE InterfaceHandle,_In_ UCHAR DescriptorType,_In_ UCHAR Index,_In_ USHORT LanguageID,_Out_ PUCHAR Buffer,_In_ ULONG BufferLength,_Out_ PULONG LengthTransferred); 59 | winusb_functions[WinUsb_GetDescriptor] = windll.WinUsb_GetDescriptor 60 | winusb_restypes[WinUsb_GetDescriptor] = BOOL 61 | winusb_argtypes[WinUsb_GetDescriptor] = [c_void_p, c_ubyte, c_ubyte, c_ushort, POINTER(c_ubyte), c_ulong, POINTER(c_ulong)] 62 | 63 | # BOOL __stdcall WinUsb_GetOverlappedResult(_In_ WINUSB_INTERFACE_HANDLE InterfaceHandle,_In_ LPOVERLAPPED lpOverlapped,_Out_ LPDWORD lpNumberOfBytesTransferred,_In_ BOOL bWait); 64 | winusb_functions[WinUsb_GetOverlappedResult] = windll.WinUsb_GetOverlappedResult 65 | winusb_restypes[WinUsb_GetOverlappedResult] = BOOL 66 | # winusb_argtypes[WinUsb_GetOverlappedResult] = [] 67 | 68 | # BOOL __stdcall WinUsb_ReadPipe( _In_ WINUSB_INTERFACE_HANDLE InterfaceHandle,_In_ UCHAR PipeID,_Out_ PUCHAR Buffer,_In_ ULONG BufferLength,_Out_opt_ PULONG LengthTransferred,_In_opt_ LPOVERLAPPED Overlapped); 69 | winusb_functions[WinUsb_ReadPipe] = windll.WinUsb_ReadPipe 70 | # winusb_restypes[WinUsb_ReadPipe] = BOOL 71 | # winusb_argtypes[WinUsb_ReadPipe] = [c_void_p, c_ubyte, POINTER(c_ubyte), c_ulong, POINTER(c_ulong), LpOverlapped] 72 | 73 | # BOOL __stdcall WinUsb_ReadPipe( _In_ WINUSB_INTERFACE_HANDLE InterfaceHandle,_In_ UCHAR PipeID,_Out_ PUCHAR Buffer,_In_ ULONG BufferLength,_Out_opt_ PULONG LengthTransferred,_In_opt_ LPOVERLAPPED Overlapped); 74 | winusb_functions[WinUsb_SetPipePolicy] = windll.WinUsb_SetPipePolicy 75 | winusb_restypes[WinUsb_SetPipePolicy] = BOOL 76 | winusb_argtypes[WinUsb_SetPipePolicy] = [c_void_p, c_ubyte, c_ulong, c_ulong, c_void_p] 77 | 78 | # BOOL __stdcall WinUsb_WritePipe(_In_ WINUSB_INTERFACE_HANDLE InterfaceHandle,_In_ UCHAR PipeID,_In_ PUCHAR Buffer,_In_ ULONG BufferLength,_Out_opt_ PULONG LengthTransferred,_In_opt_ LPOVERLAPPED Overlapped); 79 | winusb_functions[WinUsb_WritePipe] = windll.WinUsb_WritePipe 80 | # winusb_restypes[WinUsb_WritePipe] = BOOL 81 | # winusb_argtypes[WinUsb_WritePipe] = [c_void_p, c_ubyte, POINTER(c_ubyte), c_ulong, POINTER(c_ulong), LpOverlapped] 82 | 83 | # BOOL __stdcall WinUsb_FlushPipe(_In_ WINUSB_INTERFACE_HANDLE InterfaceHandle); 84 | winusb_functions[WinUsb_FlushPipe] = windll.WinUsb_FlushPipe 85 | winusb_restypes[WinUsb_FlushPipe] = BOOL 86 | winusb_argtypes[WinUsb_FlushPipe] = [c_void_p, c_ubyte] 87 | 88 | # BOOL __stdcall WinUsb_Free(_In_ WINUSB_INTERFACE_HANDLE InterfaceHandle); 89 | winusb_functions[WinUsb_Free] = windll.WinUsb_Free 90 | winusb_restypes[WinUsb_Free] = BOOL 91 | winusb_argtypes[WinUsb_Free] = [c_void_p] 92 | 93 | # BOOL __stdcall WinUsb_QueryDeviceInformation(_In_ WINUSB_INTERFACE_HANDLE InterfaceHandle,_In_ ULONG InformationType,_Inout_ PULONG BufferLength,_Out_ PVOID Buffer); 94 | winusb_functions[WinUsb_QueryDeviceInformation] = windll.WinUsb_QueryDeviceInformation 95 | winusb_restypes[WinUsb_QueryDeviceInformation] = BOOL 96 | winusb_argtypes[WinUsb_QueryDeviceInformation] = [c_void_p, c_ulong, POINTER(c_ulong), c_void_p] 97 | 98 | # BOOL __stdcall WinUsb_QueryInterfaceSettings(_In_ WINUSB_INTERFACE_HANDLE InterfaceHandle,_In_ UCHAR AlternateSettingNumber,_Out_ PUSB_INTERFACE_DESCRIPTOR UsbAltInterfaceDescriptor); 99 | winusb_functions[WinUsb_QueryInterfaceSettings] = windll.WinUsb_QueryInterfaceSettings 100 | winusb_restypes[WinUsb_QueryInterfaceSettings] = BOOL 101 | winusb_argtypes[WinUsb_QueryInterfaceSettings] = [c_void_p, c_ubyte, POINTER(UsbInterfaceDescriptor)] 102 | 103 | winusb_functions[WinUsb_QueryPipe] = windll.WinUsb_QueryPipe 104 | winusb_restypes[WinUsb_QueryPipe] = BOOL 105 | winusb_argtypes[WinUsb_QueryPipe] = [c_void_p, c_ubyte, c_ubyte, POINTER(PipeInfo)] 106 | 107 | winusb_functions[WinUsb_GetAssociatedInterface] = windll.WinUsb_GetAssociatedInterface 108 | winusb_restypes[WinUsb_GetAssociatedInterface] = BOOL 109 | winusb_argtypes[WinUsb_GetAssociatedInterface] = [c_void_p, c_ubyte, POINTER(c_void_p)] 110 | 111 | winusb_dict["functions"] = winusb_functions 112 | winusb_dict["restypes"] = winusb_restypes 113 | winusb_dict["argtypes"] = winusb_argtypes 114 | return winusb_dict 115 | 116 | 117 | def get_kernel32_functions(kernel32): 118 | kernel32_dict = {} 119 | kernel32_functions = {} 120 | kernel32_restypes = {} 121 | kernel32_argtypes = {} 122 | 123 | # BOOL WINAPI CloseHandle(_In_ HANDLE hObject); 124 | kernel32_functions[Close_Handle] = kernel32.CloseHandle 125 | kernel32_restypes[Close_Handle] = BOOL 126 | kernel32_argtypes[Close_Handle] = [HANDLE] 127 | 128 | # BOOL WINAPI ReadFile(_In_ HANDLE hFile,_Out_ LPVOID lpBuffer,_In_ DWORD nNumberOfBytesToRead,_Out_opt_ LPDWORD lpNumberOfBytesRead,_Inout_opt_ LPOVERLAPPED lpOverlapped); 129 | kernel32_functions[ReadFile] = kernel32.ReadFile 130 | kernel32_restypes[ReadFile] = BOOL 131 | kernel32_argtypes[ReadFile] = [HANDLE, c_void_p, DWORD, POINTER(DWORD), POINTER(Overlapped)] 132 | 133 | # BOOL WINAPI CancelIo(_In_ HANDLE hFile); 134 | kernel32_functions[CancelIo] = kernel32.CancelIo 135 | kernel32_restypes[CancelIo] = BOOL 136 | kernel32_argtypes[CancelIo] = [HANDLE] 137 | 138 | # BOOL WINAPI WriteFile(_In_ HANDLE hFile,_In_ LPCVOID lpBuffer,_In_ DWORD nNumberOfBytesToWrite,_Out_opt_ LPDWORD lpNumberOfBytesWritten,_Inout_opt_ LPOVERLAPPED lpOverlapped); 139 | kernel32_functions[WriteFile] = kernel32.WriteFile 140 | kernel32_restypes[WriteFile] = BOOL 141 | kernel32_argtypes[WriteFile] = [HANDLE, c_void_p, DWORD, POINTER(DWORD), POINTER(Overlapped)] 142 | 143 | # BOOL WINAPI SetEvent(_In_ HANDLE hEvent); 144 | kernel32_functions[SetEvent] = kernel32.SetEvent 145 | kernel32_restypes[SetEvent] = BOOL 146 | kernel32_argtypes[SetEvent] = [HANDLE] 147 | 148 | # DWORD WINAPI WaitForSingleObject(_In_ HANDLE hHandle, _In_ DWORD dwMilliseconds); 149 | kernel32_functions[WaitForSingleObject] = kernel32.WaitForSingleObject 150 | kernel32_restypes[WaitForSingleObject] = DWORD 151 | kernel32_argtypes[WaitForSingleObject] = [HANDLE, DWORD] 152 | 153 | # HANDLE WINAPI CreateFile(_In_ LPCTSTR lpFileName,_In_ DWORD dwDesiredAccess,_In_ DWORD dwShareMode,_In_opt_ LPSECURITY_ATTRIBUTES lpSecurityAttributes,_In_ DWORD dwCreationDisposition,_In_ DWORD dwFlagsAndAttributes,_In_opt_ HANDLE hTemplateFile); 154 | kernel32_functions[CreateFile] = kernel32.CreateFileW 155 | kernel32_restypes[CreateFile] = HANDLE 156 | 157 | # DWORD WINAPI GetLastError(void) 158 | kernel32_functions[GetLastError] = kernel32.GetLastError 159 | kernel32_restypes[GetLastError] = DWORD 160 | kernel32_argtypes[GetLastError] = [] 161 | 162 | kernel32_dict["functions"] = kernel32_functions 163 | kernel32_dict["restypes"] = kernel32_restypes 164 | kernel32_dict["argtypes"] = kernel32_argtypes 165 | return kernel32_dict 166 | 167 | 168 | def get_setupapi_functions(setupapi): 169 | setupapi_dict = {} 170 | setupapi_functions = {} 171 | setupapi_restypes = {} 172 | setupapi_argtypes = {} 173 | 174 | # HDEVINFO SetupDiGetClassDevs(_In_opt_ const GUID *ClassGuid,_In_opt_ PCTSTR Enumerator,_In_opt_ HWND hwndParent,_In_ DWORD Flags); 175 | setupapi_functions[SetupDiGetClassDevs] = setupapi.SetupDiGetClassDevsW 176 | setupapi_restypes[SetupDiGetClassDevs] = HANDLE 177 | setupapi_argtypes[SetupDiGetClassDevs] = [POINTER(GUID), c_wchar_p, HANDLE, DWORD] 178 | 179 | # BOOL SetupDiEnumDeviceInterfaces(_In_ HDEVINFO DeviceInfoSet,_In_opt_ PSP_DEVINFO_DATA DeviceInfoData,_In_ const GUID *InterfaceClassGuid,_In_ DWORD MemberIndex,_Out_ PSP_DEVICE_INTERFACE_DATA DeviceInterfaceData); 180 | setupapi_functions[SetupDiEnumDeviceInterfaces] = setupapi.SetupDiEnumDeviceInterfaces 181 | setupapi_restypes[SetupDiEnumDeviceInterfaces] = BOOL 182 | setupapi_argtypes[SetupDiEnumDeviceInterfaces] = [c_void_p, POINTER(SpDevinfoData), POINTER(GUID), DWORD, 183 | POINTER(SpDeviceInterfaceData)] 184 | 185 | # BOOL SetupDiGetDeviceInterfaceDetail(_In_ HDEVINFO DeviceInfoSet,_In_ PSP_DEVICE_INTERFACE_DATA DeviceInterfaceData,_Out_opt_ PSP_DEVICE_INTERFACE_DETAIL_DATA DeviceInterfaceDetailData,_In_ DWORD DeviceInterfaceDetailDataSize,_Out_opt_ PDWORD RequiredSize,_Out_opt_ PSP_DEVINFO_DATA DeviceInfoData); 186 | setupapi_functions[SetupDiGetDeviceInterfaceDetail] = setupapi.SetupDiGetDeviceInterfaceDetailW 187 | setupapi_restypes[SetupDiGetDeviceInterfaceDetail] = BOOL 188 | setupapi_argtypes[SetupDiGetDeviceInterfaceDetail] = [c_void_p, POINTER(SpDeviceInterfaceData), 189 | POINTER(SpDeviceInterfaceDetailData), DWORD, POINTER(DWORD), 190 | POINTER(SpDevinfoData)] 191 | 192 | # BOOL SetupDiGetDeviceInterfaceDetail(_In_ HDEVINFO DeviceInfoSet,_In_ PSP_DEVICE_INTERFACE_DATA DeviceInterfaceData,_Out_opt_ PSP_DEVICE_INTERFACE_DETAIL_DATA DeviceInterfaceDetailData,_In_ DWORD DeviceInterfaceDetailDataSize,_Out_opt_ PDWORD RequiredSize,_Out_opt_ PSP_DEVINFO_DATA DeviceInfoData); 193 | setupapi_functions[SetupDiGetDeviceRegistryProperty] = setupapi.SetupDiGetDeviceRegistryPropertyW 194 | setupapi_restypes[SetupDiGetDeviceRegistryProperty] = BOOL 195 | setupapi_argtypes[SetupDiGetDeviceRegistryProperty] = [c_void_p, POINTER(SpDevinfoData), 196 | DWORD, POINTER(DWORD), 197 | c_void_p, DWORD, POINTER(DWORD)] 198 | # [HDEVINFO, PSP_DEVINFO_DATA, DWORD, PDWORD, PBYTE, DWORD, PDWORD] 199 | 200 | # BOOL SetupDiEnumDeviceInfo(HDEVINFO DeviceInfoSet, DWORD MemberIndex, PSP_DEVINFO_DATA DeviceInfoData); 201 | setupapi_functions[SetupDiEnumDeviceInfo] = setupapi.SetupDiEnumDeviceInfo 202 | setupapi_restypes[SetupDiEnumDeviceInfo] = BOOL 203 | setupapi_argtypes[SetupDiEnumDeviceInfo] = [c_void_p, DWORD, POINTER(SpDevinfoData)] 204 | 205 | setupapi_dict["functions"] = setupapi_functions 206 | setupapi_dict["restypes"] = setupapi_restypes 207 | setupapi_dict["argtypes"] = setupapi_argtypes 208 | return setupapi_dict 209 | 210 | 211 | def is_device(vid, pid, path, name=None): 212 | #print ("name: ", name) 213 | if name and name.lower() == path.lower(): 214 | return True 215 | if vid and pid: 216 | #print(vid) 217 | #print(pid) 218 | #print("path: ", path) 219 | if path.lower().find('vid_%04x' % int(str(vid), 0)) != -1 and path.lower().find('pid_%04x' % int(str(pid), 0)) != -1: 220 | return True 221 | else: 222 | return False 223 | -------------------------------------------------------------------------------- /G14RunCommands.py: -------------------------------------------------------------------------------- 1 | from G14Utils import get_active_windows_plan 2 | import os 3 | import subprocess as sp 4 | import sys 5 | import time 6 | import re 7 | from subprocess import STDOUT 8 | 9 | 10 | class RunCommands: 11 | def __init__( 12 | self, config, G14dir, app_GUID, dpp_GUID, notify, windows_plans, active_plan_map 13 | ): 14 | self.config = config 15 | self.G14dir = G14dir 16 | self.app_GUID = app_GUID 17 | self.dpp_GUID = dpp_GUID 18 | self.notify = notify 19 | self.windows_plans = windows_plans 20 | self.active_plan_map = active_plan_map 21 | self.windows_plan_map = {name: guid for guid, name in iter(windows_plans)} 22 | self.reverse_windows_plan_map = { 23 | guid: name for guid, name in iter(windows_plans) 24 | } 25 | 26 | def set_windows_and_active_plans(self, winplns, activeplns): 27 | self.active_plan_map = activeplns 28 | self.windows_plans = winplns 29 | # noinspection PyBroadException 30 | 31 | # Small utility to convert windows HEX format to a boolean. 32 | def parse_boolean(self, parse_string): 33 | try: 34 | if parse_string == "0x00000000": # We will consider this as False 35 | return False 36 | else: # We will consider this as True 37 | return True 38 | except Exception: 39 | return None # Just in case™ 40 | 41 | def get_boost(self): 42 | # I know, it's ugly, but no other way to do that from py. 43 | pwr_guid = list(get_active_windows_plan().values())[0] # Parse the GUID 44 | SUB_PROCESSOR = " 54533251-82be-4824-96c1-47b60b740d00" 45 | PERFBOOSTMODE = " be337238-0d82-4146-a960-4f3749d470c7" 46 | # Let's get the boost option in the currently active power scheme 47 | pwr_settings = os.popen( 48 | "powercfg /Q " + pwr_guid + SUB_PROCESSOR + PERFBOOSTMODE 49 | ) 50 | output = pwr_settings.readlines() # We save the output to parse it afterwards 51 | # Parsing AC, assuming the DC is the same setting 52 | ac_boost = output[-3].rsplit(": ")[1].strip("\n") 53 | # battery_boost = parse_boolean(output[-2].rsplit(": ")[1].strip("\n")) # currently unused, we will set both 54 | return ac_boost 55 | 56 | def do_boost(self, state): 57 | # Just to be safe, let's get the current power scheme 58 | SUB_PROCESSOR = "54533251-82be-4824-96c1-47b60b740d00" 59 | PERFBOOSTMODE = "be337238-0d82-4146-a960-4f3749d470c7" 60 | set_ac = "powercfg /setacvalueindex" 61 | set_dc = "powercfg /setdcvalueindex" 62 | pwr_guid = list(get_active_windows_plan().values())[0] 63 | if state is False: 64 | state = 0 65 | SET_AC_VAL = "{0} {1} {2} {3} {4}".format( 66 | set_ac, pwr_guid, SUB_PROCESSOR, PERFBOOSTMODE, str(state) 67 | ) 68 | SET_DC_VAL = "{0} {1} {2} {3} {4}".format( 69 | set_dc, pwr_guid, SUB_PROCESSOR, PERFBOOSTMODE, str(state) 70 | ) 71 | sp.Popen(SET_AC_VAL, shell=True, creationflags=sp.CREATE_NO_WINDOW) 72 | sp.Popen(SET_DC_VAL, shell=True, creationflags=sp.CREATE_NO_WINDOW) 73 | if self.config["debug"]: 74 | print(SET_AC_VAL) 75 | print(SET_DC_VAL) 76 | 77 | def set_boost(self, state, notification=True): 78 | """ 79 | Takes boost state as a boolean or integer value and modifies the boost 80 | parameter of the current windows plan by modifying and then activating 81 | the windows plan. The current hackish solution is to switch to another 82 | windows plan and then switch back. 83 | 84 | By default set_boost will cause a windows notification to appear 85 | indicating the boost value after it is set, you can silence the 86 | notification with the parameter notification=False. 87 | """ 88 | windows_plan_map = self.windows_plan_map 89 | pwr_guid = list(get_active_windows_plan().values())[0] 90 | switch_to = list( 91 | {val for key, val in windows_plan_map.items() if val != pwr_guid} 92 | )[0] 93 | print(switch_to, "switch to guid") 94 | print(pwr_guid, "power guid") 95 | self.set_power_plan(switch_to) 96 | time.sleep(0.25) 97 | self.set_power_plan(pwr_guid) 98 | if state is True: # Activate boost 99 | self.do_boost(state) 100 | if notification is True: 101 | self.notify("Boost ENABLED") # Inform the user 102 | elif state is False or state == 0: # Deactivate boost 103 | self.do_boost(False) 104 | if notification is True: 105 | self.notify("Boost DISABLED") # Inform the user 106 | elif state == 4: 107 | self.do_boost(state) 108 | if notification is True: 109 | # Inform the user 110 | self.notify("Boost Efficient Aggressive") 111 | elif state == 2: 112 | self.do_boost(state) 113 | if notification is True: 114 | self.notify("Boost Aggressive") # Inform the user 115 | self.set_power_plan(switch_to) 116 | time.sleep(0.25) 117 | self.set_power_plan(pwr_guid) 118 | 119 | def get_dgpu(self): 120 | # Get active windows power scheme 121 | pwr_guid = list(get_active_windows_plan().values())[0] # Parse the GUID 122 | SW_DYNAMC_GRAPHICS = "e276e160-7cb0-43c6-b20b-73f5dce39954" 123 | GLOBAL_SETTINGS = "a1662ab2-9d34-4e53-ba8b-2639b9e20857" 124 | pwr_settings = os.popen( 125 | " ".join(["powercfg", "/q", pwr_guid, SW_DYNAMC_GRAPHICS, GLOBAL_SETTINGS]) 126 | ) # Let's get the dGPU status in the current power scheme 127 | output = pwr_settings.readlines() # We save the output to parse it afterwards 128 | # Convert to boolean for "On/Off" 129 | dgpu_ac = self.parse_boolean(output[-3].rsplit(": ")[1].strip("\n")) 130 | if dgpu_ac is None: 131 | return False 132 | else: 133 | return dgpu_ac 134 | 135 | def set_dgpu(self, state, notification=True): 136 | G14dir = self.G14dir 137 | # Just to be safe, let's get the current power scheme 138 | pwr_guid = list(get_active_windows_plan().values())[0] 139 | SW_DYNAMC_GRAPHICS = "e276e160-7cb0-43c6-b20b-73f5dce39954" 140 | GLOBAL_SETTINGS = "a1662ab2-9d34-4e53-ba8b-2639b9e20857" 141 | AC = "/setacvalueindex" 142 | DC = "/setdcvalueindex" 143 | 144 | def _set_dgpu(SETTING, AC_DC): 145 | return os.popen( 146 | " ".join( 147 | [ 148 | "powercfg", 149 | AC_DC, 150 | pwr_guid, 151 | SW_DYNAMC_GRAPHICS, 152 | GLOBAL_SETTINGS, 153 | str(SETTING), 154 | ] 155 | ) 156 | ) 157 | 158 | if state is True: # Activate dGPU 159 | _set_dgpu(2, AC) 160 | _set_dgpu(2, DC) 161 | time.sleep(0.25) 162 | if notification is True: 163 | self.notify("dGPU set to performance.") # Inform the user 164 | elif state is False: # Deactivate dGPU 165 | _set_dgpu(0, AC) 166 | _set_dgpu(0, DC) 167 | time.sleep(0.25) 168 | os.system('"' + str(G14dir) + "\\restartGPUcmd.bat" + '"') 169 | if notification is True: 170 | self.notify("dGPU set to force power saver.") # Inform the user 171 | 172 | def check_screen( 173 | self, 174 | ): # Checks to see if the G14 has a 120Hz capable screen or not 175 | config = self.config 176 | check_screen_ref = str( 177 | os.path.join(config["temp_dir"] + "ChangeScreenResolution.exe") 178 | ) 179 | # /m lists all possible resolutions & refresh rates 180 | screen = os.popen(check_screen_ref + " /m /d=0") 181 | output = screen.readlines() 182 | for line in output: 183 | if re.search("@120Hz", line): 184 | return True 185 | else: 186 | return False 187 | 188 | def get_screen(self): # Gets the current screen resolution 189 | config = self.config 190 | get_screen_ref = str( 191 | os.path.join(config["temp_dir"] + "ChangeScreenResolution.exe") 192 | ) 193 | # /l lists current resolution & refresh rate 194 | screen = os.popen(get_screen_ref + " /l /d=0") 195 | output = screen.readlines() 196 | for line in output: 197 | if re.search("@120Hz", line): 198 | return True 199 | else: 200 | return False 201 | 202 | def set_screen(self, refresh: str or int, notification=True): 203 | config = self.config 204 | if ( 205 | self.check_screen() 206 | ): # Before trying to change resolution, check that G14 is capable of 120Hz resolution 207 | if refresh is None: 208 | # If screen refresh rate is null (not set), set to default refresh rate of 120Hz 209 | self.set_screen(120) 210 | check_screen_ref = str( 211 | os.path.join(config["temp_dir"] + "ChangeScreenResolution.exe") 212 | ) 213 | os.popen(check_screen_ref + " /d=0 /f=" + str(refresh)) 214 | if notification is True: 215 | self.notify("Screen refresh rate set to: " + str(refresh) + "Hz") 216 | else: 217 | return 218 | 219 | def set_atrofac(self, asus_plan, cpu_curve=None, gpu_curve=None): 220 | config = self.config 221 | atrofac = str(os.path.join(config["temp_dir"] + "atrofac-cli.exe")) 222 | if cpu_curve is not None and gpu_curve is not None: 223 | cmdargs = ( 224 | atrofac 225 | + " fan --cpu " 226 | + cpu_curve 227 | + " --gpu " 228 | + gpu_curve 229 | + " --plan " 230 | + asus_plan 231 | ) 232 | elif cpu_curve is not None and gpu_curve is None: 233 | cmdargs = atrofac + " fan --cpu " + cpu_curve + " --plan " + asus_plan 234 | elif cpu_curve is None and gpu_curve is not None: 235 | cmdargs = atrofac + " fan --gpu " + gpu_curve + " --plan " + asus_plan 236 | else: 237 | cmdargs = atrofac + " --plan " + asus_plan 238 | try: 239 | result = sp.check_output( 240 | cmdargs, shell=True, creationflags=sp.CREATE_NO_WINDOW 241 | ) 242 | if self.config["debug"]: 243 | print(result) 244 | except Exception: 245 | if self.config["debug"]: 246 | print("Error setting fan speeds.") 247 | 248 | def set_ryzenadj(self, tdp, attempts=3): 249 | config = self.config 250 | ryzenadj = str(os.path.join(config["temp_dir"] + "ryzenadj.exe")) 251 | if tdp is None: 252 | pass 253 | else: 254 | try: 255 | result = sp.check_output( 256 | ryzenadj + " -a " + str(tdp) + " -b " + str(tdp), 257 | shell=True, 258 | creationflags=sp.CREATE_NO_WINDOW, 259 | ) 260 | if self.config["debug"]: 261 | print(result.decode("utf-8")) 262 | except Exception: 263 | print("There was an error applying ryzenadj\n Attempt #" + attempts) 264 | if attempts == 0: 265 | self.notify( 266 | "There was an error apply ryzenadj TDP power settings...\n" 267 | + "This is relatively normal." 268 | ) 269 | else: 270 | self.set_ryzenadj(tdp, attempts - 1) 271 | 272 | def set_power_plan(self, GUID, do_notify=False): 273 | print("setting power plan GUID to: ", GUID) 274 | result = sp.check_output( 275 | ["powercfg", "/s", GUID], 276 | shell=True, 277 | creationflags=sp.CREATE_NO_WINDOW, 278 | stderr=STDOUT, 279 | ) 280 | if self.config["debug"]: 281 | print(result.decode("utf-8")) 282 | if do_notify: 283 | self.notify( 284 | "Switched windows plan to:\n" + self.reverse_windows_plan_map[GUID] 285 | ) 286 | 287 | def finalize_powercfg_chg(self, GUID): 288 | time.sleep(0.25) 289 | sp.Popen( 290 | ["powercfg", "-setactive", GUID], 291 | shell=True, 292 | creationflags=sp.CREATE_NO_WINDOW, 293 | stderr=STDOUT, 294 | ) 295 | 296 | def edit_config(self): 297 | config_loc = "" 298 | if getattr(sys, "frozen", False): 299 | # Set absolute path for config.yaml 300 | config_loc = os.path.join(str(self.G14dir), "config.yml") 301 | elif __file__: 302 | # Set absolute path for config.yaml 303 | config_loc = os.path.join(str(self.G14dir), "data/config.yml") 304 | 305 | sp.Popen(["notepad", config_loc], shell=True, creationflags=sp.CREATE_NO_WINDOW) 306 | 307 | def apply_plan(self, plan): 308 | current_plan = plan["name"] 309 | self.set_atrofac(plan["plan"], plan["cpu_curve"], plan["gpu_curve"]) 310 | self.set_boost(plan["boost"], False) 311 | self.set_dgpu(plan["dgpu_enabled"], False) 312 | self.set_screen(plan["screen_hz"], False) 313 | self.set_ryzenadj(plan["cpu_tdp"]) 314 | self.notify("Applied plan " + plan["name"]) 315 | return current_plan 316 | -------------------------------------------------------------------------------- /winusbpy/winusbpy.py: -------------------------------------------------------------------------------- 1 | import struct 2 | import ctypes 3 | from .winusb import WinUSBApi 4 | from .winusbclasses import GUID, DIGCF_ALLCLASSES, DIGCF_DEFAULT, DIGCF_PRESENT, DIGCF_PROFILE, DIGCF_DEVICE_INTERFACE, \ 5 | SpDeviceInterfaceData, SpDeviceInterfaceDetailData, SpDevinfoData, GENERIC_WRITE, GENERIC_READ, FILE_SHARE_WRITE, \ 6 | FILE_SHARE_READ, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, FILE_FLAG_OVERLAPPED, INVALID_HANDLE_VALUE, \ 7 | UsbInterfaceDescriptor, PipeInfo, ERROR_IO_INCOMPLETE, ERROR_IO_PENDING, Overlapped 8 | from ctypes import c_byte, byref, sizeof, c_ulong, resize, wstring_at, c_void_p, c_ubyte, create_string_buffer 9 | from ctypes.wintypes import DWORD, WCHAR 10 | from .winusbutils import SetupDiGetClassDevs, SetupDiEnumDeviceInterfaces, SetupDiGetDeviceInterfaceDetail, is_device, \ 11 | CreateFile, WinUsb_Initialize, Close_Handle, WinUsb_Free, GetLastError, WinUsb_QueryDeviceInformation, \ 12 | WinUsb_GetAssociatedInterface, WinUsb_QueryInterfaceSettings, WinUsb_QueryPipe, WinUsb_ControlTransfer, \ 13 | WinUsb_WritePipe, WinUsb_ReadPipe, WinUsb_GetOverlappedResult, SetupDiGetDeviceRegistryProperty, \ 14 | WinUsb_SetPipePolicy, WinUsb_FlushPipe, SPDRP_FRIENDLYNAME 15 | 16 | 17 | def is_64bit(): 18 | return struct.calcsize('P') * 8 == 64 19 | 20 | 21 | class WinUsbPy(object): 22 | 23 | def __init__(self): 24 | self.api = WinUSBApi() 25 | byte_array = c_byte * 8 26 | self.usb_device_guid = GUID(0xA5DCBF10, 0x6530, 0x11D2, byte_array(0x90, 0x1F, 0x00, 0xC0, 0x4F, 0xB9, 0x51, 0xED)) 27 | self.usb_winusb_guid = GUID(0xdee824ef, 0x729b, 0x4a0e, byte_array(0x9c, 0x14, 0xb7, 0x11, 0x7d, 0x33, 0xa8, 0x17)) 28 | self.usb_composite_guid = GUID(0x36FC9E60, 0xC465, 0x11CF, byte_array(0x80, 0x56, 0x44, 0x45, 0x53, 0x54, 0x00, 0x00)) 29 | self.handle_file = INVALID_HANDLE_VALUE 30 | self.handle_winusb = c_void_p() 31 | self._index = -1 32 | 33 | def list_usb_devices(self, **kwargs): 34 | self.device_paths = {} 35 | value = 0x00000000 36 | try: 37 | if kwargs.get("default"): 38 | value |= DIGCF_DEFAULT 39 | if kwargs.get("present"): 40 | value |= DIGCF_PRESENT 41 | if kwargs.get("allclasses"): 42 | value |= DIGCF_ALLCLASSES 43 | if kwargs.get("profile"): 44 | value |= DIGCF_PROFILE 45 | if kwargs.get("deviceinterface"): 46 | value |= DIGCF_DEVICE_INTERFACE 47 | except KeyError: 48 | if value == 0x00000000: 49 | value = 0x00000010 50 | pass 51 | 52 | flags = DWORD(value) 53 | self.handle = self.api.exec_function_setupapi(SetupDiGetClassDevs, byref(self.usb_winusb_guid), None, None, flags) 54 | 55 | sp_device_interface_data = SpDeviceInterfaceData() 56 | sp_device_interface_data.cb_size = sizeof(sp_device_interface_data) 57 | sp_device_interface_detail_data = SpDeviceInterfaceDetailData() 58 | sp_device_info_data = SpDevinfoData() 59 | sp_device_info_data.cb_size = sizeof(sp_device_info_data) 60 | 61 | i = 0 62 | required_size = DWORD(0) 63 | member_index = DWORD(i) 64 | cb_sizes = (8, 6, 5) # different on 64 bit / 32 bit etc 65 | 66 | while self.api.exec_function_setupapi(SetupDiEnumDeviceInterfaces, self.handle, None, byref(self.usb_winusb_guid), 67 | member_index, byref(sp_device_interface_data)): 68 | self.api.exec_function_setupapi(SetupDiGetDeviceInterfaceDetail, self.handle, 69 | byref(sp_device_interface_data), None, 0, byref(required_size), None) 70 | resize(sp_device_interface_detail_data, required_size.value) 71 | 72 | 73 | path = None 74 | for cb_size in cb_sizes: 75 | sp_device_interface_detail_data.cb_size = cb_size 76 | ret = self.api.exec_function_setupapi(SetupDiGetDeviceInterfaceDetail, self.handle, 77 | byref(sp_device_interface_data), byref(sp_device_interface_detail_data), 78 | required_size, byref(required_size), byref(sp_device_info_data)) 79 | if ret: 80 | cb_sizes = (cb_size, ) 81 | path = wstring_at(byref(sp_device_interface_detail_data, sizeof(DWORD))) 82 | break 83 | if path is None: 84 | raise ctypes.WinError() 85 | 86 | # friendly name 87 | name = path 88 | buff_friendly_name = ctypes.create_unicode_buffer(250) 89 | if self.api.exec_function_setupapi(SetupDiGetDeviceRegistryProperty, self.handle, 90 | byref(sp_device_info_data), 91 | SPDRP_FRIENDLYNAME, 92 | None, 93 | ctypes.byref(buff_friendly_name), 94 | ctypes.sizeof(buff_friendly_name) - 1, 95 | None): 96 | 97 | name = buff_friendly_name.value 98 | else: 99 | print(ctypes.WinError()) 100 | self.device_paths[name] = path 101 | i += 1 102 | member_index = DWORD(i) 103 | required_size = c_ulong(0) 104 | resize(sp_device_interface_detail_data, sizeof(SpDeviceInterfaceDetailData)) 105 | return self.device_paths 106 | 107 | def find_device(self, path): 108 | #print("self.name: ", self._name) 109 | #print("self.vid: ", self._vid) 110 | #print("self.pid: ", self._pid) 111 | #print("path", path) 112 | return is_device(self._name, self._vid, self._pid, path) 113 | 114 | def init_winusb_device(self, name, vid, pid): 115 | #print(type(self.device_paths)) 116 | self._vid = vid 117 | self._pid = pid 118 | self._name = name 119 | #print("name: ", name) 120 | #print("vid: ", id) 121 | #print("pid: ", pid) 122 | for i in self.device_paths: 123 | if i == self._name: 124 | path = self.device_paths[i] 125 | #print("Path: ", self.device_paths[i]) 126 | """try: 127 | ftr = filter(self.find_device, self.device_paths) 128 | paths = [p for p in ftr] 129 | path = self.device_paths[paths[0]] 130 | except IndexError: 131 | return False""" 132 | 133 | self.handle_file = self.api.exec_function_kernel32(CreateFile, path, GENERIC_WRITE | GENERIC_READ, 134 | FILE_SHARE_WRITE | FILE_SHARE_READ, None, OPEN_EXISTING, 135 | FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, None) 136 | 137 | if self.handle_file == INVALID_HANDLE_VALUE: 138 | return False 139 | result = self.api.exec_function_winusb(WinUsb_Initialize, self.handle_file, byref(self.handle_winusb)) 140 | if result == 0: 141 | err = self.get_last_error_code() 142 | raise ctypes.WinError() 143 | # return False 144 | else: 145 | self._index = 0 146 | return True 147 | 148 | def close_winusb_device(self): 149 | result_file = self.api.exec_function_kernel32(Close_Handle, self.handle_file) 150 | result_winusb = self.api.exec_function_winusb(WinUsb_Free, self.handle_winusb) 151 | return result_file != 0 and result_winusb != 0 152 | 153 | def get_last_error_code(self): 154 | return self.api.exec_function_kernel32(GetLastError) 155 | 156 | def query_device_info(self, query=1): 157 | info_type = c_ulong(query) 158 | buff = (c_void_p * 1)() 159 | buff_length = c_ulong(sizeof(c_void_p)) 160 | result = self.api.exec_function_winusb(WinUsb_QueryDeviceInformation, self.handle_winusb, info_type, 161 | byref(buff_length), buff) 162 | if result != 0: 163 | return buff[0] 164 | else: 165 | return -1 166 | 167 | def query_interface_settings(self, index): 168 | if self._index != -1: 169 | temp_handle_winusb = self.handle_winusb 170 | if self._index != 0: 171 | result = self.api.exec_function_winusb(WinUsb_GetAssociatedInterface, self.handle_winusb, 172 | c_ubyte(index), byref(temp_handle_winusb)) 173 | if result == 0: 174 | return False 175 | interface_descriptor = UsbInterfaceDescriptor() 176 | result = self.api.exec_function_winusb(WinUsb_QueryInterfaceSettings, temp_handle_winusb, c_ubyte(0), 177 | byref(interface_descriptor)) 178 | if result != 0: 179 | return interface_descriptor 180 | else: 181 | return None 182 | else: 183 | return None 184 | 185 | def change_interface(self, index): 186 | result = self.api.exec_function_winusb(WinUsb_GetAssociatedInterface, self.handle_winusb, c_ubyte(index), 187 | byref(self.handle_winusb)) 188 | if result != 0: 189 | self._index = index 190 | return True 191 | else: 192 | return False 193 | 194 | def query_pipe(self, pipe_index): 195 | pipe_info = PipeInfo() 196 | result = self.api.exec_function_winusb(WinUsb_QueryPipe, self.handle_winusb, c_ubyte(0), pipe_index, 197 | byref(pipe_info)) 198 | if result != 0: 199 | return pipe_info 200 | else: 201 | return None 202 | 203 | def control_transfer(self, setup_packet, buff=None): 204 | if buff != None: 205 | if setup_packet.length > 0: # Host 2 Device 206 | buff = (c_ubyte * setup_packet.length)(*buff) 207 | buffer_length = setup_packet.length 208 | else: # Device 2 Host 209 | buff = (c_ubyte * setup_packet.length)() 210 | buffer_length = setup_packet.length 211 | else: 212 | buff = c_ubyte() 213 | buffer_length = 0 214 | 215 | result = self.api.exec_function_winusb(WinUsb_ControlTransfer, self.handle_winusb, setup_packet, byref(buff), 216 | c_ulong(buffer_length), byref(c_ulong(0)), None) 217 | return {"result": result != 0, "buffer": [buff]} 218 | 219 | def write(self, pipe_id, write_buffer): 220 | write_buffer = create_string_buffer(write_buffer) 221 | written = c_ulong(0) 222 | self.api.exec_function_winusb(WinUsb_WritePipe, self.handle_winusb[self._index], c_ubyte(pipe_id), write_buffer, 223 | c_ulong(len(write_buffer) - 1), byref(written), None) 224 | return written.value 225 | 226 | def read(self, pipe_id, length_buffer): 227 | read_buffer = create_string_buffer(length_buffer) 228 | read = c_ulong(0) 229 | result = self.api.exec_function_winusb(WinUsb_ReadPipe, self.handle_winusb[self._index], c_ubyte(pipe_id), 230 | read_buffer, c_ulong(length_buffer), byref(read), None) 231 | if result != 0: 232 | if read.value != length_buffer: 233 | return read_buffer[:read.value] 234 | else: 235 | return read_buffer 236 | else: 237 | return None 238 | 239 | def set_timeout(self, pipe_id, timeout): 240 | class POLICY_TYPE: 241 | SHORT_PACKET_TERMINATE = 1 242 | AUTO_CLEAR_STALL = 2 243 | PIPE_TRANSFER_TIMEOUT = 3 244 | IGNORE_SHORT_PACKETS = 4 245 | ALLOW_PARTIAL_READS = 5 246 | AUTO_FLUSH = 6 247 | RAW_IO = 7 248 | 249 | policy_type = c_ulong(POLICY_TYPE.PIPE_TRANSFER_TIMEOUT) 250 | value_length = c_ulong(4) 251 | value = c_ulong(int(timeout * 1000)) # in ms 252 | result = self.api.exec_function_winusb(WinUsb_SetPipePolicy, self.handle_winusb[self._index], c_ubyte(pipe_id), 253 | policy_type, value_length, byref(value)) 254 | return result 255 | 256 | def flush(self, pipe_id): 257 | result = self.api.exec_function_winusb(WinUsb_FlushPipe, self.handle_winusb[self._index], c_ubyte(pipe_id)) 258 | return result 259 | 260 | def _overlapped_read_do(self,pipe_id): 261 | self.olread_ol.Internal = 0 262 | self.olread_ol.InternalHigh = 0 263 | self.olread_ol.Offset = 0 264 | self.olread_ol.OffsetHigh = 0 265 | self.olread_ol.Pointer = 0 266 | self.olread_ol.hEvent = 0 267 | result = self.api.exec_function_winusb(WinUsb_ReadPipe, self.handle_winusb, c_ubyte(pipe_id), self.olread_buf, 268 | c_ulong(self.olread_buflen), byref(c_ulong(0)), byref(self.olread_ol)) 269 | if result != 0: 270 | return True 271 | else: 272 | return False 273 | 274 | def overlapped_read_init(self, pipe_id, length_buffer): 275 | self.olread_ol = Overlapped() 276 | self.olread_buf = create_string_buffer(length_buffer) 277 | self.olread_buflen = length_buffer 278 | return self._overlapped_read_do(pipe_id) 279 | 280 | def overlapped_read(self, pipe_id): 281 | """ keep on reading overlapped, return bytearray, empty if nothing to read, None if err""" 282 | rl = c_ulong(0) 283 | result = self.api.exec_function_winusb(WinUsb_GetOverlappedResult, self.handle_winusb, byref(self.olread_ol),byref(rl),False) 284 | if result == 0: 285 | if self.get_last_error_code() == ERROR_IO_PENDING or \ 286 | self.get_last_error_code() == ERROR_IO_INCOMPLETE: 287 | return "" 288 | else: 289 | return None 290 | else: 291 | ret = str(self.olread_buf[0:rl.value]) 292 | self._overlapped_read_do(pipe_id) 293 | return ret 294 | -------------------------------------------------------------------------------- /winusbpy/examples/winusbtest.py: -------------------------------------------------------------------------------- 1 | """Test1: PL2303 serial port user-space driver using WINUSB low level api""" 2 | import time 3 | from winusbpy import * 4 | from ctypes import * 5 | from ctypes.wintypes import * 6 | from ..winusbclasses import DIGCF_DEVICE_INTERFACE, DIGCF_PRESENT, GENERIC_WRITE, GENERIC_READ, FILE_SHARE_READ, \ 7 | FILE_SHARE_WRITE, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, FILE_FLAG_OVERLAPPED, INVALID_HANDLE_VALUE 8 | 9 | pl2303_vid = "067b" 10 | pl2303_pid = "2303" 11 | path = "" 12 | interface_descriptor = UsbInterfaceDescriptor() 13 | 14 | """ USB Setup Packets """ 15 | pkt1 = UsbSetupPacket(0xc0, 0x01, 0x8484, 0x00, 0x01) 16 | pkt2 = UsbSetupPacket(0x40, 0x01, 0x0404, 0x00, 0x00) 17 | pkt3 = UsbSetupPacket(0x40, 0x01, 0x0404, 0x00, 0x01) 18 | pkt4 = UsbSetupPacket(0xc0, 0x01, 0x8383, 0x00, 0x01) 19 | pkt5 = UsbSetupPacket(0xc0, 0x01, 0x8484, 0x00, 0x01) 20 | pkt6 = UsbSetupPacket(0x40, 0x01, 0x0404, 0x01, 0x00) 21 | pkt7 = UsbSetupPacket(0xc0, 0x01, 0x8484, 0x00, 0x01) 22 | pkt8 = UsbSetupPacket(0xc0, 0x01, 0x8383, 0x00, 0x01) 23 | pkt9 = UsbSetupPacket(0x40, 0x01, 0x0000, 0x01, 0x00) 24 | pkt10 = UsbSetupPacket(0x40, 0x01, 0x0001, 0x00, 0x00) 25 | pkt11 = UsbSetupPacket(0x40, 0x01, 0x0002, 0x44, 0x00) 26 | pkt12 = UsbSetupPacket(0x00, 0x01, 0x0001, 0x00, 0x00) 27 | 28 | pkt13 = UsbSetupPacket(0x21, 0x20, 0x0000, 0x00, 0x07) 29 | pkt14 = UsbSetupPacket(0x40, 0x01, 0x0505, 0x1311, 0x00) 30 | pkt15 = UsbSetupPacket(0x21, 0x22, 0x0001, 0x00, 0x00) 31 | pkt16 = UsbSetupPacket(0x40, 0x01, 0x0505, 0x1311, 0x00) 32 | pkt17 = UsbSetupPacket(0x21, 0x22, 0x0001, 0x00, 0x00) 33 | pkt18 = UsbSetupPacket(0xc0, 0x01, 0x0080, 0x00, 0x02) 34 | pkt19 = UsbSetupPacket(0xc0, 0x01, 0x0081, 0x00, 0x02) 35 | pkt20 = UsbSetupPacket(0x40, 0x01, 0x0000, 0x01, 0x00) 36 | 37 | """ USB Data""" 38 | hello = create_string_buffer("Hello") 39 | header = create_string_buffer( 40 | "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x08\x00\x00\x01\x08\x01\x00\x00\x08\x01\x00\x00\x08\x01\x00\x00\x08\x01\x00\x00\x08\x01\x00\x00\x08\x01\x00\x00\x08\x01\x00\x00") 41 | tx1 = create_string_buffer("\x18") 42 | tx2 = create_string_buffer("\x08") 43 | tx3 = create_string_buffer("\x08") 44 | tx4 = create_string_buffer("\x14") 45 | tx5 = create_string_buffer("\x14") 46 | tx6 = create_string_buffer("\x22") 47 | tx7 = create_string_buffer("\x3e") 48 | tx8 = create_string_buffer("\x22") 49 | tx9 = create_string_buffer("\x77") 50 | tx10 = create_string_buffer("\x00") 51 | tx11 = create_string_buffer("\x00") 52 | tx12 = create_string_buffer("\x00") 53 | 54 | api = WinUSBApi() 55 | byte_array = c_byte * 8 56 | guid = GUID(0xA5DCBF10, 0x6530, 0x11D2, byte_array(0x90, 0x1F, 0x00, 0xC0, 0x4F, 0xB9, 0x51, 0xED)) 57 | flags = DWORD(DIGCF_DEVICE_INTERFACE | DIGCF_PRESENT) 58 | i = 0 59 | member_index = DWORD(i) 60 | required_size = c_ulong(0) 61 | 62 | sp_device_info_data = SpDevinfoData() 63 | sp_device_interface_data = SpDeviceInterfaceData() 64 | sp_device_interface_detail_data = SpDeviceInterfaceDetailData() 65 | 66 | sp_device_interface_data.cb_size = sizeof(sp_device_interface_data) 67 | sp_device_info_data.cb_size = sizeof(sp_device_info_data) 68 | 69 | """ 70 | Enumerate all USB Devices Searching for a PL2303 device 71 | """ 72 | hdev_info = api.exec_function_setupapi("SetupDiGetClassDevs", byref(guid), None, None, flags) 73 | 74 | while api.exec_function_setupapi("SetupDiEnumDeviceInterfaces", hdev_info, None, byref(guid), member_index, 75 | byref(sp_device_interface_data)): 76 | # Get the required buffer size and resize SpDeviceInterfaceDetailData 77 | api.exec_function_setupapi("SetupDiGetDeviceInterfaceDetail", hdev_info, byref(sp_device_interface_data), None, 0, 78 | byref(required_size), None) 79 | resize(sp_device_interface_detail_data, required_size.value) 80 | 81 | """ I have been stuck here for hours. cb_size must reflect the fix part of the Struct!!!!""" 82 | sp_device_interface_detail_data.cb_size = sizeof(SpDeviceInterfaceDetailData) - sizeof(WCHAR * 1) 83 | 84 | if api.exec_function_setupapi("SetupDiGetDeviceInterfaceDetail", hdev_info, byref(sp_device_interface_data), 85 | byref(sp_device_interface_detail_data), required_size, byref(required_size), 86 | byref(sp_device_info_data)): 87 | path = wstring_at(byref(sp_device_interface_detail_data, sizeof(DWORD))) 88 | if is_device(pl2303_vid, pl2303_pid, path): 89 | print("PL 2303 PATH: " + path) 90 | break 91 | else: 92 | error_code = api.exec_function_kernel32("GetLastError") 93 | print("Error: " + str(error_code)) 94 | 95 | i += 1 96 | member_index = DWORD(i) 97 | required_size = c_ulong(0) 98 | resize(sp_device_interface_detail_data, sizeof(SpDeviceInterfaceDetailData)) 99 | 100 | """Open PL2303 Device""" 101 | handle_file = api.exec_function_kernel32("CreateFileW", path, GENERIC_WRITE | GENERIC_READ, 102 | FILE_SHARE_WRITE | FILE_SHARE_READ, None, OPEN_EXISTING, 103 | FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, None) 104 | if INVALID_HANDLE_VALUE == handle_file: 105 | print("Error Creating File") 106 | else: 107 | print("No error") 108 | handle_winusb = c_void_p() 109 | result = api.exec_function_winusb("WinUsb_Initialize", handle_file, byref(handle_winusb)) 110 | if result != 0: 111 | """ Get PL2303 Speed """ 112 | info_type = c_ulong(1) 113 | buff = (c_void_p * 1)() 114 | buff_length = c_ulong(sizeof(c_void_p)) 115 | 116 | result = api.exec_function_winusb("WinUsb_QueryDeviceInformation", handle_winusb, info_type, byref(buff_length), 117 | buff) 118 | if result != 0: 119 | print("Speed: " + str(buff[0])) 120 | 121 | else: 122 | error_code = api.exec_function_kernel32("GetLastError") 123 | print("Error Query Device: " + str(error_code)) 124 | 125 | """ Interface Settings """ 126 | response = api.exec_function_winusb("WinUsb_QueryInterfaceSettings", handle_winusb, c_ubyte(0), 127 | byref(interface_descriptor)) 128 | 129 | if response == 0: 130 | error_code = api.exec_function_kernel32("GetLastError") 131 | print("Error Query Interface: " + str(error_code)) 132 | if response != 0: 133 | print("bLength: " + str(interface_descriptor.b_length)) 134 | print("bDescriptorType: " + str(interface_descriptor.b_descriptor_type)) 135 | print("bInterfaceNumber: " + str(interface_descriptor.b_interface_number)) 136 | print("bAlternateSetting: " + str(interface_descriptor.b_alternate_setting)) 137 | print("bNumEndpoints " + str(interface_descriptor.b_num_endpoints)) 138 | print("bInterfaceClass " + str(interface_descriptor.b_interface_class)) 139 | print("bInterfaceSubClass: " + str(interface_descriptor.b_interface_sub_class)) 140 | print("bInterfaceProtocol: " + str(interface_descriptor.b_interface_protocol)) 141 | print("iInterface: " + str(interface_descriptor.i_interface)) 142 | 143 | """ Endpoints information """ 144 | i = 0 145 | endpoint_index = c_ubyte(0) 146 | pipe_info = PipeInfo() 147 | while i <= interface_descriptor.b_num_endpoints: 148 | result = api.exec_function_winusb("WinUsb_QueryPipe", handle_winusb, c_ubyte(0), endpoint_index, 149 | byref(pipe_info)) 150 | if result != 0: 151 | print("PipeType: " + str(pipe_info.pipe_type)) 152 | print("PipeId: " + str(pipe_info.pipe_id)) 153 | print("MaximumPacketSize: " + str(pipe_info.maximum_packet_size)) 154 | print("Interval: " + str(pipe_info.interval)) 155 | i += 1 156 | endpoint_index = c_ubyte(i) 157 | 158 | """ Control setup """ 159 | buff1 = c_ubyte() 160 | buff2 = (c_ubyte * 2)() 161 | buff_set_line = (c_ubyte * 7)(0xc0, 0x12, 0x00, 0x00, 0x00, 0x00, 0x08) 162 | api.exec_function_winusb("WinUsb_ControlTransfer", handle_winusb, pkt1, byref(buff1), c_ulong(1), 163 | byref(c_ulong(0)), None) 164 | api.exec_function_winusb("WinUsb_ControlTransfer", handle_winusb, pkt2, byref(buff1), c_ulong(0), 165 | byref(c_ulong(0)), None) 166 | api.exec_function_winusb("WinUsb_ControlTransfer", handle_winusb, pkt3, byref(buff1), c_ulong(1), 167 | byref(c_ulong(0)), None) 168 | api.exec_function_winusb("WinUsb_ControlTransfer", handle_winusb, pkt4, byref(buff1), c_ulong(1), 169 | byref(c_ulong(0)), None) 170 | api.exec_function_winusb("WinUsb_ControlTransfer", handle_winusb, pkt5, byref(buff1), c_ulong(1), 171 | byref(c_ulong(0)), None) 172 | api.exec_function_winusb("WinUsb_ControlTransfer", handle_winusb, pkt6, byref(buff1), c_ulong(0), 173 | byref(c_ulong(0)), None) 174 | api.exec_function_winusb("WinUsb_ControlTransfer", handle_winusb, pkt7, byref(buff1), c_ulong(1), 175 | byref(c_ulong(0)), None) 176 | api.exec_function_winusb("WinUsb_ControlTransfer", handle_winusb, pkt8, byref(buff1), c_ulong(1), 177 | byref(c_ulong(0)), None) 178 | api.exec_function_winusb("WinUsb_ControlTransfer", handle_winusb, pkt9, byref(buff1), c_ulong(0), 179 | byref(c_ulong(0)), None) 180 | api.exec_function_winusb("WinUsb_ControlTransfer", handle_winusb, pkt10, byref(buff1), c_ulong(0), 181 | byref(c_ulong(0)), None) 182 | api.exec_function_winusb("WinUsb_ControlTransfer", handle_winusb, pkt11, byref(buff1), c_ulong(0), 183 | byref(c_ulong(0)), None) 184 | api.exec_function_winusb("WinUsb_ControlTransfer", handle_winusb, pkt12, byref(buff1), c_ulong(0), 185 | byref(c_ulong(0)), None) 186 | 187 | api.exec_function_winusb("WinUsb_ControlTransfer", handle_winusb, pkt13, byref(buff_set_line), c_ulong(7), 188 | byref(c_ulong(0)), None) 189 | api.exec_function_winusb("WinUsb_ControlTransfer", handle_winusb, pkt14, byref(buff1), c_ulong(0), 190 | byref(c_ulong(0)), None) 191 | api.exec_function_winusb("WinUsb_ControlTransfer", handle_winusb, pkt15, byref(buff1), c_ulong(0), 192 | byref(c_ulong(0)), None) 193 | api.exec_function_winusb("WinUsb_ControlTransfer", handle_winusb, pkt16, byref(buff1), c_ulong(0), 194 | byref(c_ulong(0)), None) 195 | api.exec_function_winusb("WinUsb_ControlTransfer", handle_winusb, pkt17, byref(buff1), c_ulong(0), 196 | byref(c_ulong(0)), None) 197 | 198 | api.exec_function_winusb("WinUsb_ControlTransfer", handle_winusb, pkt18, byref(buff2), c_ulong(1), 199 | byref(c_ulong(0)), None) 200 | api.exec_function_winusb("WinUsb_ControlTransfer", handle_winusb, pkt19, byref(buff2), c_ulong(1), 201 | byref(c_ulong(0)), None) 202 | api.exec_function_winusb("WinUsb_ControlTransfer", handle_winusb, pkt20, byref(buff1), c_ulong(0), 203 | byref(c_ulong(0)), None) 204 | 205 | """ Send Data """ 206 | api.exec_function_winusb("WinUsb_WritePipe", handle_winusb, c_ubyte(0x02), hello, c_ulong(5), 207 | byref(c_ulong(0)), None) 208 | time.sleep(0.045) 209 | api.exec_function_winusb("WinUsb_WritePipe", handle_winusb, c_ubyte(0x02), header, c_ulong(42), 210 | byref(c_ulong(0)), None) 211 | time.sleep(0.380) 212 | api.exec_function_winusb("WinUsb_WritePipe", handle_winusb, c_ubyte(0x02), tx1, c_ulong(1), 213 | byref(c_ulong(0)), None) 214 | time.sleep(0.380) 215 | api.exec_function_winusb("WinUsb_WritePipe", handle_winusb, c_ubyte(0x02), tx2, c_ulong(1), 216 | byref(c_ulong(0)), None) 217 | time.sleep(0.380) 218 | api.exec_function_winusb("WinUsb_WritePipe", handle_winusb, c_ubyte(0x02), tx3, c_ulong(1), 219 | byref(c_ulong(0)), None) 220 | time.sleep(0.380) 221 | api.exec_function_winusb("WinUsb_WritePipe", handle_winusb, c_ubyte(0x02), tx4, c_ulong(1), 222 | byref(c_ulong(0)), None) 223 | time.sleep(0.380) 224 | api.exec_function_winusb("WinUsb_WritePipe", handle_winusb, c_ubyte(0x02), tx5, c_ulong(1), 225 | byref(c_ulong(0)), None) 226 | time.sleep(0.380) 227 | api.exec_function_winusb("WinUsb_WritePipe", handle_winusb, c_ubyte(0x02), tx6, c_ulong(1), 228 | byref(c_ulong(0)), None) 229 | time.sleep(0.380) 230 | api.exec_function_winusb("WinUsb_WritePipe", handle_winusb, c_ubyte(0x02), tx7, c_ulong(1), 231 | byref(c_ulong(0)), None) 232 | time.sleep(0.380) 233 | api.exec_function_winusb("WinUsb_WritePipe", handle_winusb, c_ubyte(0x02), tx8, c_ulong(1), 234 | byref(c_ulong(0)), None) 235 | time.sleep(0.380) 236 | api.exec_function_winusb("WinUsb_WritePipe", handle_winusb, c_ubyte(0x02), tx9, c_ulong(1), 237 | byref(c_ulong(0)), None) 238 | time.sleep(0.380) 239 | api.exec_function_winusb("WinUsb_WritePipe", handle_winusb, c_ubyte(0x02), tx10, c_ulong(1), 240 | byref(c_ulong(0)), None) 241 | time.sleep(0.380) 242 | api.exec_function_winusb("WinUsb_WritePipe", handle_winusb, c_ubyte(0x02), tx11, c_ulong(1), 243 | byref(c_ulong(0)), None) 244 | time.sleep(0.380) 245 | api.exec_function_winusb("WinUsb_WritePipe", handle_winusb, c_ubyte(0x02), tx12, c_ulong(1), 246 | byref(c_ulong(0)), None) 247 | 248 | else: 249 | error_code = api.exec_function_kernel32("GetLastError") 250 | print("Error" + str(error_code)) 251 | -------------------------------------------------------------------------------- /G14Control.pyw: -------------------------------------------------------------------------------- 1 | import re 2 | from G14Data import G14_Data, load_config 3 | import ctypes 4 | import os 5 | import sys 6 | import threading 7 | import time 8 | from threading import Thread 9 | import psutil 10 | import pystray 11 | from pystray._base import Icon, Menu, MenuItem 12 | import resources 13 | from G14RunCommands import RunCommands 14 | from G14Utils import ( 15 | create_icon, 16 | get_g14plan, 17 | is_admin, 18 | get_app_path, 19 | rog_keyset, 20 | startup_checks, 21 | get_active_windows_plan, 22 | ) 23 | from win10toast import ToastNotifier 24 | 25 | toaster = ToastNotifier() 26 | main_cmds: RunCommands 27 | 28 | 29 | def activate_powerswitching(): 30 | global data 31 | data.auto_power_switch = True 32 | if data.power_thread is None: 33 | data.power_thread = power_check_thread() 34 | data.power_thread.start() 35 | notify("Power switching has been activated.") 36 | elif not data.power_thread.is_alive(): 37 | data.power_thread = power_check_thread() 38 | data.power_thread.start() 39 | notify("Power switching has been activated.") 40 | if ( 41 | data.default_gaming_plan is not None 42 | and data.default_gaming_plan_games is not None 43 | ): 44 | if data.gaming_thread is None: 45 | data.gaming_thread = gaming_check_thread() 46 | data.gaming_thread.start() 47 | elif not data.gaming_thread.is_alive(): 48 | data.gaming_thread = gaming_check_thread() 49 | data.gaming_thread.start() 50 | 51 | 52 | def deactivate_powerswitching(should_notify=True): 53 | global data 54 | data.auto_power_switch = False 55 | if data.power_thread is not None and data.power_thread.is_alive(): 56 | data.power_thread.kill() 57 | if data.gaming_thread is not None and data.gaming_thread.is_alive(): 58 | data.gaming_thread.kill() 59 | 60 | # Plan change notifies first, so this needs to be 61 | # on a delay to prevent simultaneous notifications 62 | if should_notify: 63 | notify("Auto power switching has been disabled.", wait=1) 64 | 65 | 66 | class power_check_thread(threading.Thread): 67 | def __init__( 68 | self, 69 | ): 70 | threading.Thread.__init__(self, daemon=True) 71 | print("power thread started...") 72 | 73 | def run(self): 74 | global data 75 | debug = data.config["debug"] 76 | # Only run while loop on startup if auto_power_switch is On (True) 77 | if debug: 78 | print("power thread running...") 79 | if data.auto_power_switch: 80 | if debug: 81 | print("power switch is enabled...") 82 | while data.run_power_thread: 83 | if debug: 84 | print(" run power thread is true") 85 | # Check to user hasn't disabled auto_power_switch 86 | # (i.e. by manually switching plans) 87 | if data.auto_power_switch: 88 | ac = ( 89 | psutil.sensors_battery().power_plugged 90 | ) # Get the current AC power status 91 | # If on AC power, and not on the default_ac_plan, switch to that plan 92 | if ( 93 | ac 94 | and data.current_plan != data.default_ac_plan 95 | and not data.game_running 96 | ): 97 | for plan in data.config["plans"]: 98 | if plan["name"] == data.default_ac_plan: 99 | apply_plan(plan) 100 | break 101 | # If on DC power, and not on the default_dc_plan, switch to that plan 102 | if ( 103 | not ac 104 | and data.current_plan != data.default_dc_plan 105 | and not data.game_running 106 | ): 107 | for plan in data.config["plans"]: 108 | if plan["name"] == data.default_dc_plan: 109 | apply_plan(plan) 110 | break 111 | time.sleep(10) 112 | else: 113 | self.kill() 114 | 115 | def kill(self): 116 | thread_id = self.ident 117 | res = ctypes.pythonapi.PyThreadState_SetAsyncExc( 118 | thread_id, ctypes.py_object(SystemExit) 119 | ) 120 | if res > 1: 121 | ctypes.pythonapi.PyThreadState_SetAsyncExc(thread_id, 0) 122 | print("Exception raise failure") 123 | 124 | 125 | class gaming_check_thread(threading.Thread): 126 | def __init__( 127 | self, 128 | ): 129 | threading.Thread.__init__(self, daemon=True) 130 | 131 | def run( 132 | self, 133 | ): # Checks if user specified games/programs are running, 134 | # and switches to user defined plan, then switches back once closed 135 | global data 136 | previous_plan = None # Define the previous plan to switch back to 137 | if data.auto_power_switch: 138 | while data.run_gaming_thread: # Continuously check every 10 seconds 139 | if data.auto_power_switch: 140 | output = os.popen("wmic process get description, processid").read() 141 | process = output.split("\n") 142 | processes = set(i.split(" ")[0] for i in process) 143 | # List of user defined processes 144 | targets = set(data.default_gaming_plan_games) 145 | if ( 146 | processes & targets 147 | ): # Compare 2 lists, if ANY overlap, set game_running to true 148 | data.game_running = True 149 | else: 150 | data.game_running = False 151 | # If game is running and not on the desired gaming plan, switch to that plan 152 | if ( 153 | data.game_running 154 | and data.current_plan != data.default_gaming_plan 155 | ): 156 | previous_plan = data.current_plan 157 | for plan in data.config["plans"]: 158 | if plan["name"] == data.default_gaming_plan: 159 | apply_plan(plan) 160 | notify(plan["name"]) 161 | break 162 | # If game is no longer running, and not on previous plan 163 | # already (if set), then switch back to previous plan 164 | if ( 165 | not data.game_running 166 | and previous_plan is not None 167 | and previous_plan != data.current_plan 168 | ): 169 | for plan in data.config["plans"]: 170 | if plan["name"] == previous_plan: 171 | apply_plan(plan) 172 | notify(plan["name"]) 173 | break 174 | # Check for programs every 10 sec 175 | time.sleep(config["check_power_every"]) 176 | else: 177 | data.game_running = False 178 | self.kill() 179 | 180 | def kill(self): 181 | thread_id = self.ident 182 | data.game_running = False 183 | res = ctypes.pythonapi.PyThreadState_SetAsyncExc( 184 | thread_id, ctypes.py_object(SystemExit) 185 | ) 186 | if res > 1: 187 | ctypes.pythonapi.PyThreadState_SetAsyncExc(thread_id, 0) 188 | print("Exception raise failure") 189 | 190 | 191 | def notify(message, toast_time=5, wait=0): 192 | Thread(target=do_notify, args=(message, toast_time, wait), daemon=True).start() 193 | 194 | 195 | def do_notify(message, toast_time, wait): 196 | if wait > 0: 197 | time.sleep(wait) 198 | toaster.show_toast( 199 | "G14ControlR3", 200 | msg=message, 201 | icon_path="res/icon.ico", 202 | duration=toast_time, 203 | threaded=True, 204 | ) 205 | 206 | 207 | def apply_plan(plan): 208 | global data 209 | data.current_plan = plan["name"] 210 | data.main_cmds.set_windows_and_active_plans( 211 | data.windows_plans, data.active_plan_map 212 | ) 213 | data.main_cmds.set_atrofac(plan["plan"], plan["cpu_curve"], plan["gpu_curve"]) 214 | data.main_cmds.set_boost(plan["boost"], False) 215 | data.main_cmds.set_dgpu(plan["dgpu_enabled"], False) 216 | data.main_cmds.set_screen(plan["screen_hz"], False) 217 | data.main_cmds.set_ryzenadj(plan["cpu_tdp"]) 218 | notify("Applied plan " + plan["name"]) 219 | 220 | 221 | def quit_app(): 222 | global device, data, icon_app 223 | 224 | data.run_power_thread = False 225 | data.run_gaming_thread = False 226 | if device is not None: 227 | device.close() 228 | try: 229 | icon_app.stop() 230 | except SystemExit: 231 | print("System Exit") 232 | sys.exit() 233 | 234 | 235 | class Windows_Plan_Check(threading.Thread): 236 | def __init__(self): 237 | threading.Thread.__init__(self, daemon=True) 238 | 239 | def run(self): 240 | global data 241 | while True: 242 | requires_reload = False 243 | 244 | # Check for windows plan changes 245 | plan_tuple = re.findall( 246 | r"([0-9a-f\-]{36}) *\((.*)\)", 247 | os.popen("powercfg /GETACTIVESCHEME").read(), 248 | ) 249 | if data.current_windows_plan != plan_tuple[0][1]: 250 | print("windows plan") 251 | data.update_win_plan(plan_tuple[0][1]) 252 | data.current_windows_plan = plan_tuple[0][1] 253 | requires_reload = True 254 | 255 | # Check for boost changes 256 | current = get_g14plan(data.current_plan, data.config) 257 | boost = data.main_cmds.get_boost()[-1] 258 | if int(boost) is not current["boost"]: 259 | print(boost, current["boost"], "Boost") 260 | requires_reload = True 261 | 262 | # Check for gpu changes 263 | if current["dgpu_enabled"] is not data.main_cmds.get_dgpu(): 264 | print(current["dgpu_enabled"], data.main_cmds.get_dgpu(), "DGPU") 265 | requires_reload = True 266 | 267 | # If reload required, update menu. 268 | if requires_reload: 269 | global icon_app 270 | icon_app.update_menu() 271 | time.sleep(5) 272 | 273 | def kill(self): 274 | thread_id = self.ident 275 | res = ctypes.pythonapi.PyThreadState_SetAsyncExc( 276 | thread_id, ctypes.py_object(SystemExit) 277 | ) 278 | if res > 1: 279 | ctypes.pythonapi.PyThreadState_SetAsyncExc(thread_id, 0) 280 | print("Exception raise failure") 281 | 282 | 283 | def apply_plan_deactivate_switching(plan): 284 | global data 285 | data.current_plan = plan["name"] 286 | apply_plan(plan) 287 | deactivate_powerswitching() 288 | 289 | 290 | def set_windows_plan(plan): 291 | global data 292 | if config["debug"]: 293 | print(plan) 294 | data.current_windows_plan = plan[1] 295 | data.update_win_plan(plan[1]) 296 | data.main_cmds.set_windows_and_active_plans( 297 | data.windows_plans, data.active_plan_map 298 | ) 299 | data.main_cmds.set_power_plan(plan[0], do_notify=True) 300 | 301 | 302 | def power_options_menu(): 303 | global data 304 | return list( 305 | map( 306 | lambda winplan: ( 307 | MenuItem( 308 | winplan[1], 309 | lambda: set_windows_plan(winplan), 310 | checked=lambda menu_itm: winplan[1] 311 | == list(get_active_windows_plan().keys())[0], 312 | ) 313 | ), 314 | data.windows_plans, 315 | ) 316 | ) 317 | 318 | 319 | def create_menu( 320 | main_cmds, windows_plans, icon_app, device 321 | ): # This will create the menu in the tray app 322 | global data 323 | opts_menu = power_options_menu() 324 | 325 | menu = Menu( 326 | # The default setting will make the action run on left click 327 | MenuItem( 328 | "CPU Boost", 329 | Menu( # The "Boost" submenu 330 | MenuItem( 331 | "Boost OFF", 332 | lambda: main_cmds.set_boost(0), 333 | checked=lambda menu_itm: True 334 | if int(main_cmds.get_boost()[2:]) == 0 335 | else False, 336 | ), 337 | MenuItem( 338 | "Boost Efficient Aggressive", 339 | lambda: main_cmds.set_boost(4), 340 | checked=lambda menu_itm: True 341 | if int(main_cmds.get_boost()[2:]) == 4 342 | else False, 343 | ), 344 | MenuItem( 345 | "Boost Aggressive", 346 | lambda: main_cmds.set_boost(2), 347 | checked=lambda menu_itm: True 348 | if int(main_cmds.get_boost()[2:]) == 2 349 | else False, 350 | ), 351 | ), 352 | ), 353 | MenuItem( 354 | "dGPU", 355 | Menu( 356 | MenuItem( 357 | "dGPU ON", 358 | lambda: main_cmds.set_dgpu(True), 359 | checked=lambda menu_itm: ( 360 | True if bool(main_cmds.get_dgpu()) else False 361 | ), 362 | ), 363 | MenuItem( 364 | "dGPU OFF", 365 | lambda: main_cmds.set_dgpu(False), 366 | checked=lambda menu_itm: ( 367 | False if bool(main_cmds.get_dgpu()) else True 368 | ), 369 | ), 370 | ), 371 | ), 372 | MenuItem( 373 | "Screen Refresh", 374 | Menu( 375 | MenuItem( 376 | "120Hz", 377 | lambda: main_cmds.set_screen(120), 378 | checked=lambda menu_itm: True 379 | if main_cmds.get_screen() == 1 380 | else False, 381 | ), 382 | MenuItem( 383 | "60Hz", 384 | lambda: main_cmds.set_screen(60), 385 | checked=lambda menu_itm: True 386 | if main_cmds.get_screen() == 0 387 | else False, 388 | ), 389 | ), 390 | visible=main_cmds.check_screen(), 391 | ), 392 | Menu.SEPARATOR, 393 | MenuItem("Windows Power Options", Menu(*opts_menu)), 394 | Menu.SEPARATOR, 395 | MenuItem( 396 | "Disable Auto Power Switching", 397 | lambda: deactivate_powerswitching(True), 398 | checked=lambda menu_itm: False if data.auto_power_switch else True, 399 | ), 400 | MenuItem( 401 | "Enable Auto Power Switching", 402 | lambda: activate_powerswitching(), 403 | checked=lambda menu_itm: data.auto_power_switch, 404 | ), 405 | Menu.SEPARATOR, 406 | # I have no idea of what I am doing, fo real, man.y 407 | # MenuItem('Stuff',*list(map((lambda win_plan: )))) 408 | *list( 409 | map( 410 | lambda plan: MenuItem( 411 | plan["name"], 412 | lambda: apply_plan_deactivate_switching(plan), 413 | checked=lambda menu_itm: True 414 | if data.current_plan == plan["name"] 415 | else False, 416 | ), 417 | data.config["plans"], 418 | ) 419 | ), # Blame @dedo1911 for this. You can find him on github. 420 | Menu.SEPARATOR, 421 | MenuItem("Edit config", main_cmds.edit_config), 422 | MenuItem("Reload config", lambda: reload_config(icon_app, device)), 423 | Menu.SEPARATOR, 424 | MenuItem("Quit", quit_app) # This to close the app, we will need it. 425 | ) 426 | return menu 427 | 428 | 429 | def reload_config(icon_app, device): 430 | global data 431 | deactivate_powerswitching(False) 432 | data = G14_Data() 433 | if ( 434 | data.default_ac_plan is not None 435 | and data.default_dc_plan is not None 436 | and data.config["power_switch_enabled"] is True 437 | ): 438 | data.auto_power_switch = True 439 | else: 440 | data.auto_power_switch = False 441 | 442 | if data.auto_power_switch and data.config["power_switch_enabled"]: 443 | data.power_thread = power_check_thread() 444 | data.run_power_thread = True 445 | data.power_thread.start() 446 | 447 | if ( 448 | data.config["default_gaming_plan"] is not None 449 | and data.config["default_gaming_plan_games"] is not None 450 | and data.config["power_switch_enabled"] is True 451 | ): 452 | data.gaming_thread = gaming_check_thread() 453 | data.run_gaming_thread = True 454 | data.gaming_thread.start() 455 | 456 | if device is not None: 457 | device.close() 458 | device = rog_keyset(config) 459 | 460 | start_plan = {} 461 | for plan in data.config["plans"]: 462 | if data.current_plan == plan["name"]: 463 | start_plan = plan 464 | break 465 | 466 | apply_plan(start_plan) 467 | data.main_cmds.set_power_plan(data.windows_plan_map[data.current_windows_plan]) 468 | updated_menu = create_menu(data.main_cmds, data.windows_plans, icon_app, device) 469 | icon_app.menu = updated_menu 470 | icon_app.update_menu() 471 | 472 | 473 | def startup(config, icon_app): 474 | global data 475 | data = G14_Data() 476 | 477 | # Set variable before startup_checks decides what the value should be 478 | resources.extract(config["temp_dir"]) 479 | 480 | startup_checks(data) 481 | # A process in the background will check for AC, autoswitch plan if enabled and detected 482 | # Instantiate command line tasks runners in G14RunCommands.py 483 | 484 | if data.power_switch_enabled: 485 | data.power_thread = power_check_thread() 486 | data.run_power_thread = True 487 | data.power_thread.start() 488 | 489 | if ( 490 | data.default_gaming_plan is not None 491 | and data.default_gaming_plan_games is not None 492 | and data.power_switch_enabled 493 | ): 494 | data.gaming_thread = gaming_check_thread() 495 | data.run_gaming_thread = True 496 | data.gaming_thread.start() 497 | 498 | device = rog_keyset(config) 499 | 500 | # This is the displayed name when hovering on the icon 501 | icon_app.title = config["app_name"] 502 | icon_app.icon = create_icon( 503 | config 504 | ) # This will set the icon itself (the graphical icon) 505 | icon_app.menu = create_menu( 506 | data.main_cmds, data.windows_plans, icon_app, device 507 | ) # This will create the menu 508 | 509 | start_plan = {} 510 | for plan in data.config["plans"]: 511 | if data.current_plan == plan["name"]: 512 | start_plan = plan 513 | break 514 | data.main_cmds.set_power_plan(data.windows_plan_map[data.current_windows_plan]) 515 | Windows_Plan_Check().start() 516 | apply_plan(start_plan) 517 | icon_app.run() # This runs the icon. Is single threaded, blocking. 518 | 519 | 520 | if __name__ == "__main__": 521 | global icon_app 522 | device = None 523 | G14dir = get_app_path() 524 | config = load_config(G14dir) # Make the config available to the whole script 525 | # Initialize the icon app and set its name 526 | icon_app: Icon = pystray.Icon(config["app_name"]) 527 | # If running as admin or in debug mode, launch program 528 | if is_admin(): 529 | startup(config, icon_app) 530 | else: # Re-run the program with admin rights 531 | ctypes.windll.shell32.ShellExecuteW( 532 | None, "runas", sys.executable, " ".join(sys.argv), None, 1 533 | ) 534 | -------------------------------------------------------------------------------- /pywinusb/hid/winapi.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | from __future__ import absolute_import 4 | 5 | import ctypes 6 | from ctypes import Structure, Union, c_ubyte, c_long, c_ulong, c_ushort, \ 7 | c_wchar, c_void_p, c_uint 8 | from ctypes import byref, POINTER, sizeof 9 | from ctypes.wintypes import ULONG, BOOLEAN, BYTE, WORD, DWORD, HANDLE, BOOL, \ 10 | WCHAR, LPWSTR, LPCWSTR 11 | #from core import HIDError 12 | from . import helpers 13 | import platform 14 | 15 | UCHAR = c_ubyte 16 | ENUM = c_uint 17 | TCHAR = WCHAR 18 | 19 | if platform.architecture()[0].startswith('64'): 20 | WIN_PACK = 8 21 | else: 22 | WIN_PACK = 1 23 | 24 | class WinApiException(Exception): 25 | "Rough Windows API exception type" 26 | pass 27 | 28 | def winapi_result( result ): 29 | """Validate WINAPI BOOL result, raise exception if failed""" 30 | if not result: 31 | raise WinApiException("%d (%x): %s" % (ctypes.GetLastError(), 32 | ctypes.GetLastError(), ctypes.FormatError())) 33 | return result 34 | 35 | #dll references 36 | setup_api = ctypes.windll.setupapi 37 | hid_dll = ctypes.windll.hid 38 | kernel32 = ctypes.windll.kernel32 39 | 40 | #os independent functions 41 | ReadFile = kernel32.ReadFile 42 | CancelIo = kernel32.CancelIo 43 | WriteFile = kernel32.WriteFile 44 | CloseHandle = kernel32.CloseHandle 45 | CloseHandle.restype = BOOL 46 | CloseHandle.argtypes = [HANDLE] 47 | SetEvent = kernel32.SetEvent 48 | WaitForSingleObject = kernel32.WaitForSingleObject 49 | 50 | #os dependant functions and definitions 51 | c_tchar = c_wchar 52 | CreateFile = kernel32.CreateFileW 53 | CreateEvent = kernel32.CreateEventW 54 | 55 | CM_Get_Device_ID = setup_api.CM_Get_Device_IDW 56 | 57 | 58 | b_verbose = True 59 | usb_verbose = False 60 | 61 | #************** 62 | # SetupApi.dll, it likes pack'ed = 1 structures 63 | class GUID(Structure): 64 | """GUID Windows OS structure""" 65 | _pack_ = 1 66 | _fields_ = [("data1", DWORD), 67 | ("data2", WORD), 68 | ("data3", WORD), 69 | ("data4", BYTE * 8)] 70 | 71 | class OVERLAPPED(Structure): 72 | class OFFSET_OR_HANDLE(Union): 73 | class OFFSET(Structure): 74 | _fields_ = [ 75 | ("offset", DWORD), 76 | ("offset_high", DWORD) ] 77 | 78 | _fields_ = [ 79 | ("offset", OFFSET), 80 | ("pointer", c_void_p) ] 81 | _fields_ = [ 82 | ("internal", POINTER(ULONG)), 83 | ("internal_high", POINTER(ULONG)), 84 | ("u", OFFSET_OR_HANDLE), 85 | ("h_event", HANDLE) 86 | ] 87 | 88 | class SP_DEVICE_INTERFACE_DATA(Structure): 89 | """ 90 | typedef struct _SP_DEVICE_INTERFACE_DATA { 91 | DWORD cbSize; 92 | GUID InterfaceClassGuid; 93 | DWORD Flags; 94 | ULONG_PTR Reserved; 95 | } SP_DEVICE_INTERFACE_DATA, *PSP_DEVICE_INTERFACE_DATA; 96 | """ 97 | _pack_ = WIN_PACK 98 | _fields_ = [ \ 99 | ("cb_size", DWORD), 100 | ("interface_class_guid", GUID), 101 | ("flags", DWORD), 102 | ("reserved", POINTER(ULONG)) 103 | ] 104 | 105 | class SP_DEVICE_INTERFACE_DETAIL_DATA(Structure): 106 | """ 107 | typedef struct _SP_DEVICE_INTERFACE_DETAIL_DATA { 108 | DWORD cbSize; 109 | TCHAR DevicePath[ANYSIZE_ARRAY]; 110 | } SP_DEVICE_INTERFACE_DETAIL_DATA, *PSP_DEVICE_INTERFACE_DETAIL_DATA; 111 | """ 112 | _pack_ = WIN_PACK 113 | _fields_ = [ \ 114 | ("cb_size", DWORD), 115 | ("device_path", TCHAR * 1) # device_path[1] 116 | ] 117 | def get_string(self): 118 | """Retreive stored string""" 119 | return ctypes.wstring_at(byref(self, sizeof(DWORD))) 120 | 121 | class SP_DEVINFO_DATA(Structure): 122 | """ 123 | typedef struct _SP_DEVINFO_DATA { 124 | DWORD cbSize; 125 | GUID ClassGuid; 126 | DWORD DevInst; 127 | ULONG_PTR Reserved; 128 | } SP_DEVINFO_DATA, *PSP_DEVINFO_DATA; 129 | """ 130 | _pack_ = WIN_PACK 131 | _fields_ = [ \ 132 | ("cb_size", DWORD), 133 | ("class_guid", GUID), 134 | ("dev_inst", DWORD), 135 | ("reserved", POINTER(ULONG)), 136 | ] 137 | 138 | 139 | SetupDiGetDeviceInterfaceDetail = setup_api.SetupDiGetDeviceInterfaceDetailW 140 | SetupDiGetDeviceInterfaceDetail.restype = BOOL 141 | SetupDiGetDeviceInterfaceDetail.argtypes = [ 142 | HANDLE, # __in HDEVINFO DeviceInfoSet, 143 | POINTER(SP_DEVICE_INTERFACE_DATA), # __in PSP_DEVICE_INTERFACE_DATA DeviceIn 144 | # __out_opt PSP_DEVICE_INTERFACE_DETAIL_DATA DeviceInterfaceDetailData, 145 | POINTER(SP_DEVICE_INTERFACE_DETAIL_DATA), 146 | DWORD, # __in DWORD DeviceInterfaceDetailDataSize, 147 | POINTER(DWORD), # __out_opt PDWORD RequiredSize, 148 | POINTER(SP_DEVINFO_DATA), # __out_opt PSP_DEVINFO_DATA DeviceInfoData 149 | ] 150 | 151 | SetupDiGetDeviceInstanceId = setup_api.SetupDiGetDeviceInstanceIdW 152 | SetupDiGetDeviceInstanceId.restype = BOOL 153 | SetupDiGetDeviceInstanceId.argtypes = [ 154 | HANDLE, # __in HDEVINFO DeviceInfoSet, 155 | POINTER(SP_DEVINFO_DATA), # __in PSP_DEVINFO_DATA DeviceInfoData, 156 | LPWSTR, # __out_opt PTSTR DeviceInstanceId, 157 | DWORD, # __in DWORD DeviceInstanceIdSize, 158 | POINTER(DWORD), # __out_opt PDWORD RequiredSize 159 | ] 160 | 161 | SetupDiGetClassDevs = setup_api.SetupDiGetClassDevsW 162 | SetupDiGetClassDevs.restype = HANDLE 163 | SetupDiGetClassDevs.argtypes = [ 164 | POINTER(GUID), # __in_opt const GUID *ClassGuid, 165 | LPCWSTR, # __in_opt PCTSTR Enumerator, 166 | HANDLE, # __in_opt HWND hwndParent, 167 | DWORD, # __in DWORD Flags 168 | ] 169 | 170 | SetupDiGetDeviceRegistryProperty = setup_api.SetupDiGetDeviceRegistryPropertyW 171 | SetupDiGetDeviceRegistryProperty.restype = BOOL 172 | SetupDiGetDeviceRegistryProperty.argtypes = [ 173 | HANDLE, # __in HDEVINFO DeviceInfoSet, 174 | POINTER(SP_DEVINFO_DATA), # __in PSP_DEVINFO_DATA DeviceInfoData, 175 | DWORD, # __in DWORD Property, 176 | POINTER(DWORD), # __out_opt PDWORD PropertyRegDataType, 177 | POINTER(BYTE), # __out_opt PBYTE PropertyBuffer, 178 | DWORD, # __in DWORD PropertyBufferSize, 179 | POINTER(DWORD), # __out_opt PDWORD RequiredSize 180 | ] 181 | 182 | SetupDiDestroyDeviceInfoList = setup_api.SetupDiDestroyDeviceInfoList 183 | SetupDiDestroyDeviceInfoList.restype = BOOL 184 | SetupDiDestroyDeviceInfoList.argtypes = [ 185 | HANDLE, # __in HDEVINFO DeviceInfoSet, 186 | ] 187 | 188 | SetupDiEnumDeviceInterfaces = setup_api.SetupDiEnumDeviceInterfaces 189 | SetupDiEnumDeviceInterfaces.restype = BOOL 190 | SetupDiEnumDeviceInterfaces.argtypes = [ 191 | HANDLE, # _In_ HDEVINFO DeviceInfoSet, 192 | POINTER(SP_DEVINFO_DATA), # _In_opt_ PSP_DEVINFO_DATA DeviceInfoData, 193 | POINTER(GUID), # _In_ const GUIDi *InterfaceClassGuid, 194 | DWORD, # _In_ DWORD MemberIndex, 195 | POINTER(SP_DEVICE_INTERFACE_DATA), # _Out_ PSP_DEVICE_INTERFACE_DATA DeviceInterfaceData 196 | ] 197 | 198 | #structures for ctypes 199 | class DIGCF: 200 | """ 201 | Flags controlling what is included in the device information set built 202 | by SetupDiGetClassDevs 203 | """ 204 | DEFAULT = 0x00000001 # only valid with DIGCF.DEVICEINTERFACE 205 | PRESENT = 0x00000002 206 | ALLCLASSES = 0x00000004 207 | PROFILE = 0x00000008 208 | DEVICEINTERFACE = 0x00000010 209 | 210 | #******* 211 | # hid.dll 212 | class HIDD_ATTRIBUTES(Structure): 213 | _fields_ = [("cb_size", DWORD), 214 | ("vendor_id", c_ushort), 215 | ("product_id", c_ushort), 216 | ("version_number", c_ushort) 217 | ] 218 | 219 | class HIDP_CAPS(Structure): 220 | _fields_ = [ 221 | ("usage", c_ushort), #usage id 222 | ("usage_page", c_ushort), #usage page 223 | ("input_report_byte_length", c_ushort), 224 | ("output_report_byte_length", c_ushort), 225 | ("feature_report_byte_length", c_ushort), 226 | ("reserved", c_ushort * 17), 227 | ("number_link_collection_nodes", c_ushort), 228 | ("number_input_button_caps", c_ushort), 229 | ("number_input_value_caps", c_ushort), 230 | ("number_input_data_indices", c_ushort), 231 | ("number_output_button_caps", c_ushort), 232 | ("number_output_value_caps", c_ushort), 233 | ("number_output_data_indices", c_ushort), 234 | ("number_feature_button_caps", c_ushort), 235 | ("number_feature_value_caps", c_ushort), 236 | ("number_feature_data_indices", c_ushort) 237 | ] 238 | 239 | class HIDP_BUTTON_CAPS(Structure): 240 | class RANGE_NOT_RANGE(Union): 241 | class RANGE(Structure): 242 | _fields_ = [ 243 | ("usage_min", c_ushort), ("usage_max", c_ushort), 244 | ("string_min", c_ushort), ("string_max", c_ushort), 245 | ("designator_min", c_ushort),("designator_max", c_ushort), 246 | ("data_index_min", c_ushort), ("data_index_max", c_ushort) 247 | ] 248 | 249 | class NOT_RANGE(Structure): 250 | _fields_ = [ 251 | ("usage", c_ushort), ("reserved1", c_ushort), 252 | ("string_index", c_ushort), ("reserved2", c_ushort), 253 | ("designator_index", c_ushort), ("reserved3", c_ushort), 254 | ("data_index", c_ushort), ("reserved4", c_ushort) 255 | ] 256 | _fields_ = [ 257 | ("range", RANGE), 258 | ("not_range", NOT_RANGE) 259 | ] 260 | 261 | _fields_ = [ 262 | ("usage_page", c_ushort), 263 | ("report_id", c_ubyte), 264 | ("is_alias", BOOLEAN), 265 | ("bit_field", c_ushort), 266 | ("link_collection", c_ushort), 267 | ("link_usage", c_ushort), 268 | ("link_usage_page", c_ushort), 269 | ("is_range", BOOLEAN), 270 | ("is_string_range", BOOLEAN), 271 | ("is_designator_range", BOOLEAN), 272 | ("is_absolute", BOOLEAN), 273 | ("reserved", c_ulong * 10), 274 | ("union", RANGE_NOT_RANGE) 275 | ] 276 | 277 | class HIDP_VALUE_CAPS(Structure): 278 | class RANGE_NOT_RANGE(Union): 279 | class RANGE(Structure): 280 | _fields_ = [ 281 | ("usage_min", c_ushort), ("usage_max", c_ushort), 282 | ("string_min", c_ushort), ("string_max", c_ushort), 283 | ("designator_min", c_ushort),("designator_max", c_ushort), 284 | ("data_index_min", c_ushort), ("data_index_max", c_ushort) 285 | ] 286 | 287 | class NOT_RANGE(Structure): 288 | _fields_ = [ 289 | ("usage", c_ushort), ("reserved1", c_ushort), 290 | ("string_index", c_ushort), ("reserved2", c_ushort), 291 | ("designator_index", c_ushort), ("reserved3", c_ushort), 292 | ("data_index", c_ushort), ("reserved4", c_ushort) 293 | ] 294 | _fields_ = [ 295 | ("range", RANGE), 296 | ("not_range", NOT_RANGE) 297 | ] 298 | 299 | _fields_ = [ 300 | ("usage_page", c_ushort), 301 | ("report_id", c_ubyte), 302 | ("is_alias", BOOLEAN), 303 | ("bit_field", c_ushort), 304 | ("link_collection", c_ushort), 305 | ("link_usage", c_ushort), 306 | ("link_usage_page", c_ushort), 307 | ("is_range", BOOLEAN), 308 | ("is_string_range", BOOLEAN), 309 | ("is_designator_range", BOOLEAN), 310 | ("is_absolute", BOOLEAN), 311 | ("has_null", BOOLEAN), 312 | ("reserved", c_ubyte), 313 | ("bit_size", c_ushort), 314 | ("report_count", c_ushort), 315 | ("reserved2", c_ushort * 5), 316 | ("units_exp", c_ulong), 317 | ("units", c_ulong), 318 | ("logical_min", c_long), 319 | ("logical_max", c_long), 320 | ("physical_min", c_long), 321 | ("physical_max", c_long), 322 | ("union", RANGE_NOT_RANGE) 323 | ] 324 | 325 | class HIDP_DATA(Structure): 326 | class HIDP_DATA_VALUE(Union): 327 | _fields_ = [ 328 | ("raw_value", c_ulong), 329 | ("on", BOOLEAN), 330 | ] 331 | 332 | _fields_ = [ 333 | ("data_index", c_ushort), 334 | ("reserved", c_ushort), 335 | ("value", HIDP_DATA_VALUE) 336 | ] 337 | 338 | #get report 339 | HidP_Input = 0x0000 340 | HidP_Output = 0x0001 341 | HidP_Feature = 0x0002 342 | 343 | FACILITY_HID_ERROR_CODE = 0x11 344 | def HIDP_ERROR_CODES(sev, code): 345 | return (((sev) << 28) | (FACILITY_HID_ERROR_CODE << 16) | (code)) & 0xFFFFFFFF 346 | 347 | class HidStatus(object): 348 | HIDP_STATUS_SUCCESS = ( HIDP_ERROR_CODES(0x0, 0) ) 349 | HIDP_STATUS_NULL = ( HIDP_ERROR_CODES(0x8, 1) ) 350 | HIDP_STATUS_INVALID_PREPARSED_DATA = ( HIDP_ERROR_CODES(0xC, 1) ) 351 | HIDP_STATUS_INVALID_REPORT_TYPE = ( HIDP_ERROR_CODES(0xC, 2) ) 352 | HIDP_STATUS_INVALID_REPORT_LENGTH = ( HIDP_ERROR_CODES(0xC, 3) ) 353 | HIDP_STATUS_USAGE_NOT_FOUND = ( HIDP_ERROR_CODES(0xC, 4) ) 354 | HIDP_STATUS_VALUE_OUT_OF_RANGE = ( HIDP_ERROR_CODES(0xC, 5) ) 355 | HIDP_STATUS_BAD_LOG_PHY_VALUES = ( HIDP_ERROR_CODES(0xC, 6) ) 356 | HIDP_STATUS_BUFFER_TOO_SMALL = ( HIDP_ERROR_CODES(0xC, 7) ) 357 | HIDP_STATUS_INTERNAL_ERROR = ( HIDP_ERROR_CODES(0xC, 8) ) 358 | HIDP_STATUS_I8042_TRANS_UNKNOWN = ( HIDP_ERROR_CODES(0xC, 9) ) 359 | HIDP_STATUS_INCOMPATIBLE_REPORT_ID = ( HIDP_ERROR_CODES(0xC, 0xA) ) 360 | HIDP_STATUS_NOT_VALUE_ARRAY = ( HIDP_ERROR_CODES(0xC, 0xB) ) 361 | HIDP_STATUS_IS_VALUE_ARRAY = ( HIDP_ERROR_CODES(0xC, 0xC) ) 362 | HIDP_STATUS_DATA_INDEX_NOT_FOUND = ( HIDP_ERROR_CODES(0xC, 0xD) ) 363 | HIDP_STATUS_DATA_INDEX_OUT_OF_RANGE = ( HIDP_ERROR_CODES(0xC, 0xE) ) 364 | HIDP_STATUS_BUTTON_NOT_PRESSED = ( HIDP_ERROR_CODES(0xC, 0xF) ) 365 | HIDP_STATUS_REPORT_DOES_NOT_EXIST = ( HIDP_ERROR_CODES(0xC, 0x10) ) 366 | HIDP_STATUS_NOT_IMPLEMENTED = ( HIDP_ERROR_CODES(0xC, 0x20) ) 367 | 368 | error_message_dict = { 369 | HIDP_STATUS_SUCCESS : "success", 370 | HIDP_STATUS_NULL : "null", 371 | HIDP_STATUS_INVALID_PREPARSED_DATA : "invalid preparsed data", 372 | HIDP_STATUS_INVALID_REPORT_TYPE : "invalid report type", 373 | HIDP_STATUS_INVALID_REPORT_LENGTH : "invalid report length", 374 | HIDP_STATUS_USAGE_NOT_FOUND : "usage not found", 375 | HIDP_STATUS_VALUE_OUT_OF_RANGE : "value out of range", 376 | HIDP_STATUS_BAD_LOG_PHY_VALUES : "bad log phy values", 377 | HIDP_STATUS_BUFFER_TOO_SMALL : "buffer too small", 378 | HIDP_STATUS_INTERNAL_ERROR : "internal error", 379 | HIDP_STATUS_I8042_TRANS_UNKNOWN : "i8042/I8242 trans unknown", 380 | HIDP_STATUS_INCOMPATIBLE_REPORT_ID : "incompatible report ID", 381 | HIDP_STATUS_NOT_VALUE_ARRAY : "not value array", 382 | HIDP_STATUS_IS_VALUE_ARRAY : "is value array", 383 | HIDP_STATUS_DATA_INDEX_NOT_FOUND : "data index not found", 384 | HIDP_STATUS_DATA_INDEX_OUT_OF_RANGE : "data index out of range", 385 | HIDP_STATUS_BUTTON_NOT_PRESSED : "button not pressed", 386 | HIDP_STATUS_REPORT_DOES_NOT_EXIST : "report does not exist", 387 | HIDP_STATUS_NOT_IMPLEMENTED : "not implemented" 388 | } 389 | 390 | def __init__(self, error_code): 391 | error_code &= 0xFFFFFFFF 392 | self.error_code = error_code 393 | if error_code != self.HIDP_STATUS_SUCCESS: 394 | if error_code in self.error_message_dict: 395 | raise helpers.HIDError("hidP error: %s" % self.error_message_dict[error_code]) 396 | else: 397 | raise helpers.HIDError("Unknown HidP error (%s)"%hex(error_code)) 398 | 399 | #***************** 400 | # kernel32 401 | # 402 | #wait for single object 403 | WAIT_ABANDONED = 0x00000080 # mutex used by another thread 404 | WAIT_OBJECT_0 = 0x00000000 # signaled 405 | WAIT_TIMEOUT = 0x00000102 # object signal timed out 406 | WAIT_FAILED = 0xFFFFFFFF #failed 407 | INFINITE = 0xFFFFFFFF 408 | 409 | GENERIC_READ = (-2147483648) 410 | GENERIC_WRITE = (1073741824) 411 | FILE_SHARE_READ = 1 412 | FILE_SHARE_WRITE = 2 413 | # 414 | OPEN_EXISTING = 3 415 | OPEN_ALWAYS = 4 416 | # 417 | INVALID_HANDLE_VALUE = HANDLE(-1) 418 | 419 | FILE_FLAG_OVERLAPPED = 1073741824 420 | FILE_ATTRIBUTE_NORMAL = 128 421 | # 422 | NO_ERROR = 0 423 | ERROR_IO_PENDING = 997 424 | 425 | def GetHidGuid(): 426 | "Get system-defined GUID for HIDClass devices" 427 | hid_guid = GUID() 428 | hid_dll.HidD_GetHidGuid(byref(hid_guid)) 429 | return hid_guid 430 | 431 | class DeviceInterfaceSetInfo(object): 432 | """Context manager for SetupDiGetClassDevs / SetupDiDestroyDeviceInfoList 433 | resource allocation / cleanup 434 | """ 435 | def __init__(self, guid_target): 436 | self.guid = guid_target 437 | self.h_info = None 438 | 439 | def __enter__(self): 440 | """Context manager initializer, calls self.open()""" 441 | return self.open() 442 | 443 | def open(self): 444 | """ 445 | Calls SetupDiGetClassDevs to obtain a handle to an opaque device 446 | information set that describes the device interfaces supported by all 447 | the USB collections currently installed in the system. The 448 | application should specify DIGCF.PRESENT and DIGCF.INTERFACEDEVICE 449 | in the Flags parameter passed to SetupDiGetClassDevs. 450 | """ 451 | self.h_info = SetupDiGetClassDevs(byref(self.guid), None, None, 452 | (DIGCF.PRESENT | DIGCF.DEVICEINTERFACE) ) 453 | 454 | return self.h_info 455 | 456 | def __exit__(self, exc_type, exc_value, traceback): 457 | """Context manager clean up, calls self.close()""" 458 | self.close() 459 | 460 | def close(self): 461 | """Destroy allocated storage""" 462 | if self.h_info and self.h_info != INVALID_HANDLE_VALUE: 463 | # clean up 464 | SetupDiDestroyDeviceInfoList(self.h_info) 465 | self.h_info = None 466 | 467 | def enum_device_interfaces(h_info, guid): 468 | """Function generator that returns a device_interface_data enumerator 469 | for the given device interface info and GUID parameters 470 | """ 471 | dev_interface_data = SP_DEVICE_INTERFACE_DATA() 472 | dev_interface_data.cb_size = sizeof(dev_interface_data) 473 | 474 | device_index = 0 475 | while SetupDiEnumDeviceInterfaces(h_info, 476 | None, 477 | byref(guid), 478 | device_index, 479 | byref(dev_interface_data) ): 480 | yield dev_interface_data 481 | device_index += 1 482 | del dev_interface_data 483 | 484 | def get_device_path(h_info, interface_data, ptr_info_data = None): 485 | """"Returns Hardware device path 486 | Parameters: 487 | h_info, interface set info handler 488 | interface_data, device interface enumeration data 489 | ptr_info_data, pointer to SP_DEVINFO_DATA() instance to receive details 490 | """ 491 | required_size = c_ulong(0) 492 | 493 | dev_inter_detail_data = SP_DEVICE_INTERFACE_DETAIL_DATA() 494 | dev_inter_detail_data.cb_size = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA) 495 | 496 | # get actual storage requirement 497 | SetupDiGetDeviceInterfaceDetail(h_info, byref(interface_data), 498 | None, 0, byref(required_size), 499 | None) 500 | ctypes.resize(dev_inter_detail_data, required_size.value) 501 | 502 | # read value 503 | SetupDiGetDeviceInterfaceDetail(h_info, byref(interface_data), 504 | byref(dev_inter_detail_data), required_size, None, 505 | ptr_info_data) 506 | 507 | # extract string only 508 | return dev_inter_detail_data.get_string() 509 | 510 | 511 | 512 | -------------------------------------------------------------------------------- /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 | --------------------------------------------------------------------------------