91 lines
2.8 KiB
Python
91 lines
2.8 KiB
Python
import logging
|
|
import socket
|
|
import sys
|
|
from pathlib import Path
|
|
from time import sleep
|
|
|
|
import servicemanager
|
|
import win32event
|
|
import win32service
|
|
import win32serviceutil
|
|
|
|
import app_path
|
|
from mqtt_client import MqttClient
|
|
from win32_notification_receiver import Win32NotificationReceiver
|
|
|
|
Path(app_path.base_pash).mkdir(parents=True, exist_ok=True)
|
|
|
|
logging.basicConfig(
|
|
level=logging.DEBUG,
|
|
format="%(asctime)s [%(name)-12.12s] [%(levelname)-5.5s] %(message)s",
|
|
handlers=[
|
|
logging.FileHandler(app_path.log_path),
|
|
logging.StreamHandler()
|
|
]
|
|
)
|
|
|
|
logger = logging.getLogger("Main")
|
|
|
|
|
|
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
|
|
mqtt_client: MqttClient = 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.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
|
|
self.mqtt_client.disconnect()
|
|
win32event.SetEvent(self.hWaitStop)
|
|
self.running_flag = False
|
|
|
|
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):
|
|
logger.info("********************** Starting Service ********************** ")
|
|
try:
|
|
self.mqtt_client = MqttClient("ScreenStatusMQTT")
|
|
self.mqtt_client.init_connection()
|
|
|
|
self.win32_notification_receiver = Win32NotificationReceiver(self.ssh, self.mqtt_client)
|
|
except Exception:
|
|
logger.exception("Error during init:")
|
|
sys.exit(1)
|
|
|
|
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)
|