No puede seleccionar más de 25 temas Los temas deben comenzar con una letra o número, pueden incluir guiones ('-') y pueden tener hasta 35 caracteres de largo.

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