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.

494 lines
17KB

  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 modules.core.props import *
  12. from modules.core.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 list(t.items()):
  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. clazz = self.cache.get("actor_types").get(value.type).get("class")
  32. value.instance = clazz(**cfg)
  33. value.instance.init()
  34. value.state = 0
  35. value.power = 100
  36. except Exception as e:
  37. self.notify("Actor Error", "Failed to setup actor %s. Please check the configuraiton" % value.name,
  38. type="danger", timeout=None)
  39. self.app.logger.error("Initializing of Actor %s failed" % id)
  40. def switch_actor_on(self, id, power=None):
  41. actor = self.cache.get("actors").get(id)
  42. if actor.state == 1:
  43. return
  44. actor.instance.on(power=power)
  45. actor.state = 1
  46. if power is not None:
  47. actor.power = power
  48. self.emit("SWITCH_ACTOR", actor)
  49. def actor_power(self, id, power=100):
  50. actor = self.cache.get("actors").get(id)
  51. actor.instance.set_power(power=power)
  52. actor.power = power
  53. self.emit("SWITCH_ACTOR", actor)
  54. def switch_actor_off(self, id):
  55. actor = self.cache.get("actors").get(id)
  56. if actor.state == 0:
  57. return
  58. actor.instance.off()
  59. actor.state = 0
  60. self.emit("SWITCH_ACTOR", actor)
  61. class SensorAPI(object):
  62. def init_sensors(self):
  63. '''
  64. Initialize all sensors
  65. :return:
  66. '''
  67. self.app.logger.info("Init Sensors")
  68. t = self.cache.get("sensor_types")
  69. for key, value in list(t.items()):
  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)
  114. def save_to_file(self, id, value, prefix="sensor"):
  115. filename = "./logs/%s_%s.log" % (prefix, str(id))
  116. formatted_time = strftime("%Y-%m-%d %H:%M:%S", localtime())
  117. msg = str(formatted_time) + "," +str(value) + "\n"
  118. with open(filename, "a") as file:
  119. file.write(msg)
  120. def log_action(self, text):
  121. filename = "./logs/action.log"
  122. formatted_time = strftime("%Y-%m-%d %H:%M:%S", localtime())
  123. with open(filename, "a") as file:
  124. text = text.encode("utf-8")
  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. self.emit_message(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 set_config_parameter(self, name, value):
  187. from modules.config import Config
  188. with self.app.app_context():
  189. update_data = {"name": name, "value": value}
  190. self.cache.get("config")[name].__dict__.update(**update_data)
  191. c = Config.update(**update_data)
  192. self.emit("UPDATE_CONFIG", c)
  193. def add_config_parameter(self, name, value, type, description, options=None):
  194. from modules.config import Config
  195. with self.app.app_context():
  196. c = Config.insert(**{"name":name, "value": value, "type": type, "description": description, "options": options})
  197. if self.cache.get("config") is not None:
  198. self.cache.get("config")[c.name] = c
  199. def clear_cache(self, key, is_array=False):
  200. if is_array:
  201. self.cache[key] = []
  202. else:
  203. self.cache[key] = {}
  204. # helper method for parsing props
  205. def __parseProps(self, key, cls):
  206. name = cls.__name__
  207. self.cache[key][name] = {"name": name, "class": cls, "properties": [], "actions": []}
  208. tmpObj = cls()
  209. members = [attr for attr in dir(tmpObj) if not callable(getattr(tmpObj, attr)) and not attr.startswith("__")]
  210. for m in members:
  211. if isinstance(tmpObj.__getattribute__(m), Property.Number):
  212. t = tmpObj.__getattribute__(m)
  213. self.cache[key][name]["properties"].append(
  214. {"name": m, "label": t.label, "type": "number", "configurable": t.configurable, "description": t.description, "default_value": t.default_value})
  215. elif isinstance(tmpObj.__getattribute__(m), Property.Text):
  216. t = tmpObj.__getattribute__(m)
  217. self.cache[key][name]["properties"].append(
  218. {"name": m, "label": t.label, "type": "text", "configurable": t.configurable, "default_value": t.default_value, "description": t.description})
  219. elif isinstance(tmpObj.__getattribute__(m), Property.Select):
  220. t = tmpObj.__getattribute__(m)
  221. self.cache[key][name]["properties"].append(
  222. {"name": m, "label": t.label, "type": "select", "configurable": True, "options": t.options, "description": t.description})
  223. elif isinstance(tmpObj.__getattribute__(m), Property.Actor):
  224. t = tmpObj.__getattribute__(m)
  225. self.cache[key][name]["properties"].append({"name": m, "label": t.label, "type": "actor", "configurable": t.configurable, "description": t.description})
  226. elif isinstance(tmpObj.__getattribute__(m), Property.Sensor):
  227. t = tmpObj.__getattribute__(m)
  228. self.cache[key][name]["properties"].append({"name": m, "label": t.label, "type": "sensor", "configurable": t.configurable, "description": t.description})
  229. elif isinstance(tmpObj.__getattribute__(m), Property.Kettle):
  230. t = tmpObj.__getattribute__(m)
  231. self.cache[key][name]["properties"].append({"name": m, "label": t.label, "type": "kettle", "configurable": t.configurable, "description": t.description})
  232. for name, method in list(cls.__dict__.items()):
  233. if hasattr(method, "action"):
  234. label = method.__getattribute__("label")
  235. self.cache[key][cls.__name__]["actions"].append({"method": name, "label": label})
  236. return cls
  237. def actor(self, cls):
  238. return self.__parseProps("actor_types", cls)
  239. def actor2(self, description="", power=True, **options):
  240. def decorator(f):
  241. print((f()))
  242. print(f)
  243. print(options)
  244. print(description)
  245. return f
  246. return decorator
  247. def sensor(self, cls):
  248. return self.__parseProps("sensor_types", cls)
  249. def controller(self, cls):
  250. return self.__parseProps("controller_types", cls)
  251. def fermentation_controller(self, cls):
  252. return self.__parseProps("fermentation_controller_types", cls)
  253. def get_controller(self, name):
  254. return self.cache["controller_types"].get(name)
  255. def get_fermentation_controller(self, name):
  256. return self.cache["fermentation_controller_types"].get(name)
  257. # Step action
  258. def action(self,label):
  259. def real_decorator(func):
  260. func.action = True
  261. func.label = label
  262. return func
  263. return real_decorator
  264. # step decorator
  265. def step(self, cls):
  266. key = "step_types"
  267. name = cls.__name__
  268. self.cache[key][name] = {"name": name, "class": cls, "properties": [], "actions": []}
  269. tmpObj = cls()
  270. members = [attr for attr in dir(tmpObj) if not callable(getattr(tmpObj, attr)) and not attr.startswith("__")]
  271. for m in members:
  272. if isinstance(tmpObj.__getattribute__(m), StepProperty.Number):
  273. t = tmpObj.__getattribute__(m)
  274. self.cache[key][name]["properties"].append({"name": m, "label": t.label, "type": "number", "configurable": t.configurable, "default_value": t.default_value, "description": t.description})
  275. elif isinstance(tmpObj.__getattribute__(m), StepProperty.Text):
  276. t = tmpObj.__getattribute__(m)
  277. self.cache[key][name]["properties"].append({"name": m, "label": t.label, "type": "text", "configurable": t.configurable, "default_value": t.default_value, "description": t.description})
  278. elif isinstance(tmpObj.__getattribute__(m), StepProperty.Select):
  279. t = tmpObj.__getattribute__(m)
  280. self.cache[key][name]["properties"].append({"name": m, "label": t.label, "type": "select", "configurable": True, "options": t.options, "description": t.description})
  281. elif isinstance(tmpObj.__getattribute__(m), StepProperty.Actor):
  282. t = tmpObj.__getattribute__(m)
  283. self.cache[key][name]["properties"].append({"name": m, "label": t.label, "type": "actor", "configurable": t.configurable, "description": t.description})
  284. elif isinstance(tmpObj.__getattribute__(m), StepProperty.Sensor):
  285. t = tmpObj.__getattribute__(m)
  286. self.cache[key][name]["properties"].append({"name": m, "label": t.label, "type": "sensor", "configurable": t.configurable, "description": t.description})
  287. elif isinstance(tmpObj.__getattribute__(m), StepProperty.Kettle):
  288. t = tmpObj.__getattribute__(m)
  289. self.cache[key][name]["properties"].append({"name": m, "label": t.label, "type": "kettle", "configurable": t.configurable, "description": t.description})
  290. for name, method in list(cls.__dict__.items()):
  291. if hasattr(method, "action"):
  292. label = method.__getattribute__("label")
  293. self.cache[key][cls.__name__]["actions"].append({"method": name, "label": label})
  294. return cls
  295. # Event Bus
  296. def event(self, name, async=False):
  297. def real_decorator(function):
  298. if self.eventbus.get(name) is None:
  299. self.eventbus[name] = []
  300. self.eventbus[name].append({"function": function, "async": async})
  301. def wrapper(*args, **kwargs):
  302. return function(*args, **kwargs)
  303. return wrapper
  304. return real_decorator
  305. def emit_message(self, message):
  306. self.emit_event(name="MESSAGE", message=message)
  307. def emit_event(self, name, **kwargs):
  308. for i in self.eventbus.get(name, []):
  309. if i["async"] is False:
  310. i["function"](**kwargs)
  311. else:
  312. t = self.socketio.start_background_task(target=i["function"], **kwargs)
  313. # initializer decorator
  314. def initalizer(self, order=0):
  315. def real_decorator(function):
  316. self.cache["init"].append({"function": function, "order": order})
  317. def wrapper(*args, **kwargs):
  318. return function(*args, **kwargs)
  319. return wrapper
  320. return real_decorator
  321. def try_catch(self, errorResult="ERROR"):
  322. def real_decorator(function):
  323. def wrapper(*args, **kwargs):
  324. try:
  325. return function(*args, **kwargs)
  326. except:
  327. self.app.logger.error("Exception in function %s. Return default %s" % (function.__name__, errorResult))
  328. return errorResult
  329. return wrapper
  330. return real_decorator
  331. def nocache(self, view):
  332. @wraps(view)
  333. def no_cache(*args, **kwargs):
  334. response = make_response(view(*args, **kwargs))
  335. response.headers['Last-Modified'] = datetime.now()
  336. response.headers[
  337. 'Cache-Control'] = 'no-store, no-cache, must-revalidate, post-check=0, pre-check=0, max-age=0'
  338. response.headers['Pragma'] = 'no-cache'
  339. response.headers['Expires'] = '-1'
  340. return response
  341. return update_wrapper(no_cache, view)
  342. def init_kettle(self, id):
  343. try:
  344. value = self.cache.get("kettle").get(id)
  345. value["state"] = False
  346. except:
  347. self.notify("Kettle Setup Faild", "Please check %s configuration" % value.name, type="danger", timeout=None)
  348. self.app.logger.error("Initializing of Kettle %s failed" % id)
  349. def run_init(self):
  350. '''
  351. call all initialziers after startup
  352. :return:
  353. '''
  354. self.app.logger.info("Invoke Init")
  355. self.cache["init"] = sorted(self.cache["init"], key=lambda k: k['order'])
  356. for i in self.cache.get("init"):
  357. self.app.logger.info("INITIALIZER - METHOD %s PAHT %s: " % (i.get("function").__name__, str(inspect.getmodule(i.get("function")).__file__) ))
  358. i.get("function")(self)
  359. def backgroundtask(self, key, interval, config_parameter=None):
  360. '''
  361. Background Task Decorator
  362. :param key:
  363. :param interval:
  364. :param config_parameter:
  365. :return:
  366. '''
  367. def real_decorator(function):
  368. self.cache["background"].append({"function": function, "key": key, "interval": interval, "config_parameter": config_parameter})
  369. def wrapper(*args, **kwargs):
  370. return function(*args, **kwargs)
  371. return wrapper
  372. return real_decorator
  373. def run_background_processes(self):
  374. '''
  375. call all background task after startup
  376. :return:
  377. '''
  378. self.app.logger.info("Start Background")
  379. def job(interval, method):
  380. while True:
  381. try:
  382. method(self)
  383. except Exception as e:
  384. self.app.logger.error("Exception " + method.__name__ + ": " + str(e))
  385. self.socketio.sleep(interval)
  386. for value in self.cache.get("background"):
  387. t = self.socketio.start_background_task(target=job, interval=value.get("interval"), method=value.get("function"))