Skip to content

Commit

Permalink
persist als enabled setting
Browse files Browse the repository at this point in the history
  • Loading branch information
aarron-lee committed Apr 24, 2024
1 parent ef5d4c8 commit 57b1ce1
Show file tree
Hide file tree
Showing 4 changed files with 93 additions and 31 deletions.
7 changes: 7 additions & 0 deletions main.py
Original file line number Diff line number Diff line change
Expand Up @@ -159,6 +159,13 @@ async def set_charge_limit(self, enabled):
except Exception as e:
decky_plugin.logger.error(f'error while setting charge limit {e}')

async def set_als_enabled(self, enabled):
try:
settings.set_setting('alsEnabled', enabled)
except Exception as e:
decky_plugin.logger.error(f'error while setting als {e}')


async def remap_button(self, button: str, action: str):
decky_plugin.logger.info(f"remap_button {button} {action}")
controller_code = None
Expand Down
22 changes: 15 additions & 7 deletions src/backend/utils.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,14 +8,14 @@ export enum ServerAPIMethods {
LOG_INFO = 'log_info',
GET_SETTINGS = 'get_settings',
SET_POWER_LED = 'set_power_led',
SET_CHARGE_LIMIT = 'set_charge_limit'
SET_CHARGE_LIMIT = 'set_charge_limit',
SET_ALS_ENABLED = 'set_als_enabled'
}

const readAls =
(serverApi: ServerAPI) => async () => {
const { result } = await serverApi.callPluginMethod('read_als', {});
return Number(result);
};
const readAls = (serverApi: ServerAPI) => async () => {
const { result } = await serverApi.callPluginMethod('read_als', {});
return Number(result);
};

const createRgbOn =
(serverAPI: ServerAPI) => async (controller: ControllerType) => {
Expand Down Expand Up @@ -60,6 +60,13 @@ const createSetChargeLimit =
});
};

const createSetAlsEnabled =
(serverAPI: ServerAPI) => async (enabled: boolean) => {
await serverAPI.callPluginMethod(ServerAPIMethods.SET_ALS_ENABLED, {
enabled
});
};

const createGetSettings = (serverAPI: ServerAPI) => async () => {
return await serverAPI.callPluginMethod(ServerAPIMethods.GET_SETTINGS, {});
};
Expand Down Expand Up @@ -89,7 +96,8 @@ export const createServerApiHelpers = (serverAPI: ServerAPI) => {
getSettings: createGetSettings(serverAPI),
setPowerLed: createSetPowerLed(serverAPI),
setChargeLimit: createSetChargeLimit(serverAPI),
readAls: readAls(serverAPI)
readAls: readAls(serverAPI),
setAlsEnabled: createSetAlsEnabled(serverAPI)
};
};

Expand Down
71 changes: 51 additions & 20 deletions src/components/als/ALSPanel.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,17 +6,36 @@ import {
} from 'decky-frontend-lib';

import { useState, useEffect } from 'react';
import { getServerApi, createServerApiHelpers, logInfo } from '../../backend/utils';
import {
getServerApi,
createServerApiHelpers,
logInfo
} from '../../backend/utils';
import { useDispatch, useSelector } from 'react-redux';
import { selectAlsEnabled, uiSlice } from '../../redux-modules/uiSlice';

let currentBrightness = 40;

const useAlsEnabled = () => {
const enabledAls = useSelector(selectAlsEnabled);
const dispatch = useDispatch();

const setAlsEnabled = (enabled: boolean) => {
return dispatch(uiSlice.actions.setAlsEnabled(enabled));
};

return { enabledAls, setAlsEnabled };
};

