Archived Started Oct 2024
Battery Monitor Service
A small Python Windows service that puts a laptop to sleep whenever it is running unplugged.
- Problem
- I wanted a laptop to go to sleep automatically as soon as it is unplugged, without relying on power-plan timeouts.
- Outcome
- A Windows service that starts at boot, checks the battery's charging state every two seconds through WMI, and suspends the machine when it isn't charging.
- Stack
-
- Python
- pywin32
- WMI
- Windows services
How it works
- The script subclasses pywin32’s
ServiceFramework, so Windows manages it asBatteryMonitorService. You install, start and stop it withpython battery_monitor_service.py install|start|stop. - Every two seconds it queries
Win32_Batterythrough WMI.BatteryStatus == 2means the laptop is charging. - When the laptop isn’t charging, the service writes a message to the Windows event log and calls
SetSuspendStateinpowrprof.dllto put it to sleep.