core.py 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348
  1. import os
  2. import sys
  3. import yaml
  4. import requests
  5. import shutil
  6. from datetime import date
  7. import csv
  8. import urllib2
  9. import tornado.escape
  10. import tornado.ioloop
  11. import tornado.web
  12. import tornado.autoreload
  13. from tornado.escape import json_decode
  14. from tornado.escape import json_encode
  15. from threading import Timer
  16. import collections
  17. root = os.path.dirname(__file__)
  18. with open("config.yaml", 'r') as stream:
  19. try:
  20. #print(yaml.load(stream))
  21. config = yaml.load(stream)
  22. except yaml.YAMLError as exc:
  23. print(exc)
  24. if config == None:
  25. print("Error: Empty configuration file.")
  26. sys.exit(1)
  27. class RepeatedTimer(object):
  28. def __init__(self, interval, function, *args, **kwargs):
  29. self._timer = None
  30. self.interval = interval
  31. self.function = function
  32. self.args = args
  33. self.kwargs = kwargs
  34. self.is_running = False
  35. self.start()
  36. def _run(self):
  37. self.is_running = False
  38. self.start()
  39. self.function(*self.args, **self.kwargs)
  40. def start(self):
  41. if not self.is_running:
  42. self._timer = Timer(self.interval, self._run)
  43. self._timer.start()
  44. self.is_running = True
  45. def stop(self):
  46. self._timer.cancel()
  47. self.is_running = False
  48. def setInterval(self, interval):
  49. self.interval = interval
  50. def fetchDataADEI():
  51. if os.path.isfile(config["path"]+".mutex"):
  52. #print("Process running...")
  53. return
  54. else:
  55. #print("Created mutex")
  56. file = open(config["path"]+'.mutex', 'w+')
  57. with open("varname.yaml", 'r') as stream:
  58. try:
  59. #print(yaml.load(stream))
  60. varname = yaml.load(stream)
  61. except yaml.YAMLError as exc:
  62. print(exc)
  63. if varname == None:
  64. print("Error: Empty varname file.")
  65. os.remove(config["path"]+".mutex")
  66. return
  67. cache_data = {}
  68. for param in varname:
  69. print param
  70. dest = config['server'] + config['script']
  71. url = dest + "?" + varname[param]
  72. print url
  73. data = requests.get(url,
  74. auth=(config['username'],
  75. config['password'])).content
  76. #tmp_data = data.content
  77. last_value = data.split(",")[-1].strip()
  78. print last_value
  79. cache_data[param] = last_value
  80. with open(".tmp.yaml", 'w') as stream_tmp:
  81. stream_tmp.write(yaml.dump(cache_data, default_flow_style=False))
  82. src_file = config["path"] + ".tmp.yaml"
  83. dst_file = config["path"] + "cache.yaml"
  84. shutil.copy(src_file, dst_file)
  85. os.remove(config["path"]+".mutex")
  86. """
  87. with open("config.yaml", 'r') as stream:
  88. try:
  89. #print(yaml.load(stream))
  90. config = yaml.load(stream)
  91. except yaml.YAMLError as exc:
  92. print(exc)
  93. if config == None:
  94. print("Error: Empty configuration file.")
  95. sys.exit(1)
  96. """
  97. print "Start torrenting..."
  98. # it auto-starts, no need of rt.start()
  99. print "Debugging..."
  100. # TODO: Turn off for debug
  101. rt = RepeatedTimer(config["polling"], fetchDataADEI)
  102. class ListHandler(tornado.web.RequestHandler):
  103. def get(self):
  104. with open("cache.yaml", 'r') as stream:
  105. try:
  106. #print(yaml.load(stream))
  107. response = yaml.load(stream)
  108. except yaml.YAMLError as exc:
  109. print(exc)
  110. if response == None:
  111. response = {"error": "No data entry."}
  112. print response
  113. self.write(response)
  114. class StartHandler(tornado.web.RequestHandler):
  115. def get(self):
  116. print "Start fetchData"
  117. rt.start()
  118. class StopHandler(tornado.web.RequestHandler):
  119. def get(self):
  120. print "Stop fetchData"
  121. rt.stop()
  122. if os.path.isfile(config["path"]+".mutex"):
  123. os.remove(config["path"]+".mutex")
  124. class SetTimerHandler(tornado.web.RequestHandler):
  125. def get(self, duration):
  126. print "Set interval"
  127. rt.setInterval(float(duration))
  128. class DesignerHandler(tornado.web.RequestHandler):
  129. def get(self):
  130. print "In designer mode."
  131. with open("cache.yaml", 'r') as stream:
  132. try:
  133. #print(yaml.load(stream))
  134. cache_data = yaml.load(stream)
  135. except yaml.YAMLError as exc:
  136. print(exc)
  137. if cache_data == None:
  138. print("Error: Empty cache data file.")
  139. return
  140. print cache_data
  141. with open("style.yaml", 'r') as stream:
  142. try:
  143. #print(yaml.load(stream))
  144. style_data = yaml.load(stream)
  145. except yaml.YAMLError as exc:
  146. print(exc)
  147. data = {
  148. "cache": cache_data,
  149. "style": style_data
  150. }
  151. self.render('designer.html', data=data)
  152. class VersionHandler(tornado.web.RequestHandler):
  153. def get(self):
  154. response = {'version': '0.0.1',
  155. 'last_build': date.today().isoformat()}
  156. self.write(response)
  157. class SaveHandler(tornado.web.RequestHandler):
  158. def post(self):
  159. print self.request.body
  160. json_obj = json_decode(self.request.body)
  161. print('Post data received')
  162. with open("style.yaml", 'w') as output:
  163. output.write(yaml.safe_dump(json_obj, encoding='utf-8', allow_unicode=True, default_flow_style=False))
  164. response = {"success": "Data entry inserted."}
  165. #self.write(json.dumps(response))
  166. class StatusHandler(tornado.web.RequestHandler):
  167. def get(self):
  168. print "In status mode."
  169. with open("style.yaml", 'r') as stream:
  170. try:
  171. #print(yaml.load(stream))
  172. style_data = yaml.load(stream)
  173. except yaml.YAMLError as exc:
  174. print(exc)
  175. if style_data == None:
  176. print("Error: Empty style data file.")
  177. return
  178. data = {
  179. "style": style_data
  180. }
  181. self.render('status.html', data=data)
  182. class AdeiKatrinHandler(tornado.web.RequestHandler):
  183. def get(self, **params):
  184. #print params
  185. sensor_name = str(params["sensor_name"])
  186. """
  187. {'db_group': u'320_KRY_Kryo_4K_CurLead',
  188. 'db_name': u'ControlSystem_CPS',
  189. 'sensor_name': u'320-RTP-8-1103',
  190. 'db_server': u'cscps',
  191. 'control_group': u'320_KRY_Kryo_3K'}
  192. """
  193. if config["type"] != "adei":
  194. print("Error: Wrong handler.")
  195. return
  196. #print config
  197. dest = config['server'] + config['script']
  198. query_cmds = []
  199. query_cmds.append("db_server="+str(params['db_server']))
  200. query_cmds.append("db_name="+str(params['db_name']))
  201. query_cmds.append("db_group="+str(params['db_group']))
  202. query_cmds.append("db_mask=all")
  203. query_cmds.append("window=-1")
  204. query = "&".join(query_cmds)
  205. url = dest + "?" + query
  206. #print url
  207. # get the db_masks
  208. # store the query command in varname
  209. data = requests.get(url, auth=(config['username'], config['password']))
  210. cr = data.content
  211. cr = cr.split(",")
  212. print cr, len(cr)
  213. # parameter name stored in ADEI with '-IST_Val' suffix
  214. match_token = params['sensor_name'] + "-IST_Val"
  215. db_mask = None
  216. for i, item in enumerate(cr):
  217. if item.strip() == match_token:
  218. db_mask = i - 1
  219. if db_mask == None:
  220. response = {"Error": "Cannot find variable on ADEI server."}
  221. self.write(response)
  222. return
  223. query_cmds.append("db_mask="+str(db_mask))
  224. query = "&".join(query_cmds)
  225. # column name available
  226. # store in yaml file
  227. with open("varname.yaml", 'r') as stream:
  228. try:
  229. #print(yaml.load(stream))
  230. cache_data = yaml.load(stream)
  231. except yaml.YAMLError as exc:
  232. print(exc)
  233. #print "CHECK THIS"
  234. #print sensor_name, query
  235. #print cache_data
  236. if cache_data == None:
  237. cache_data = {}
  238. cache_data[sensor_name] = query
  239. else:
  240. if sensor_name not in cache_data:
  241. cache_data[sensor_name] = query
  242. else:
  243. response = {"Error": "Variable already available in varname file."}
  244. self.write(response)
  245. return
  246. with open("varname.yaml", 'w') as output:
  247. output.write(yaml.dump(cache_data, default_flow_style=False))
  248. response = {"success": "Data entry inserted."}
  249. #print match_token, db_mask
  250. self.write(response)
  251. class GetDataHandler(tornado.web.RequestHandler):
  252. def get(self):
  253. with open("cache.yaml", 'r') as stream:
  254. try:
  255. #print(yaml.load(stream))
  256. cache_data = yaml.load(stream)
  257. except yaml.YAMLError as exc:
  258. print(exc)
  259. print("GetData:")
  260. if cache_data == None:
  261. cache_data = {}
  262. print cache_data
  263. self.write(cache_data)
  264. application = tornado.web.Application([
  265. (r"/version", VersionHandler),
  266. (r"/list", ListHandler),
  267. (r"/start", StartHandler),
  268. (r"/stop", StopHandler),
  269. (r"/designer", DesignerHandler),
  270. (r"/status", StatusHandler),
  271. (r"/save/", SaveHandler),
  272. (r"/getdata/", GetDataHandler),
  273. (r"/timer/(?P<duration>[^\/]+)/?", SetTimerHandler),
  274. (r"/add/(?P<db_server>[^\/]+)/?(?P<db_name>[^\/]+)/?(?P<db_group>[^\/]+)/?(?P<sensor_name>[^\/]+)?", AdeiKatrinHandler)
  275. ], debug=True, static_path=os.path.join(root, 'static'), js_path=os.path.join(root, 'js'))
  276. if __name__ == "__main__":
  277. application.listen(8888)
  278. tornado.autoreload.start()
  279. #tornado.autoreload.watch('myfile')
  280. tornado.ioloop.IOLoop.instance().start()