You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

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