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

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