Skip to content

Commit

Permalink
Attempting fixes for 'object destroyed' bugs, battery limiter now per…
Browse files Browse the repository at this point in the history
…sists after restart.
  • Loading branch information
aredden committed Dec 18, 2020
1 parent f919229 commit a815160
Show file tree
Hide file tree
Showing 5 changed files with 140 additions and 38 deletions.
2 changes: 1 addition & 1 deletion electron/package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "g14controlv2-main",
"productName": "G14ControlV2-Main",
"version": "0.1.30",
"version": "0.1.31",
"description": "",
"main": "./build/electron.js",
"scripts": {
Expand Down
95 changes: 88 additions & 7 deletions electron/src/IPCEvents/BatteryListener.ts
Original file line number Diff line number Diff line change
@@ -1,23 +1,104 @@
/** @format */

import { BrowserWindow, IpcMain } from 'electron';
import { setBatteryLimiter, whichCharger } from './WMI/HardwareControl';
import {
buildAtkWmi,
setBatteryLimiter,
whichCharger,
} from './WMI/HardwareControl';
import getLogger from '../Logger';
import Shell from 'node-powershell';
import { checkTaskExists } from '../AutoLaunch';

const LOGGER = getLogger('BatteryListener');

const batteryCommand = (enabled: boolean, comnd: string) =>
enabled
? `$Action = New-ScheduledTaskAction -Execute 'Powershell.exe' -Argument '-NoProfile -WindowStyle Hidden -command "${comnd}"'
$Trigger = New-ScheduledTaskTrigger -AtLogOn
$Settings = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries
Register-ScheduledTask G14ControlBatteryLimit -Action $Action -Trigger $Trigger -Settings $Settings -RunLevel Highest`
: `Unregister-ScheduledTask -TaskName G14ControlBatteryLimit -Confirm:$false`;

export const buildBatterySaverListener = (win: BrowserWindow, ipc: IpcMain) => {
ipc.handle('setBatteryLimiter', async (event, value: number) => {
let modified = await setBatteryLimiter(value);
if (modified) {
return true;
} else {
return false;
}
await setBatteryLimiter(value);
let modd = (await setLimit(value)) as boolean;
return modd;
});

ipc.handle('isPlugged', async (event) => {
let plugType = await whichCharger();
return plugType;
});
};

const removeTask = async () => {
return new Promise((resolve) => {
let shell = new Shell({ executionPolicy: 'Bypass', noProfile: true });
shell.addCommand(
`Unregister-ScheduledTask -TaskName G14ControlBatteryLimit -Confirm:$false`
);
shell
.invoke()
.then((resul) => {
if (resul) {
LOGGER.error(
'There was a problem removing battery limit Task Scheduler command.\n' +
JSON.stringify(resul, null, 2)
);
resolve(false);
shell.dispose();
} else {
LOGGER.info(`Successfully removed previous task:\n${resul}`);
resolve(true);
shell.dispose();
}
})
.catch((err) => {
LOGGER.error(
'There was a problem removing battery limit Task Scheduler command.\n' +
JSON.stringify(err, null, 2)
);
resolve(false);
shell.dispose();
});
});
};

const setLimit = async (amt: number) => {
return new Promise(async (resolve) => {
let exist = await checkTaskExists('G14ControlBatteryLimit');
if (exist) {
await removeTask();
}
let command = buildAtkWmi('DEVS', '0x00120057', amt);
let addCommand = batteryCommand(true, command);
let sh = new Shell({
executionPolicy: 'Bypass',
noProfile: true,
});
sh.addCommand(addCommand);
sh.invoke()
.then((result) => {
if (result) {
LOGGER.info('Result of limit command: \n' + result);
resolve(true);
sh.dispose();
} else {
LOGGER.error(
'There was a problem setting battery limit Task Scheduler command.'
);
resolve(false);
sh.dispose();
}
})
.catch((err) => {
LOGGER.error(
'There was an error setting Task Scheduler task: \n' + err
);
resolve(false);
sh.dispose();
});
});
};
7 changes: 3 additions & 4 deletions electron/src/IPCEvents/WMI/HardwareControl.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,9 @@ const ps = new Shell({
inputEncoding: 'utf-8',
outputEncoding: 'utf-8',
});
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const BATTERY_AC_USBC = '0x0012006C';
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const BATTERY_AC = '0x00120061';

export const BATTERY_AC_USBC = '0x0012006C';
export const BATTERY_AC = '0x00120061';

const parseWmiObjectResult = (res: string, targetProperty?: string) => {
//@ts-ignore
Expand Down
72 changes: 47 additions & 25 deletions electron/src/electron.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ import {
powerMonitor,
ipcMain,
Notification,
remote,
} from 'electron';

import getLogger from './Logger';
Expand Down Expand Up @@ -42,7 +41,7 @@ export const setG14Config = (g14conf: G14Config) => {

if (!gotTheLock) {
LOGGER.info('Another process had the lock, quitting!');
app.quit();
app.exit();
}

const ICONPATH = is_dev
Expand Down Expand Up @@ -261,9 +260,23 @@ export async function createWindow(
}

powerMonitor.on('shutdown', () => {
let w = remote.getCurrentWindow();
w.close();
app.quit();
globalShortcut.unregisterAll();
if (hid) {
hid.close();
}
if (!tray.isDestroyed()) {
tray.destroy();
}
if (!browserWindow.isDestroyed()) {
browserWindow.destroy();
}
if (loopsAreRunning()) {
killEmitters().then((ok) => {
app.quit();
});
} else {
app.quit();
}
});

powerMonitor.on('suspend', () => {
Expand All @@ -278,34 +291,39 @@ app.on('window-all-closed', async () => {
});

app.on('before-quit', async () => {
globalShortcut.unregisterAll();
if (hid) {
hid.close();
if (gotTheLock) {
globalShortcut.unregisterAll();
if (hid) {
hid.close();
}
LOGGER.info('Keyboard shortcuts unregistered.');
LOGGER.info('Preparing to quit.');
killEmitters();
}
LOGGER.info('Keyboard shortcuts unregistered.');
LOGGER.info('Preparing to quit.');
killEmitters();
});

app.on('quit', async (evt, e) => {
LOGGER.info(`Quitting with exit code. ${e}`);
process.exit();
});

app.on('ready', async () => {
let results = await createWindow(
gotTheLock,
g14Config,
browserWindow,
tray,
trayContext,
ICONPATH,
hid
);
g14Config = results.g14Config;
tray = results.tray;
browserWindow = results.browserWindow;
trayContext = results.trayContext;
if (!gotTheLock) {
app.quit();
} else {
let results = await createWindow(
gotTheLock,
g14Config,
browserWindow,
tray,
trayContext,
ICONPATH,
hid
);
g14Config = results.g14Config;
tray = results.tray;
browserWindow = results.browserWindow;
trayContext = results.trayContext;
}
});

app.on('renderer-process-crashed', (event, webcontents, killed) => {
Expand All @@ -316,10 +334,12 @@ app.on('renderer-process-crashed', (event, webcontents, killed) => {
2
)}\nWas killed? ${killed} ... ${killed ? 'RIP' : ''}`
);
app.quit();
});

app.on('render-process-gone', (event, contents, details) => {
LOGGER.info(`Renderer Process is Gone:\n${details.reason}`);
app.quit();
});

app.on('second-instance', () => {
Expand All @@ -328,5 +348,7 @@ app.on('second-instance', () => {
if (browserWindow) {
if (browserWindow.isMinimized()) browserWindow.restore();
browserWindow.focus();
} else {
app.exit();
}
});
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "g14controlv2",
"productName": "G14ControlV2",
"version": "v0.1.30",
"version": "v0.1.31",
"description": "Management Tools for the Zephyrus G14",
"author": {
"name": "Alex Redden",
Expand Down

0 comments on commit a815160

Please sign in to comment.