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 from mqtt_client import MqttClient 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("Win32Notif") class Win32NotificationReceiver(): running_flag = False def __init__(self, recipient, mqtt_client: MqttClient): super().__init__() self.mqtt_client = mqtt_client 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") self.mqtt_client.publish_status("display", "Off") if data[0] == 1: logger.debug("Display on") self.mqtt_client.publish_status("display", "On") if data[0] == 2: logger.debug("Display dimmed") self.mqtt_client.publish_status("display", "Dimmed") elif power_setting == GUID_MONITOR_POWER_ON: if data[0] == 0: logger.debug("Monitor off") self.mqtt_client.publish_status("monitor", "OFF") if data[0] == 1: logger.debug("Monitor on") self.mqtt_client.publish_status("monitor", "ON") else: logger.warning("unknown GUID")