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.

453 lines
15KB

  1. import pprint
  2. import sqlite3
  3. from flask import make_response, g
  4. import datetime
  5. from datetime import datetime
  6. from flask.views import MethodView
  7. from flask_classy import FlaskView, route
  8. from time import localtime, strftime
  9. from functools import wraps, update_wrapper
  10. from props import *
  11. from hardware import *
  12. import time
  13. import uuid
  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").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. filename = "./logs/%s_%s.log" % (prefix, str(id))
  115. formatted_time = strftime("%Y-%m-%d %H:%M:%S", localtime())
  116. msg = str(formatted_time) + "," +str(value) + "\n"
  117. with open(filename, "a") as file:
  118. file.write(msg)
  119. def log_action(self, text):
  120. filename = "./logs/action.log"
  121. formatted_time = strftime("%Y-%m-%d %H:%M:%S", localtime())
  122. with open(filename, "a") as file:
  123. file.write("%s,%s\n" % (formatted_time, text))
  124. def shutdown_sensor(self, id):
  125. self.cache.get("sensors")[id].stop()
  126. def get_sensor_value(self, id):
  127. try:
  128. id = int(id)
  129. return int(self.cache.get("sensors")[id].instance.last_value)
  130. except Exception as e:
  131. return None
  132. class CacheAPI(object):
  133. def get_sensor(self, id):
  134. try:
  135. return self.cache["sensors"][id]
  136. except:
  137. return None
  138. def get_actor(self, id):
  139. try:
  140. return self.cache["actors"][id]
  141. except:
  142. return None
  143. class CraftBeerPi(ActorAPI, SensorAPI):
  144. cache = {
  145. "init": {},
  146. "config": {},
  147. "actor_types": {},
  148. "sensor_types": {},
  149. "sensors": {},
  150. "sensor_instances": {},
  151. "init": [],
  152. "background":[],
  153. "step_types": {},
  154. "controller_types": {},
  155. "messages": [],
  156. "plugins": {},
  157. "fermentation_controller_types": {},
  158. "fermenter_task": {}
  159. }
  160. buzzer = None
  161. eventbus = {}
  162. # constructor
  163. def __init__(self, app, socketio):
  164. self.app = app
  165. self.socketio = socketio
  166. def emit(self, key, data):
  167. self.socketio.emit(key, data, namespace='/brew')
  168. def notify(self, headline, message, type="success", timeout=5000):
  169. self.beep()
  170. msg = {"id": str(uuid.uuid1()), "type": type, "headline": headline, "message": message, "timeout": timeout}
  171. if timeout is None:
  172. self.cache["messages"].append(msg)
  173. self.emit("NOTIFY", msg)
  174. def beep(self):
  175. if self.buzzer is not None:
  176. self.buzzer.beep()
  177. def add_cache_callback(self, key, method):
  178. method.callback = True
  179. self.cache[key] = method
  180. def get_config_parameter(self, key, default):
  181. cfg = self.cache.get("config").get(key)
  182. if cfg is None:
  183. return default
  184. else:
  185. return cfg.value
  186. def clear_cache(self, key, is_array=False):
  187. if is_array:
  188. self.cache[key] = []
  189. else:
  190. self.cache[key] = {}
  191. # helper method for parsing props
  192. def __parseProps(self, key, cls):
  193. name = cls.__name__
  194. self.cache[key][name] = {"name": name, "class": cls, "properties": []}
  195. tmpObj = cls()
  196. members = [attr for attr in dir(tmpObj) if not callable(getattr(tmpObj, attr)) and not attr.startswith("__")]
  197. for m in members:
  198. if isinstance(tmpObj.__getattribute__(m), Property.Number):
  199. t = tmpObj.__getattribute__(m)
  200. self.cache[key][name]["properties"].append(
  201. {"name": m, "label": t.label, "type": "number", "configurable": t.configurable})
  202. elif isinstance(tmpObj.__getattribute__(m), Property.Text):
  203. t = tmpObj.__getattribute__(m)
  204. self.cache[key][name]["properties"].append(
  205. {"name": m, "label": t.label, "type": "text", "configurable": t.configurable})
  206. elif isinstance(tmpObj.__getattribute__(m), Property.Select):
  207. t = tmpObj.__getattribute__(m)
  208. self.cache[key][name]["properties"].append(
  209. {"name": m, "label": t.label, "type": "select", "configurable": True, "options": t.options})
  210. return cls
  211. def actor(self, cls):
  212. return self.__parseProps("actor_types", cls)
  213. def sensor(self, cls):
  214. return self.__parseProps("sensor_types", cls)
  215. def controller(self, cls):
  216. return self.__parseProps("controller_types", cls)
  217. def fermentation_controller(self, cls):
  218. return self.__parseProps("fermentation_controller_types", cls)
  219. def get_controller(self, name):
  220. return self.cache["controller_types"].get(name)
  221. def get_fermentation_controller(self, name):
  222. return self.cache["fermentation_controller_types"].get(name)
  223. # Step action
  224. def action(self,label):
  225. def real_decorator(func):
  226. func.action = True
  227. func.label = label
  228. return func
  229. return real_decorator
  230. # step decorator
  231. def step(self, cls):
  232. key = "step_types"
  233. name = cls.__name__
  234. self.cache[key][name] = {"name": name, "class": cls, "properties": [], "actions": []}
  235. tmpObj = cls()
  236. members = [attr for attr in dir(tmpObj) if not callable(getattr(tmpObj, attr)) and not attr.startswith("__")]
  237. for m in members:
  238. if isinstance(tmpObj.__getattribute__(m), StepProperty.Number):
  239. t = tmpObj.__getattribute__(m)
  240. self.cache[key][name]["properties"].append({"name": m, "label": t.label, "type": "number", "configurable": t.configurable})
  241. elif isinstance(tmpObj.__getattribute__(m), StepProperty.Text):
  242. t = tmpObj.__getattribute__(m)
  243. self.cache[key][name]["properties"].append({"name": m, "label": t.label, "type": "text", "configurable": t.configurable})
  244. elif isinstance(tmpObj.__getattribute__(m), StepProperty.Select):
  245. t = tmpObj.__getattribute__(m)
  246. self.cache[key][name]["properties"].append({"name": m, "label": t.label, "type": "select", "options": t.options})
  247. elif isinstance(tmpObj.__getattribute__(m), StepProperty.Actor):
  248. t = tmpObj.__getattribute__(m)
  249. self.cache[key][name]["properties"].append({"name": m, "label": t.label, "type": "actor", "configurable": t.configurable})
  250. elif isinstance(tmpObj.__getattribute__(m), StepProperty.Sensor):
  251. t = tmpObj.__getattribute__(m)
  252. self.cache[key][name]["properties"].append({"name": m, "label": t.label, "type": "sensor", "configurable": t.configurable})
  253. elif isinstance(tmpObj.__getattribute__(m), StepProperty.Kettle):
  254. t = tmpObj.__getattribute__(m)
  255. self.cache[key][name]["properties"].append({"name": m, "label": t.label, "type": "kettle", "configurable": t.configurable})
  256. for name, method in cls.__dict__.iteritems():
  257. if hasattr(method, "action"):
  258. label = method.__getattribute__("label")
  259. self.cache[key][cls.__name__]["actions"].append({"method": name, "label": label})
  260. return cls
  261. # Event Bus
  262. def event(self, name, async=False):
  263. def real_decorator(function):
  264. if self.eventbus.get(name) is None:
  265. self.eventbus[name] = []
  266. self.eventbus[name].append({"function": function, "async": async})
  267. def wrapper(*args, **kwargs):
  268. return function(*args, **kwargs)
  269. return wrapper
  270. return real_decorator
  271. def emit_message(self, message):
  272. self.emit_event(name="MESSAGE", message=message)
  273. def emit_event(self, name, **kwargs):
  274. for i in self.eventbus.get(name, []):
  275. if i["async"] is False:
  276. i["function"](**kwargs)
  277. else:
  278. t = self.socketio.start_background_task(target=i["function"], **kwargs)
  279. # initializer decorator
  280. def initalizer(self, order=0):
  281. def real_decorator(function):
  282. self.cache["init"].append({"function": function, "order": order})
  283. def wrapper(*args, **kwargs):
  284. return function(*args, **kwargs)
  285. return wrapper
  286. return real_decorator
  287. def try_catch(self, errorResult="ERROR"):
  288. def real_decorator(function):
  289. def wrapper(*args, **kwargs):
  290. try:
  291. return function(*args, **kwargs)
  292. except:
  293. self.app.logger.error("Exception in function %s. Return default %s" % (function.__name__, errorResult))
  294. return errorResult
  295. return wrapper
  296. return real_decorator
  297. def nocache(self, view):
  298. @wraps(view)
  299. def no_cache(*args, **kwargs):
  300. response = make_response(view(*args, **kwargs))
  301. response.headers['Last-Modified'] = datetime.now()
  302. response.headers[
  303. 'Cache-Control'] = 'no-store, no-cache, must-revalidate, post-check=0, pre-check=0, max-age=0'
  304. response.headers['Pragma'] = 'no-cache'
  305. response.headers['Expires'] = '-1'
  306. return response
  307. return update_wrapper(no_cache, view)
  308. def init_kettle(self, id):
  309. try:
  310. value = self.cache.get("kettle").get(id)
  311. value["state"] = False
  312. except:
  313. self.notify("Kettle Setup Faild", "Please check %s configuration" % value.name, type="danger", timeout=None)
  314. self.app.logger.error("Initializing of Kettle %s failed" % id)
  315. def run_init(self):
  316. '''
  317. call all initialziers after startup
  318. :return:
  319. '''
  320. self.app.logger.info("Invoke Init")
  321. self.cache["init"] = sorted(self.cache["init"], key=lambda k: k['order'])
  322. for i in self.cache.get("init"):
  323. self.app.logger.info("-> %s " % i.get("function").__name__)
  324. i.get("function")(self)
  325. def backgroundtask(self, key, interval, config_parameter=None):
  326. '''
  327. Background Task Decorator
  328. :param key:
  329. :param interval:
  330. :param config_parameter:
  331. :return:
  332. '''
  333. def real_decorator(function):
  334. self.cache["background"].append({"function": function, "key": key, "interval": interval, "config_parameter": config_parameter})
  335. def wrapper(*args, **kwargs):
  336. return function(*args, **kwargs)
  337. return wrapper
  338. return real_decorator
  339. def run_background_processes(self):
  340. '''
  341. call all background task after startup
  342. :return:
  343. '''
  344. self.app.logger.info("Start Background")
  345. def job(interval, method):
  346. while True:
  347. try:
  348. method()
  349. except Exception as e:
  350. self.app.logger.error("Exception" + method.__name__ + ": " + str(e))
  351. self.socketio.sleep(interval)
  352. for value in self.cache.get("background"):
  353. t = self.socketio.start_background_task(target=job, interval=value.get("interval"), method=value.get("function"))