screen_status_to_mqtt/win32_notification_receiver.py
2022-03-11 18:56:49 +01:00

69 lines
2.3 KiB
Python

import threading
import win32con
import win32api
import win32gui
import time
import logging
from ctypes import POINTER, windll, Structure, cast, CFUNCTYPE, c_int, c_uint, c_void_p, c_bool
from comtypes import GUID
from ctypes.wintypes import HANDLE, DWORD
PBT_POWERSETTINGCHANGE = 0x8013 # 32787
GUID_CONSOLE_DISPLAY_STATE = "{6FE69556-704A-47A0-8F24-C28D936FDA47}"
GUID_MONITOR_POWER_ON = "{02731015-4510-4526-99E6-E5A17EBD1AEA}"
logger = logging.getLogger()
class Win32NotificationReceiver():
running_flag = False
def __init__(self, recipient):
super().__init__()
self.recipient = recipient
self.__prepare_win32gui_message()
def __prepare_win32gui_message(self):
guids_info = {
"GUID_MONITOR_POWER_ON": GUID_MONITOR_POWER_ON,
"GUID_CONSOLE_DISPLAY_STATE": GUID_CONSOLE_DISPLAY_STATE,
}
logger.info("----")
for name, guid_info in guids_info.items():
logger.info(self.recipient)
result = windll.user32.RegisterPowerSettingNotification(HANDLE(self.recipient), GUID(guid_info), DWORD(1))
logger.info(f'registering {name}')
logger.info(f"result: {hex(result)}")
logger.info(f"lastError: {win32api.GetLastError()}")
logger.info("----")
def event_handler(self, event_type, raw_data):
if event_type == PBT_POWERSETTINGCHANGE:
logger.debug("Power setting changed...")
logger.debug("raw_data:")
logger.debug(raw_data)
power_setting = str(raw_data[0])
logger.debug("Power Setting: ")
logger.debug(power_setting)
data = list(raw_data[1])
logger.debug("Data: ")
logger.debug(data)
if power_setting == GUID_CONSOLE_DISPLAY_STATE:
if data[0] == 0:
logger.debug("Display off")
if data[0] == 1:
logger.debug("Display on")
if data[0] == 2:
logger.debug("Display dimmed")
elif power_setting == GUID_MONITOR_POWER_ON:
if data[0] == 0:
logger.debug("Monitor off")
if data[0] == 1:
logger.debug("Monitor on")
else:
logger.warning("unknown GUID")