server.py 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261
  1. #!/usr/bin/env python3.5
  2. # Copyright 2017 Digital
  3. #
  4. # This file is part of BeeWatch.
  5. #
  6. # BeeWatch is free software: you can redistribute it and/or modify
  7. # it under the terms of the GNU General Public License as published by
  8. # the Free Software Foundation, either version 3 of the License, or
  9. # (at your option) any later version.
  10. #
  11. # BeeWatch is distributed in the hope that it will be useful,
  12. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. # GNU General Public License for more details.
  15. #
  16. # You should have received a copy of the GNU General Public License
  17. # along with BeeWatch. If not, see <http://www.gnu.org/licenses/>.
  18. #
  19. import argparse
  20. import gi
  21. gi.require_version('Notify', '0.7')
  22. from gi.repository import Notify
  23. import logging
  24. import logging.config
  25. import logging.handlers
  26. import sys
  27. import mylibnetwork
  28. import threading
  29. import socket
  30. import traceback
  31. import time
  32. import yaml
  33. import beewatch
  34. # import beewatch.server as beeserver
  35. import beewatch.server
  36. parser = argparse.ArgumentParser(
  37. # usage="use this to play",
  38. description="BeeWatch Server",
  39. )
  40. parser.add_argument(
  41. "host",
  42. type=str,
  43. help="hostname/ip address/filename (only if --use-file was specified)"
  44. )
  45. parser.add_argument(
  46. "port",
  47. type=int,
  48. default=80540,
  49. nargs="?",
  50. help="the port on wich the connection will open up. ignored if --use-file \
  51. is given"
  52. )
  53. parser.add_argument(
  54. "-d","--debug",
  55. default=False,
  56. action="store_true",
  57. help="enables logging"
  58. )
  59. group_af_family = parser.add_mutually_exclusive_group()
  60. group_af_family.add_argument(
  61. "-u","--af-unix",
  62. dest="af_family",
  63. # default=False,
  64. action="store_const",
  65. const="AF_UNIX",
  66. help="""use an AF_UNIX socket (a file). can't be used in combination with
  67. --af-inet."""
  68. # " will be used \
  69. # instead of an AF_INET socket (hostname/ip address + port)."
  70. )
  71. group_af_family.add_argument(
  72. "-i","--af_inet",
  73. default="AF_INET",
  74. dest="af_family",
  75. action="store_const",
  76. const="AF_INET",
  77. help="""use an AF_INET socket (hostname/ip address + port). can't be used
  78. with --af-unix"""
  79. # (hostname/ip address + port) will be used instead of an AF_INET \
  80. # socket (a file)."
  81. )
  82. args = parser.parse_args()
  83. print(args)
  84. if args.debug:
  85. with open("bee_logging.yaml") as f:
  86. data = f.read()
  87. config = yaml.safe_load(data)
  88. logging.config.dictConfig(config)
  89. if args.af_family == "AF_UNIX":
  90. port = None
  91. elif args.af_family == "AF_INET":
  92. port = args.port
  93. bee_server = beewatch.server.BeeWatchServer(
  94. host=args.host,
  95. port=args.port,
  96. af_family=args.af_family,
  97. )
  98. # bee_api = beeserver.BeeAPI()
  99. # s = mylibnetwork.Server(
  100. # host=args.host,
  101. # port=port,
  102. # handler=beeserver.ConnHandlerBeeWatch,
  103. # handler_kwargs={"bee_api":bee_api}
  104. # )
  105. bee_server.run()
  106. try:
  107. while True:
  108. try:
  109. if bee_server.is_alive():
  110. bee_server.join(1)
  111. else:
  112. break
  113. except Exception as e:
  114. log.warn("an error occured, aborting")
  115. log.error(e, exc_info=True)
  116. bee_server.stop()
  117. break
  118. except KeyboardInterrupt:
  119. print("\r ", end="\r")
  120. logging.warn("keyboardinterrupt! aborting!")
  121. bee_server.stop()
  122. sys.exit()
  123. log = logging.getLogger(__name__+".server")
  124. logc = logging.getLogger(__name__+".chat")
  125. Notify.init("Bee Watch Server")
  126. #
  127. # class ConnHandlerBeeWatch(mylibnetwork.ConnHandlerBase):
  128. # def __init__(self, socket, addr, server, action=None):
  129. # self.status = "init"
  130. # self.super_class = super(ConnHandlerBeeWatch, self)
  131. # self.super_class.__init__(socket, addr, server)
  132. # logc.info('hey')
  133. # self.server = server
  134. # self.address = addr
  135. # self.action=action
  136. # self.command_to_function={
  137. # "set_speed":self.action.c.movement_control.set_speed,
  138. # "mod_speed":self.action.c.movement_control.change_speed,
  139. # "get_speed":self.speedcheck,
  140. # "print":self.echo,
  141. # "None":None,
  142. # }
  143. # def welcome_client(self):
  144. # self.send("this is the server speaking, hello new client!")
  145. # def handle(self, data_decoded):
  146. # data_decoded=data_decoded.strip()
  147. # logc.info("Client:"+data_decoded)
  148. # if data_decoded.find(" ") != -1:
  149. # cmd=data_decoded.split()[0]
  150. # args=data_decoded.split()[1:]
  151. # else:
  152. # cmd=data_decoded
  153. # args=()
  154. # kwargs={}
  155. # if cmd in self.command_to_function.keys():
  156. # try:
  157. # # self.respond(str(args))
  158. # self.command_to_function[cmd](respond_method=self.respond,*args)
  159. # except:
  160. # tb = traceback.format_exc()
  161. # print(tb)
  162. # self.respond(tb)
  163. # # for line in tb.split('\n'):
  164. # # self.respond(line)
  165. # # # print(line)
  166. # # # time.sleep(0.001)
  167. # # time.sleep(0.1)
  168. # # # if line != "\n"
  169. # else:
  170. # self.respond("Unknown command")
  171. # # Notify.Notification.new(
  172. # # self.address[0]+" ("+self.server.host+":"+str(self.server.port)+")",
  173. # # data_decoded
  174. # # ).show()
  175. # def echo(self,*args,**kwargs):
  176. # logc.info(str(args))
  177. # logc.info(str(kwargs))
  178. # def speedcheck(self,respond_method):
  179. # left_speed=str(self.action.c.movement_control.get_speed("left"))
  180. # right_speed=str(self.action.c.movement_control.get_speed("right"))
  181. # result = "left: "+left_speed+", right: "+right_speed
  182. # logc.info(result)
  183. # self.respond(result)
  184. # def respond(self,text,*args):
  185. # self.send(text)
  186. #
  187. # # logging.basicConfig(
  188. # # format = myLogger.fmt + " {process:^^20}",
  189. # # datefmt = myLogger.datefmt,
  190. # # style = "{",
  191. # # level = logging.DEBUG,
  192. # # handlers = [
  193. # # myLogger.logHandler_console,
  194. # # ]
  195. # # )
  196. # # logger_server = logging.getLogger("server")
  197. # # logger_server.propagate = False
  198. # # logHandler_server_file = logging.handlers.WatchedFileHandler(filename="logs/server.log")
  199. # # logHandler_server_file.setFormatter(myLogger.logFormatter)
  200. # # logHandler_server_file.setLevel(level=logging.DEBUG)
  201. # # logger_server.addHandler(myLogger.logHandler_console)
  202. # # logger_server.addHandler(logHandler_server_file)
  203. # # logger_beewatch = logging.getLogger("BeeWatch")
  204. # # logger_beewatch.propagate = False
  205. # # logHandler_beewatch_file = logging.handlers.WatchedFileHandler(filename="logs/beeserver.log")
  206. # # logHandler_beewatch_file.setFormatter(myLogger.logFormatter)
  207. # # logHandler_beewatch_file.setLevel(level=logging.DEBUG)
  208. # # logger_beewatch.addHandler(myLogger.logHandler_console)
  209. # # logger_beewatch.addHandler(logHandler_beewatch_file)
  210. #
  211. #
  212. # action=beeserver.BoatAction()
  213. # boat_movement=beeserver.BoatMovement(action.boat_api)
  214. # action.add_component("movement_control",boat_movement)
  215. # # engine_left=beeserver.Engine(logger_beewatch,action,{"name":"engine_left"})
  216. # # engine_right=beeserver.Engine(logger_beewatch,action,{"name":"engine_right"})
  217. # # action.add_component("engine_left",engine_left)
  218. # # action.add_component("engine_right",engine_right)
  219. # argv_dict = dict(zip(range(0,len(sys.argv)),sys.argv))
  220. # port = argv_dict.get(2,None)
  221. # if port != None:
  222. # port = int(port)
  223. # s = mylibnetwork.Server(
  224. # host=sys.argv[1],
  225. # port=port,
  226. # handler=ConnHandlerBeeWatch,
  227. # handler_kwargs={"action":action}
  228. # )
  229. # bee_server.run()
  230. # while True:
  231. # try:
  232. # # print("".join(myLogger.list_stream))
  233. # if bee_server.is_alive():
  234. # bee_server.join(1)
  235. # else:
  236. # break
  237. # except KeyboardInterrupt:
  238. # print("\r ", end="\r")
  239. # logging.warn("keyboardinterrupt! aborting!")
  240. # bee_server.stop()
  241. # break
  242. # except Exception as e:
  243. # log.warn("an error occured, aborting")
  244. # log.error(e, exc_info=True)
  245. # bee_server.stop()
  246. # break