您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

522 行
18KB

  1. import inspect
  2. from flask import make_response, g
  3. import datetime
  4. from datetime import datetime
  5. from time import localtime, strftime
  6. from functools import wraps, update_wrapper
  7. import requests
  8. import json
  9. from props import *
  10. from hardware import *
  11. import time
  12. import uuid
  13. import logging
  14. class NotificationAPI(object):
  15. pass
  16. class ActorAPI(object):
  17. def init_actors(self):
  18. self.app.logger.info("Init Actors")
  19. t = self.cache.get("actor_types")
  20. for key, value in t.iteritems():
  21. value.get("class").api = self
  22. value.get("class").init_global()
  23. for key in self.cache.get("actors"):
  24. self.init_actor(key)
  25. def init_actor(self, id):
  26. try:
  27. value = self.cache.get("actors").get(int(id))
  28. cfg = value.config.copy()
  29. cfg.update(dict(api=self, id=id, name=value.name))
  30. clazz = self.cache.get("actor_types").get(value.type).get("class")
  31. value.instance = clazz(**cfg)
  32. value.instance.init()
  33. value.state = 0
  34. value.power = 100
  35. except Exception as e:
  36. self.notify("Actor Error", "Failed to setup actor %s. Please check the configuraiton" % value.name,
  37. type="danger", timeout=None)
  38. self.app.logger.error("Initializing of Actor %s failed" % id)
  39. def switch_actor_on(self, id, power=None):
  40. actor = self.cache.get("actors").get(id)
  41. if actor.state == 1:
  42. return
  43. actor.instance.on(power=power)
  44. actor.state = 1
  45. if power is not None:
  46. actor.power = power
  47. self.emit("SWITCH_ACTOR", actor)
  48. def actor_power(self, id, power=100):
  49. actor = self.cache.get("actors").get(id)
  50. actor.instance.set_power(power=power)
  51. actor.power = power
  52. self.emit("SWITCH_ACTOR", actor)
  53. def switch_actor_off(self, id):
  54. actor = self.cache.get("actors").get(id)
  55. if actor.state == 0:
  56. return
  57. actor.instance.off()
  58. actor.state = 0
  59. self.emit("SWITCH_ACTOR", actor)
  60. class SensorAPI(object):
  61. def init_sensors(self):
  62. '''
  63. Initialize all sensors
  64. :return:
  65. '''
  66. self.logger = logging.getLogger(__name__)
  67. self.app.logger.info("Init Sensors")
  68. t = self.cache.get("sensor_types")
  69. for key, value in t.iteritems():
  70. value.get("class").init_global()
  71. for key in self.cache.get("sensors"):
  72. self.init_sensor(key)
  73. def stop_sensor(self, id):
  74. try:
  75. self.cache.get("sensors").get(id).instance.stop()
  76. except Exception as e:
  77. self.app.logger.info("Stop Sensor Error")
  78. pass
  79. def init_sensor(self, id):
  80. '''
  81. initialize sensor by id
  82. :param id:
  83. :return:
  84. '''
  85. def start_active_sensor(instance):
  86. '''
  87. start active sensors as background job
  88. :param instance:
  89. :return:
  90. '''
  91. instance.execute()
  92. try:
  93. if id in self.cache.get("sensor_instances"):
  94. self.cache.get("sensor_instances").get(id).stop()
  95. value = self.cache.get("sensors").get(id)
  96. cfg = value.config.copy()
  97. cfg.update(dict(api=self, id=id, name=value.name))
  98. clazz = self.cache.get("sensor_types").get(value.type).get("class")
  99. value.instance = clazz(**cfg)
  100. value.instance.init()
  101. if isinstance(value.instance, SensorPassive):
  102. # Passive Sensors
  103. value.mode = "P"
  104. else:
  105. # Active Sensors
  106. value.mode = "A"
  107. t = self.socketio.start_background_task(target=start_active_sensor, instance=value.instance)
  108. except Exception as e:
  109. self.notify("Sensor Error", "Failed to setup Sensor %s. Please check the configuraiton" % value.name, type="danger", timeout=None)
  110. self.app.logger.error("Initializing of Sensor %s failed" % id)
  111. def receive_sensor_value(self, id, value):
  112. self.emit("SENSOR_UPDATE", self.cache.get("sensors")[id])
  113. self.save_to_file(id, value, "sensor")
  114. def save_to_file(self, id, value, prefix):
  115. sensor_name = "%s_%s" % (prefix, str(id))
  116. use_kairosdb = (self.cache["config"]["kairos_db"].__dict__["value"] == "YES")
  117. if use_kairosdb:
  118. self.write_to_tsdb(prefix, sensor_name, value)
  119. else:
  120. self.write_to_logfile(sensor_name, value)
  121. def write_to_logfile(self, sensor_name, value):
  122. filename = "./logs/%s.log" % sensor_name
  123. formatted_time = strftime("%Y-%m-%d %H:%M:%S", localtime())
  124. msg = str(formatted_time) + "," + str(value) + "\n"
  125. with open(filename, "a") as file:
  126. file.write(msg)
  127. def write_to_tsdb(self, prefix, sensor_name, value):
  128. kairosdb_server = "http://127.0.0.1:" + self.cache["config"]["kairos_db_port"].__dict__["value"]
  129. data = [
  130. dict(name="cbpi." + sensor_name, datapoints=[
  131. [int(round(time.time() * 1000)), value]
  132. ], tags={
  133. "cbpi": prefix,
  134. "brew": self.cache["active_brew"]
  135. })
  136. ]
  137. response = requests.post(kairosdb_server + "/api/v1/datapoints", json.dumps(data))
  138. if not response.ok:
  139. self.logger.warning("Failed to write time series entry for [%s]. Response [%s]", sensor_name, response)
  140. def log_action(self, text):
  141. use_kairosdb = (self.cache["config"]["kairos_db"].__dict__["value"] == "YES")
  142. if use_kairosdb:
  143. self.write_to_tsdb("action", "action", text)
  144. else:
  145. self.write_to_logfile("action", text)
  146. def shutdown_sensor(self, id):
  147. self.cache.get("sensors")[id].stop()
  148. def get_sensor_value(self, id):
  149. try:
  150. id = int(id)
  151. return float(self.cache.get("sensors")[id].instance.last_value)
  152. except Exception as e:
  153. return None
  154. class CacheAPI(object):
  155. def get_sensor(self, id):
  156. try:
  157. return self.cache["sensors"][id]
  158. except:
  159. return None
  160. def get_actor(self, id):
  161. try:
  162. return self.cache["actors"][id]
  163. except:
  164. return None
  165. class CraftBeerPi(ActorAPI, SensorAPI):
  166. cache = {
  167. "init": {},
  168. "config": {},
  169. "actor_types": {},
  170. "sensor_types": {},
  171. "sensors": {},
  172. "sensor_instances": {},
  173. "init": [],
  174. "background":[],
  175. "step_types": {},
  176. "controller_types": {},
  177. "messages": [],
  178. "plugins": {},
  179. "fermentation_controller_types": {},
  180. "fermenter_task": {},
  181. "active_brew": "none"
  182. }
  183. buzzer = None
  184. eventbus = {}
  185. # constructor
  186. def __init__(self, app, socketio):
  187. self.app = app
  188. self.socketio = socketio
  189. def emit(self, key, data):
  190. self.socketio.emit(key, data, namespace='/brew')
  191. def notify(self, headline, message, type="success", timeout=5000):
  192. self.beep()
  193. msg = {"id": str(uuid.uuid1()), "type": type, "headline": headline, "message": message, "timeout": timeout}
  194. self.emit_message(msg)
  195. def beep(self):
  196. if self.buzzer is not None:
  197. self.buzzer.beep()
  198. def add_cache_callback(self, key, method):
  199. method.callback = True
  200. self.cache[key] = method
  201. def get_config_parameter(self, key, default):
  202. cfg = self.cache.get("config").get(key)
  203. if cfg is None:
  204. return default
  205. else:
  206. return cfg.value
  207. def set_config_parameter(self, name, value):
  208. from modules.config import Config
  209. with self.app.app_context():
  210. update_data = {"name": name, "value": value}
  211. self.cache.get("config")[name].__dict__.update(**update_data)
  212. c = Config.update(**update_data)
  213. self.emit("UPDATE_CONFIG", c)
  214. def add_config_parameter(self, name, value, type, description, options=None):
  215. from modules.config import Config
  216. with self.app.app_context():
  217. c = Config.insert(**{"name":name, "value": value, "type": type, "description": description, "options": options})
  218. if self.cache.get("config") is not None:
  219. self.cache.get("config")[c.name] = c
  220. def clear_cache(self, key, is_array=False):
  221. if is_array:
  222. self.cache[key] = []
  223. else:
  224. self.cache[key] = {}
  225. # helper method for parsing props
  226. def __parseProps(self, key, cls):
  227. name = cls.__name__
  228. self.cache[key][name] = {"name": name, "class": cls, "properties": [], "actions": []}
  229. tmpObj = cls()
  230. members = [attr for attr in dir(tmpObj) if not callable(getattr(tmpObj, attr)) and not attr.startswith("__")]
  231. for m in members:
  232. if isinstance(tmpObj.__getattribute__(m), Property.Number):
  233. t = tmpObj.__getattribute__(m)
  234. self.cache[key][name]["properties"].append(
  235. {"name": m, "label": t.label, "type": "number", "configurable": t.configurable, "description": t.description, "default_value": t.default_value})
  236. elif isinstance(tmpObj.__getattribute__(m), Property.Text):
  237. t = tmpObj.__getattribute__(m)
  238. self.cache[key][name]["properties"].append(
  239. {"name": m, "label": t.label, "type": "text", "configurable": t.configurable, "default_value": t.default_value, "description": t.description})
  240. elif isinstance(tmpObj.__getattribute__(m), Property.Select):
  241. t = tmpObj.__getattribute__(m)
  242. self.cache[key][name]["properties"].append(
  243. {"name": m, "label": t.label, "type": "select", "configurable": True, "options": t.options, "description": t.description})
  244. elif isinstance(tmpObj.__getattribute__(m), Property.Actor):
  245. t = tmpObj.__getattribute__(m)
  246. self.cache[key][name]["properties"].append({"name": m, "label": t.label, "type": "actor", "configurable": t.configurable, "description": t.description})
  247. elif isinstance(tmpObj.__getattribute__(m), Property.Sensor):
  248. t = tmpObj.__getattribute__(m)
  249. self.cache[key][name]["properties"].append({"name": m, "label": t.label, "type": "sensor", "configurable": t.configurable, "description": t.description})
  250. elif isinstance(tmpObj.__getattribute__(m), Property.Kettle):
  251. t = tmpObj.__getattribute__(m)
  252. self.cache[key][name]["properties"].append({"name": m, "label": t.label, "type": "kettle", "configurable": t.configurable, "description": t.description})
  253. for name, method in cls.__dict__.iteritems():
  254. if hasattr(method, "action"):
  255. label = method.__getattribute__("label")
  256. self.cache[key][cls.__name__]["actions"].append({"method": name, "label": label})
  257. return cls
  258. def actor(self, cls):
  259. return self.__parseProps("actor_types", cls)
  260. def actor2(self, description="", power=True, **options):
  261. def decorator(f):
  262. print f()
  263. print f
  264. print options
  265. print description
  266. return f
  267. return decorator
  268. def sensor(self, cls):
  269. return self.__parseProps("sensor_types", cls)
  270. def controller(self, cls):
  271. return self.__parseProps("controller_types", cls)
  272. def fermentation_controller(self, cls):
  273. return self.__parseProps("fermentation_controller_types", cls)
  274. def get_controller(self, name):
  275. return self.cache["controller_types"].get(name)
  276. def get_fermentation_controller(self, name):
  277. return self.cache["fermentation_controller_types"].get(name)
  278. # Step action
  279. def action(self,label):
  280. def real_decorator(func):
  281. func.action = True
  282. func.label = label
  283. return func
  284. return real_decorator
  285. # step decorator
  286. def step(self, cls):
  287. key = "step_types"
  288. name = cls.__name__
  289. self.cache[key][name] = {"name": name, "class": cls, "properties": [], "actions": []}
  290. tmpObj = cls()
  291. members = [attr for attr in dir(tmpObj) if not callable(getattr(tmpObj, attr)) and not attr.startswith("__")]
  292. for m in members:
  293. if isinstance(tmpObj.__getattribute__(m), StepProperty.Number):
  294. t = tmpObj.__getattribute__(m)
  295. self.cache[key][name]["properties"].append({"name": m, "label": t.label, "type": "number", "configurable": t.configurable, "default_value": t.default_value, "description": t.description})
  296. elif isinstance(tmpObj.__getattribute__(m), StepProperty.Text):
  297. t = tmpObj.__getattribute__(m)
  298. self.cache[key][name]["properties"].append({"name": m, "label": t.label, "type": "text", "configurable": t.configurable, "default_value": t.default_value, "description": t.description})
  299. elif isinstance(tmpObj.__getattribute__(m), StepProperty.Select):
  300. t = tmpObj.__getattribute__(m)
  301. self.cache[key][name]["properties"].append({"name": m, "label": t.label, "type": "select", "configurable": True, "options": t.options, "description": t.description})
  302. elif isinstance(tmpObj.__getattribute__(m), StepProperty.Actor):
  303. t = tmpObj.__getattribute__(m)
  304. self.cache[key][name]["properties"].append({"name": m, "label": t.label, "type": "actor", "configurable": t.configurable, "description": t.description})
  305. elif isinstance(tmpObj.__getattribute__(m), StepProperty.Sensor):
  306. t = tmpObj.__getattribute__(m)
  307. self.cache[key][name]["properties"].append({"name": m, "label": t.label, "type": "sensor", "configurable": t.configurable, "description": t.description})
  308. elif isinstance(tmpObj.__getattribute__(m), StepProperty.Kettle):
  309. t = tmpObj.__getattribute__(m)
  310. self.cache[key][name]["properties"].append({"name": m, "label": t.label, "type": "kettle", "configurable": t.configurable, "description": t.description})
  311. for name, method in cls.__dict__.iteritems():
  312. if hasattr(method, "action"):
  313. label = method.__getattribute__("label")
  314. self.cache[key][cls.__name__]["actions"].append({"method": name, "label": label})
  315. return cls
  316. # Event Bus
  317. def event(self, name, async=False):
  318. def real_decorator(function):
  319. if self.eventbus.get(name) is None:
  320. self.eventbus[name] = []
  321. self.eventbus[name].append({"function": function, "async": async})
  322. def wrapper(*args, **kwargs):
  323. return function(*args, **kwargs)
  324. return wrapper
  325. return real_decorator
  326. def emit_message(self, message):
  327. self.emit_event(name="MESSAGE", message=message)
  328. def emit_event(self, name, **kwargs):
  329. for i in self.eventbus.get(name, []):
  330. if i["async"] is False:
  331. i["function"](**kwargs)
  332. else:
  333. t = self.socketio.start_background_task(target=i["function"], **kwargs)
  334. # initializer decorator
  335. def initalizer(self, order=0):
  336. def real_decorator(function):
  337. self.cache["init"].append({"function": function, "order": order})
  338. def wrapper(*args, **kwargs):
  339. return function(*args, **kwargs)
  340. return wrapper
  341. return real_decorator
  342. def try_catch(self, errorResult="ERROR"):
  343. def real_decorator(function):
  344. def wrapper(*args, **kwargs):
  345. try:
  346. return function(*args, **kwargs)
  347. except:
  348. self.app.logger.error("Exception in function %s. Return default %s" % (function.__name__, errorResult))
  349. return errorResult
  350. return wrapper
  351. return real_decorator
  352. def nocache(self, view):
  353. @wraps(view)
  354. def no_cache(*args, **kwargs):
  355. response = make_response(view(*args, **kwargs))
  356. response.headers['Last-Modified'] = datetime.now()
  357. response.headers[
  358. 'Cache-Control'] = 'no-store, no-cache, must-revalidate, post-check=0, pre-check=0, max-age=0'
  359. response.headers['Pragma'] = 'no-cache'
  360. response.headers['Expires'] = '-1'
  361. return response
  362. return update_wrapper(no_cache, view)
  363. def init_kettle(self, id):
  364. try:
  365. value = self.cache.get("kettle").get(id)
  366. value["state"] = False
  367. except:
  368. self.notify("Kettle Setup Faild", "Please check %s configuration" % value.name, type="danger", timeout=None)
  369. self.app.logger.error("Initializing of Kettle %s failed" % id)
  370. def run_init(self):
  371. '''
  372. call all initialziers after startup
  373. :return:
  374. '''
  375. self.app.logger.info("Invoke Init")
  376. self.cache["init"] = sorted(self.cache["init"], key=lambda k: k['order'])
  377. for i in self.cache.get("init"):
  378. self.app.logger.info("INITIALIZER - METHOD %s PAHT %s: " % (i.get("function").__name__, str(inspect.getmodule(i.get("function")).__file__) ))
  379. i.get("function")(self)
  380. def backgroundtask(self, key, interval, config_parameter=None):
  381. '''
  382. Background Task Decorator
  383. :param key:
  384. :param interval:
  385. :param config_parameter:
  386. :return:
  387. '''
  388. def real_decorator(function):
  389. self.cache["background"].append({"function": function, "key": key, "interval": interval, "config_parameter": config_parameter})
  390. def wrapper(*args, **kwargs):
  391. return function(*args, **kwargs)
  392. return wrapper
  393. return real_decorator
  394. def run_background_processes(self):
  395. '''
  396. call all background task after startup
  397. :return:
  398. '''
  399. self.app.logger.info("Start Background")
  400. def job(interval, method):
  401. while True:
  402. try:
  403. method(self)
  404. except Exception as e:
  405. self.app.logger.error("Exception" + method.__name__ + ": " + str(e))
  406. self.socketio.sleep(interval)
  407. for value in self.cache.get("background"):
  408. t = self.socketio.start_background_task(target=job, interval=value.get("interval"), method=value.get("function"))