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

77 lines
2.3 KiB
Python

import logging
import socket
import sys
from time import sleep
import servicemanager
import win32event
import win32service
import win32serviceutil
from win32_notification_receiver import Win32NotificationReceiver
logPath = 'C:/Users/seb65/Documents/Gitea/screen_status_to_mqtt/'
logging.basicConfig(
level=logging.DEBUG,
format="%(asctime)s [%(threadName)-12.12s] [%(levelname)-5.5s] %(message)s",
handlers=[
logging.FileHandler(logPath + "debug.log"),
logging.StreamHandler()
]
)
logger = logging.getLogger()
class ScreenStatusToMqttService(win32serviceutil.ServiceFramework):
_svc_name_ = "ScreenStatusToMqtt"
_svc_display_name_ = "Screen Status To MQTT"
_svc_description_ = "Send your screen status to MQTT Broker"
win32_notification_receiver: Win32NotificationReceiver = None
running_flag = False
def __init__(self, args):
super().__init__(args)
self.hWaitStop = win32event.CreateEvent(None, 0, 0, None)
socket.setdefaulttimeout(60)
def SvcStop(self):
logger.info("Stopping Service...")
self.running_flag = False
self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
win32event.SetEvent(self.hWaitStop)
def SvcDoRun(self):
self.running_flag = True
servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE,
servicemanager.PYS_SERVICE_STARTED,
(self._svc_name_, ''))
if self.ssh is None:
logger.critical("Can't be run in debug mode !")
sys.exit(1)
else:
self.main()
def SvcOtherEx(self, control, event_type, data):
if control == win32service.SERVICE_CONTROL_POWEREVENT:
self.win32_notification_receiver.event_handler(event_type, data)
else:
logger.warning("Unsupported control: ")
logger.warning(control)
def main(self):
self.win32_notification_receiver = Win32NotificationReceiver(self.ssh)
while self.running_flag:
sleep(1)
if __name__ == '__main__':
if len(sys.argv) == 1:
servicemanager.Initialize()
servicemanager.PrepareToHostSingle(ScreenStatusToMqttService)
servicemanager.StartServiceCtrlDispatcher()
else:
win32serviceutil.HandleCommandLine(ScreenStatusToMqttService)