您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

498 行
18KB

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