zsterm-server.py 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136
  1. from bottle import Bottle,route,run,get,post,request,HTTPError,static_file,response,error,template
  2. import threading,serial,time
  3. import ConfigParser
  4. import re,sys
  5. import win32serviceutil
  6. import win32service
  7. import win32event
  8. global tlock
  9. tlock=False
  10. now = lambda: time.strftime("[%Y-%b-%d %H:%M:%S] ")
  11. class PythonService(win32serviceutil.ServiceFramework):
  12. """
  13. Usage: 'PythonService.py [options] install|update|remove|start [...]|stop|restart [...]|debug [...]'
  14. Options for 'install' and 'update' commands only:
  15. --username domain\username : The Username the service is to run under
  16. --password password : The password for the username
  17. --startup [manual|auto|disabled|delayed] : How the service starts, default = manual
  18. --interactive : Allow the service to interact with the desktop.
  19. --perfmonini file: .ini file to use for registering performance monitor data
  20. --perfmondll file: .dll file to use when querying the service for
  21. performance data, default = perfmondata.dll
  22. Options for 'start' and 'stop' commands only:
  23. --wait seconds: Wait for the service to actually start or stop.
  24. If you specify --wait with the 'stop' option, the service
  25. and all dependent services will be stopped, each waiting
  26. the specified period.
  27. """
  28. #服务名
  29. _svc_name_ = "ZSHTT"
  30. #服务显示名称
  31. _svc_display_name_ = "ZSH Touch Term Server"
  32. #服务描述
  33. _svc_description_ = "ZRY Smart Home Touch Terminal Service."
  34. def __init__(self, args):
  35. win32serviceutil.ServiceFramework.__init__(self, args)
  36. self.hWaitStop = win32event.CreateEvent(None, 0, 0, None)
  37. self.logger = self._getLogger()
  38. self.isAlive = True
  39. def _getLogger(self):
  40. import logging
  41. import os
  42. import inspect
  43. logger = logging.getLogger('[ZSHTT]')
  44. this_file = inspect.getfile(inspect.currentframe())
  45. dirpath = os.path.abspath(os.path.dirname(this_file))
  46. handler = logging.FileHandler(os.path.join(dirpath, "service.log"))
  47. formatter = logging.Formatter('%(asctime)s %(name)-12s %(levelname)-8s %(message)s')
  48. handler.setFormatter(formatter)
  49. logger.addHandler(handler)
  50. logger.setLevel(logging.INFO)
  51. return logger
  52. def SvcDoRun(self):
  53. import time
  54. self.logger.error("ZSHTT Server start...")
  55. main(self)
  56. while self.isAlive:
  57. time.sleep(slp)
  58. # 等待服务被停止
  59. #win32event.WaitForSingleObject(self.hWaitStop, win32event.INFINITE)
  60. def SvcStop(self):
  61. # 先告诉SCM停止这个过程
  62. self.logger.error("ZSHTT Server stop...")
  63. self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
  64. # 设置事件
  65. thrd.stop()
  66. try:
  67. if ser.isOpen():
  68. ser.close()
  69. except:
  70. pass
  71. win32event.SetEvent(self.hWaitStop)
  72. self.isAlive = False
  73. def str2int(strs):
  74. strr=filter(str.isdigit,strs)
  75. if strr==None:
  76. return 0
  77. elif strr=='':
  78. return 0
  79. else:
  80. return int(strr)
  81. def makelog(msg):
  82. f3.write(now()+msg+"\n")
  83. f3.flush()
  84. @get("/hello")
  85. def hello():
  86. return "<h1>ZRY Smart Home Touch Terminal Service.</h1>"
  87. if __name__ == '__main__':
  88. global curdir
  89. win32serviceutil.HandleCommandLine(PythonService)
  90. def main(sf):
  91. global ser,f1,f2,f3,conf,slp
  92. curdir="Z:\\Public\\Python\\Project\\ZSTerm-Server\\"
  93. f1=open(curdir+"zsterm-server.err",'a')
  94. f2=open(curdir+"zsterm-server.out",'a')
  95. f3=open(curdir+"messages.log",'a')
  96. sys.stderr=f1
  97. sys.stdout=f2
  98. conf=ConfigParser.ConfigParser()
  99. conf.read(curdir+"zsterm-server.conf")
  100. slp=float(conf.get('serial','wait'))
  101. ser = serial.Serial(conf.get('serial','port'),conf.get('serial','baudrate'),xonxoff=1)
  102. ser.timeout=float(conf.get('serial','timeout'))
  103. global thrd
  104. #scr=[[0]*80]*25
  105. sf.logger.error("ready...")
  106. thrd=RunServer()
  107. sf.logger.error("create http server...")
  108. thrd.start()
  109. sf.logger.error("http server listening...")
  110. class RunServer(threading.Thread):
  111. def run(self):
  112. run(host=conf.get('httpserver','host'),port=conf.get('httpserver','port'),server='cherrypy')
  113. def stop(self):
  114. f1.flush()
  115. f2.flush()
  116. f1.close()
  117. f2.close()
  118. ser.close()