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.

472 lines
16KB

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