export default function () {
const [enabledAls, setAlsEnabled] = useState(false);
const { enabledAls, setAlsEnabled } = useAlsEnabled();

const previousAlsValues = [-1, -1, -1, -1];

const serverApi = getServerApi();
const { readAls } = serverApi ? createServerApiHelpers(serverApi) : { readAls: async () => null };
const { readAls } = serverApi
? createServerApiHelpers(serverApi)
: { readAls: async () => null };

// Brightness steps
// [ALS delta, brightness add in %]
Expand All @@ -31,7 +50,8 @@ export default function () {
const stepCount = 10;
const ignoreThreshold = 30;

const sleep = (ms: number) => new Promise(resolve => setTimeout(resolve, ms));
const sleep = (ms: number) =>
new Promise((resolve) => setTimeout(resolve, ms));

const brigtnessPromise = new Promise(async (resolve) => {
while (true) {
Expand All @@ -54,8 +74,12 @@ export default function () {
//logInfo(`ALS value: ${alsValue}`);

// Set the initial values
if (previousAlsValues[0] === -1 || previousAlsValues[1] === -1
|| previousAlsValues[2] === -1 || previousAlsValues[3] === -1) {
if (
previousAlsValues[0] === -1 ||
previousAlsValues[1] === -1 ||
previousAlsValues[2] === -1 ||
previousAlsValues[3] === -1
) {
continue;
}

Expand All @@ -68,7 +92,9 @@ export default function () {
alsDeltas.push(previousAlsValues[i + 1] - previousAlsValues[i]);
}

const delta = Math.round(alsDeltas.reduce((acc, val) => acc + val, 0) / alsDeltas.length);
const delta = Math.round(
alsDeltas.reduce((acc, val) => acc + val, 0) / alsDeltas.length
);
const absDelta = Math.abs(delta);

// Ignore small changes
Expand Down Expand Up @@ -101,13 +127,18 @@ export default function () {

// Smoothing
let localCurrentBrightness = currentBrightness;
const brightnessPerMs = brightnessAdd / smoothTime * stepCount;
const brightnessPerMs = (brightnessAdd / smoothTime) * stepCount;

for (let i = 0; i < smoothTime / stepCount; i++) {
localCurrentBrightness += brightnessPerMs;
localCurrentBrightness = Math.min(100, Math.max(0, localCurrentBrightness));
localCurrentBrightness = Math.min(
100,
Math.max(0, localCurrentBrightness)
);

window.SteamClient.System.Display.SetBrightness(localCurrentBrightness / 100);
window.SteamClient.System.Display.SetBrightness(
localCurrentBrightness / 100
);

await sleep(smoothTime / stepCount);

Expand All @@ -120,11 +151,12 @@ export default function () {
});

useEffect(() => {
const registration = window.SteamClient.System.Display.RegisterForBrightnessChanges(
async (data: { flBrightness: number }) => {
currentBrightness = data.flBrightness * 100;
}
);
const registration =
window.SteamClient.System.Display.RegisterForBrightnessChanges(
async (data: { flBrightness: number }) => {
currentBrightness = data.flBrightness * 100;
}
);

return () => {
registration.unregister();
Expand All @@ -136,17 +168,16 @@ export default function () {
brigtnessPromise.then(() => {
logInfo('Brightness promise resolved');
});
}
};
}, []);

const handleAlsEnabled = (enabled: boolean) => {
setAlsEnabled(enabled);

}
};

return (
<>
<PanelSection title='Ambient Light Sensor'>
<PanelSection title="Ambient Light Sensor">
<PanelSectionRow>
<ToggleField
label={'Enable ALS'}
Expand All @@ -157,4 +188,4 @@ export default function () {
</PanelSection>
</>
);
};
}
24 changes: 20 additions & 4 deletions src/redux-modules/uiSlice.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { RootState } from './store';
import {
createServerApiHelpers,
extractDisplayName,
getServerApi,
getServerApi
} from '../backend/utils';
// import type { RootState } from './store';

Expand All @@ -14,6 +14,7 @@ type UiStateType = {
currentGameId: undefined | string;
currentDisplayName: undefined | string;
chargeLimitEnabled?: boolean;
alsEnabled?: boolean;
pluginVersionNum?: string;
};

Expand All @@ -35,6 +36,9 @@ export const uiSlice = createSlice({
},
setChargeLimit(state, action: PayloadAction<boolean>) {
state.chargeLimitEnabled = action.payload;
},
setAlsEnabled(state, action: PayloadAction<boolean>) {
state.alsEnabled = action.payload;
}
},
extraReducers: (builder) => {
Expand All @@ -46,6 +50,9 @@ export const uiSlice = createSlice({
if (action.payload?.chargeLimitEnabled) {
state.chargeLimitEnabled = Boolean(action.payload?.chargeLimitEnabled);
}
if (action.payload?.alsEnabled) {
state.alsEnabled = Boolean(action.payload?.alsEnabled);
}
});
builder.addCase(setCurrentGameId, (state, action) => {
if (action?.payload) {
Expand All @@ -70,17 +77,26 @@ export const selectCurrentGameDisplayName = (state: RootState) =>
export const selectChargeLimitEnabled = (state: RootState) =>
Boolean(state.ui?.chargeLimitEnabled);

export const selectAlsEnabled = (state: RootState) =>
Boolean(state.ui?.alsEnabled);

export const uiSliceMiddleware =
(_store: any) => (next: any) => (action: any) => {
const { type } = action;
const serverApi = getServerApi();

const result = next(action);

if (type === uiSlice.actions.setChargeLimit.type && serverApi) {
const { setChargeLimit } = createServerApiHelpers(serverApi);
if (serverApi) {
const { setChargeLimit, setAlsEnabled } =
createServerApiHelpers(serverApi);

setChargeLimit(action.payload);
if (type === uiSlice.actions.setChargeLimit.type && serverApi) {
setChargeLimit(action.payload);
}
if (type === uiSlice.actions.setAlsEnabled.type && serverApi) {
setAlsEnabled(action.payload);
}
}

return result;
Expand Down

0 comments on commit 57b1ce1

Please sign in to comment.