from bottle import Bottle,route,run,get,post,request,HTTPError,static_file,response,error,template import threading,serial,time import ConfigParser import re,sys import win32serviceutil import win32service import win32event global tlock tlock=False now = lambda: time.strftime("[%Y-%b-%d %H:%M:%S] ") class PythonService(win32serviceutil.ServiceFramework): """ Usage: 'PythonService.py [options] install|update|remove|start [...]|stop|restart [...]|debug [...]' Options for 'install' and 'update' commands only: --username domain\username : The Username the service is to run under --password password : The password for the username --startup [manual|auto|disabled|delayed] : How the service starts, default = manual --interactive : Allow the service to interact with the desktop. --perfmonini file: .ini file to use for registering performance monitor data --perfmondll file: .dll file to use when querying the service for performance data, default = perfmondata.dll Options for 'start' and 'stop' commands only: --wait seconds: Wait for the service to actually start or stop. If you specify --wait with the 'stop' option, the service and all dependent services will be stopped, each waiting the specified period. """ #服务名 _svc_name_ = "ZSHTT" #服务显示名称 _svc_display_name_ = "ZSH Touch Term Server" #服务描述 _svc_description_ = "ZRY Smart Home Touch Terminal Service." def __init__(self, args): win32serviceutil.ServiceFramework.__init__(self, args) self.hWaitStop = win32event.CreateEvent(None, 0, 0, None) self.logger = self._getLogger() self.isAlive = True def _getLogger(self): import logging import os import inspect logger = logging.getLogger('[ZSHTT]') this_file = inspect.getfile(inspect.currentframe()) dirpath = os.path.abspath(os.path.dirname(this_file)) handler = logging.FileHandler(os.path.join(dirpath, "service.log")) formatter = logging.Formatter('%(asctime)s %(name)-12s %(levelname)-8s %(message)s') handler.setFormatter(formatter) logger.addHandler(handler) logger.setLevel(logging.INFO) return logger def SvcDoRun(self): import time self.logger.error("ZSHTT Server start...") main(self) while self.isAlive: time.sleep(slp) # 等待服务被停止 #win32event.WaitForSingleObject(self.hWaitStop, win32event.INFINITE) def SvcStop(self): # 先告诉SCM停止这个过程 self.logger.error("ZSHTT Server stop...") self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING) # 设置事件 thrd.stop() try: if ser.isOpen(): ser.close() except: pass win32event.SetEvent(self.hWaitStop) self.isAlive = False def str2int(strs): strr=filter(str.isdigit,strs) if strr==None: return 0 elif strr=='': return 0 else: return int(strr) def makelog(msg): f3.write(now()+msg+"\n") f3.flush() @get("/hello") def hello(): return "

ZRY Smart Home Touch Terminal Service.

" if __name__ == '__main__': global curdir win32serviceutil.HandleCommandLine(PythonService) def main(sf): global ser,f1,f2,f3,conf,slp curdir="Z:\\Public\\Python\\Project\\ZSTerm-Server\\" f1=open(curdir+"zsterm-server.err",'a') f2=open(curdir+"zsterm-server.out",'a') f3=open(curdir+"messages.log",'a') sys.stderr=f1 sys.stdout=f2 conf=ConfigParser.ConfigParser() conf.read(curdir+"zsterm-server.conf") slp=float(conf.get('serial','wait')) ser = serial.Serial(conf.get('serial','port'),conf.get('serial','baudrate'),xonxoff=1) ser.timeout=float(conf.get('serial','timeout')) global thrd #scr=[[0]*80]*25 sf.logger.error("ready...") thrd=RunServer() sf.logger.error("create http server...") thrd.start() sf.logger.error("http server listening...") class RunServer(threading.Thread): def run(self): run(host=conf.get('httpserver','host'),port=conf.get('httpserver','port'),server='cherrypy') def stop(self): f1.flush() f2.flush() f1.close() f2.close() ser.close()