diff --git a/main.py b/main.py index e7819f5..1cdc206 100644 --- a/main.py +++ b/main.py @@ -21,7 +21,7 @@ logging.basicConfig( logger = logging.getLogger() logger.setLevel(logging.DEBUG) logging.info(f"PowerTools v{VERSION} https://github.com/NGnius/PowerTools") -logging.info(f"CWD: {os.getcwd()} HOME:{HOME_DIR}") +logging.debug(f"CWD: {os.getcwd()} HOME:{HOME_DIR}") import sys #import pathlib @@ -129,8 +129,7 @@ class Plugin: auto_fan = True persistent = True modified_settings = False - current_game = None # None means main menu - last_recognised_game = None + current_gameid = None async def get_version(self) -> str: return VERSION @@ -265,47 +264,44 @@ class Plugin: if settings is None or settings["persistent"] == False: logging.debug("Ignoring settings from file") self.persistent = False - self.cpus = [] - - for cpu_number in range(0, Plugin.CPU_COUNT): - self.cpus.append(CPU(cpu_number)) - - # If any core has two threads, smt is True - self.smt = self.cpus[1].status() - if(not self.smt): - for cpu_number in range(2, len(self.cpus), 2): - if(self.cpus[cpu_number].status()): - self.smt = True - break - logging.info(f"SMT state is guessed to be {self.smt}") - + self.guess_settings(self) + self.modified_settings = True else: # apply settings logging.debug("Restoring settings from file") self.persistent = True - # CPU - self.cpus = [] - - for cpu_number in range(0, Plugin.CPU_COUNT): - self.cpus.append(CPU(cpu_number, settings=settings["cpu"]["threads"][cpu_number])) - self.smt = settings["cpu"]["smt"] - write_cpu_boost(settings["cpu"]["boost"]) - # GPU - write_gpu_ppt(1, settings["gpu"]["slowppt"]) - write_gpu_ppt(2, settings["gpu"]["fastppt"]) - # Fan - if not (os.path.exists(FANTASTIC_INSTALL_DIR) or settings["fan"]["auto"]): - write_to_sys("/sys/class/hwmon/hwmon5/recalculate", 1) - write_to_sys("/sys/class/hwmon/hwmon5/fan1_target", settings["fan"]["target"]) - self.dirty = False + self.apply_settings(self, settings) + # self.modified_settings = False logging.info("Handled saved settings, back-end startup complete") # server setup await pt_server.start(VERSION) # work loop while True: + # persistence if self.modified_settings and self.persistent: self.save_settings(self) self.modified_settings = False + if self.persistent: + # per-game profiles + current_game = pt_server.http_server.game() + old_gameid = self.current_gameid + if current_game is not None and current_game.has_settings(): + self.current_gameid = current_game.gameid + if old_gameid != self.current_gameid: + logging.info(f"Applying custom settings for {current_game.name()} {current_game.appid()}") + # new game; apply settings + settings = current_game.load_settings() + if settings is not None: + self.apply_settings(self, settings) + else: + self.current_gameid = None + if old_gameid != self.current_gameid: + logging.info("Reapplying default settings; game without custom settings found") + # game without custom settings; apply defaults + settings = read_json(DEFAULT_SETTINGS_LOCATION) + self.apply_settings(self, settings) + logging.debug(f"gameid update: {old_gameid} -> {self.current_gameid}") + await asyncio.sleep(1) await pt_server.shutdown() @@ -356,8 +352,44 @@ class Plugin: def save_settings(self): settings = self.current_settings(self) - logging.info(f"Saving settings to file: {settings}") - write_json(DEFAULT_SETTINGS_LOCATION, settings) + logging.debug(f"Saving settings to file: {settings}") + current_game = pt_server.http_server.game() + if current_game is not None and self.current_gameid is not None: + save_location = current_game.settings_path() + else: + save_location = DEFAULT_SETTINGS_LOCATION + write_json(save_location, settings) + logging.info(f"Saved settings to {save_location}") + + def apply_settings(self, settings: dict): + # CPU + self.cpus = [] + + for cpu_number in range(0, Plugin.CPU_COUNT): + self.cpus.append(CPU(cpu_number, settings=settings["cpu"]["threads"][cpu_number])) + self.smt = settings["cpu"]["smt"] + write_cpu_boost(settings["cpu"]["boost"]) + # GPU + write_gpu_ppt(1, settings["gpu"]["slowppt"]) + write_gpu_ppt(2, settings["gpu"]["fastppt"]) + # Fan + if not (os.path.exists(FANTASTIC_INSTALL_DIR) or settings["fan"]["auto"]): + write_to_sys("/sys/class/hwmon/hwmon5/recalculate", 1) + write_to_sys("/sys/class/hwmon/hwmon5/fan1_target", settings["fan"]["target"]) + + def guess_settings(self): + self.cpus = [] + for cpu_number in range(0, Plugin.CPU_COUNT): + self.cpus.append(CPU(cpu_number)) + + # If any core has two threads, smt is True + self.smt = self.cpus[1].status() + if(not self.smt): + for cpu_number in range(2, len(self.cpus), 2): + if(self.cpus[cpu_number].status()): + self.smt = True + break + logging.info(f"SMT state is guessed to be {self.smt}") # per-game profiles @@ -368,6 +400,17 @@ class Plugin: else: return f"{current_game.name()} ({current_game.appid()})" + async def set_per_game_profile(self, enabled: bool): + current_game = pt_server.http_server.game() + if enabled and self.persistent and current_game is not None: + self.current_gameid = current_game.gameid + self.modified_settings = True + else: + self.current_gameid = None + + async def get_per_game_profile(self) -> bool: + return self.current_gameid is not None + # these are stateless (well, the state is not saved internally) functions, so there's no need for these to be called like a class method diff --git a/main_view.html b/main_view.html index 5ed1539..49fea6d 100644 --- a/main_view.html +++ b/main_view.html @@ -82,6 +82,14 @@ return call_plugin_method("get_persistent", {}); } + function setPerGameProfile(value) { + return call_plugin_method("set_per_game_profile", {"enabled": value}); + } + + function getPerGameProfile() { + return call_plugin_method("get_per_game_profile", {}); + } + function getCurrentGame() { return call_plugin_method("get_current_game", {}); } @@ -94,7 +102,8 @@ // detect game starts and exits console.log("Injecting game detection code into main window (SP)"); await execute_in_tab("SP", false, - `SteamClient.Apps.RegisterForGameActionStart((actionType, data) => { + `console.log("Hey PowerTools is over here now too!"); + SteamClient.Apps.RegisterForGameActionStart((actionType, data) => { console.log("start game", appStore.GetAppOverviewByGameID(data)); fetch("http://127.0.0.1:5030/on_game_start/" + data.toString(), {method: "POST", body: JSON.stringify(appStore.GetAppOverviewByGameID(data))}).then((_) => {}); }); @@ -110,6 +119,35 @@ });*/` ); + await updateCurrentGame(); + /*let boostToggle = document.getElementById("boostToggle"); + setToggleState(boostToggle, await getCPUBoost()); + setToggleState(document.getElementById("smtToggle"), await getSMT()); + selectNotch("cpuThreadsNotch", await getCPUs() - 1, 8); + selectNotch("frequencyNotch", await getMaxBoost(), 3); + await onReadyGPU(); + let isFantasticInstalled = await getFantastic(); + if (isFantasticInstalled) { + // Don't fight with Fantastic + let fanRoot = document.getElementById("fanRoot"); + fanRoot.style.visibility = "hidden"; + fanRoot.style.height = "0px"; + } else { + selectNotch("fanNotch", await getFanTick(), 8); + } + await updateBatteryStats(); + setToggleState(document.getElementById("persistToggle"), await getPersistent()); + setToggleState(document.getElementById("gameProfileToggle"), await getPerGameProfile()); + await updateCurrentGame();*/ + // this is unimportant; always do it last + await updateVersion(); + window.setInterval(function() { + updateBatteryStats().then(_ => {}); + updateCurrentGame().then(_ => {}); + }, 1000); + } + + async function reloadSettings() { let boostToggle = document.getElementById("boostToggle"); setToggleState(boostToggle, await getCPUBoost()); setToggleState(document.getElementById("smtToggle"), await getSMT()); @@ -127,12 +165,7 @@ } await updateBatteryStats(); setToggleState(document.getElementById("persistToggle"), await getPersistent()); - // this is unimportant; always do it last - await updateVersion(); - window.setInterval(function() { - updateBatteryStats().then(_ => {}); - updateCurrentGame().then(_ => {}); - }, 5000); + setToggleState(document.getElementById("gameProfileToggle"), await getPerGameProfile()); } async function setCPUNotch(index) { @@ -193,7 +226,7 @@ async function onSlideBoostNotch(e) { const ROOT_ID = "frequencyNotch"; - let closest = closestNotch(e, ROOT_ID, 8); + let closest = closestNotch(e, ROOT_ID, 3); await setBoostNotch(closest); } @@ -318,9 +351,23 @@ setToggleState(toggle, !isActive); } + async function toggleGameProfile() { + let toggle = document.getElementById("gameProfileToggle"); + let isActive = getToggleState(toggle); + await setPerGameProfile(!isActive); + setToggleState(toggle, await getPerGameProfile()); + } + + let lastGameName = ""; + async function updateCurrentGame() { let gameNow = document.getElementById("gameNow"); let gameNameNow = await getCurrentGame(); + if (lastGameName != gameNameNow) { + setToggleState(document.getElementById("gameProfileToggle"), await getPerGameProfile()); + await reloadSettings(); + } + lastGameName = gameNameNow gameNow.innerText = gameNameNow; } @@ -369,7 +416,7 @@ -
+
Threads
@@ -440,12 +487,12 @@ -
+
Max Frequency
-
+
@@ -485,7 +532,7 @@
GPU SlowPPT Power
-
+
@@ -511,12 +558,12 @@
-
+
GPU FastPPT Power
-
+
@@ -545,12 +592,12 @@ -
+
Fan RPM
-
+
@@ -605,7 +652,7 @@
-
+
Now (Charge)
@@ -615,7 +662,7 @@
-
+
Max (Design)
@@ -640,21 +687,34 @@
-
Restores settings after a reboot
-
-
-
Now Playing
-
-
Littlewood (894940)
+
Restores settings after an app or OS restart
+
+
+
+
+ Use per-game profile +
+
+
+
+
+
+
+
Now Playing
+
+
the bongos
+
+
+
-
+
PowerTools
diff --git a/server.py b/server.py index 28cfc7f..3ce6db6 100644 --- a/server.py +++ b/server.py @@ -3,8 +3,9 @@ import json import os import pathlib -import asyncio +# import asyncio from aiohttp import web +import aiohttp HOME_DIR = str(pathlib.Path(os.getcwd()).parent.parent.resolve()) SETTINGS_DIR = HOME_DIR + "/.config/powertools" @@ -14,6 +15,7 @@ if not os.path.exists(SETTINGS_DIR): http_runner = None http_server = None +http_site = None class GameInfo: def __init__(self, gameid: int, game_info: dict): @@ -27,17 +29,17 @@ class GameInfo: return self.game_info["display_name"] def settings_path(self) -> str: - return SETTINGS_DIR + os.pathsep + str(self.appid()) + ".json" + return SETTINGS_DIR + os.path.sep + str(self.appid()) + ".json" def load_settings(self) -> dict: settings_path = self.settings_path() - if os.exists(settings_path): + if os.path.exists(settings_path): with open(settings_path, mode="r") as f: return json.load(f) return None def has_settings(self) -> bool: - return os.exists(self.settings_path()) + return os.path.exists(self.settings_path()) class Server(web.Application): @@ -46,28 +48,27 @@ class Server(web.Application): super().__init__() self.version = version self.current_game = None - self.last_recognised_game = None self.add_routes([ web.get("/", lambda req: self.index(req)), web.post("/on_game_start/{game_id}", lambda req: self.on_game_start(req)), web.post("/on_game_exit/{game_id}", lambda req: self.on_game_exit(req)), - web.post("/on_game_exit_null", lambda req: self.on_game_exit_null(req)) + web.post("/on_game_exit_null", lambda req: self.on_game_exit_null(req)), + web.get("/self_destruct", lambda req: self.self_destruct(req)) ]) logging.debug("Server init complete") def game(self) -> GameInfo: return self.current_game - def recognised_game(self) -> GameInfo: - return self.last_recognised_game - async def index(self, request): logging.debug("Debug index page accessed") + current_game = None if self.current_game is None else self.current_game.gameid + game_info = None if self.current_game is None else self.current_game.game_info return web.json_response({ "name": "PowerTools", "version": self.version, - "latest_game_id": self.current_game, - "latest_recognised_game_id": self.last_recognised_game, + "latest_game_id": current_game, + "game_info": game_info }, headers={"Access-Control-Allow-Origin": "*"}) async def on_game_start(self, request): @@ -80,9 +81,8 @@ class Server(web.Application): except: return web.Response(text="WTF", status=400) self.current_game = GameInfo(game_id, data) - if True: # TODO check for game_id in existing profiles - self.last_recognised_game = self.current_game # only set this when profile exists - # TODO apply profile + if self.current_game.has_settings(): + self.last_recognised_game = self.current_game return web.Response(status=204, headers={"Access-Control-Allow-Origin": "*"}) async def on_game_exit(self, request): @@ -107,9 +107,21 @@ class Server(web.Application): # TODO change settings to default return web.Response(status=204, headers={"Access-Control-Allow-Origin": "*"}) + async def self_destruct(self, request): + logging.warning("Geodude self-destructed") + await shutdown() + # unreachable \/ \/ \/ + return web.Response(status=204, headers={"Access-Control-Allow-Origin": "*"}) + async def start(version): - global http_runner, http_server - loop = asyncio.get_event_loop() + global http_runner, http_server, http_site + # make sure old server has shutdown + try: + async with aiohttp.ClientSession() as session: + async with session.get('http://127.0.0.1:5030/self_destruct') as response: + await response.text() + except: + pass http_server = Server(version) http_runner = web.AppRunner(http_server) await http_runner.setup() @@ -117,8 +129,10 @@ async def start(version): await site.start() async def shutdown(): # never really called - global http_runner, http_server + global http_runner, http_server, http_site if http_runner is not None: await http_runner.cleanup() http_runner = None + http_site.stop() + http_site = None http_server = None