Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

247 строки
7.2KB

  1. import time
  2. import datetime
  3. from flask import json, request
  4. from flask_classy import route
  5. from modules import DBModel, cbpi, get_db
  6. from modules.core.baseview import BaseView
  7. class Step(DBModel):
  8. __fields__ = ["name","type", "stepstate", "state", "start", "end", "order", "config"]
  9. __table_name__ = "step"
  10. __json_fields__ = ["config", "stepstate"]
  11. __order_by__ = "order"
  12. __as_array__ = True
  13. @classmethod
  14. def get_max_order(cls):
  15. cur = get_db().cursor()
  16. cur.execute("SELECT max(step.'order') as 'order' FROM %s" % cls.__table_name__)
  17. r = cur.fetchone()
  18. return r.get("order")
  19. @classmethod
  20. def get_by_state(cls, state, order=True):
  21. cur = get_db().cursor()
  22. cur.execute("SELECT * FROM %s WHERE state = ? ORDER BY %s.'order'" % (cls.__table_name__,cls.__table_name__,), state)
  23. r = cur.fetchone()
  24. if r is not None:
  25. return cls(r)
  26. else:
  27. return None
  28. @classmethod
  29. def delete_all(cls):
  30. cur = get_db().cursor()
  31. cur.execute("DELETE FROM %s" % cls.__table_name__)
  32. get_db().commit()
  33. @classmethod
  34. def reset_all_steps(cls):
  35. cur = get_db().cursor()
  36. cur.execute("UPDATE %s SET state = 'I', stepstate = NULL , start = NULL, end = NULL " % cls.__table_name__)
  37. get_db().commit()
  38. @classmethod
  39. def update_state(cls, id, state):
  40. cur = get_db().cursor()
  41. cur.execute("UPDATE %s SET state = ? WHERE id =?" % cls.__table_name__, (state, id))
  42. get_db().commit()
  43. @classmethod
  44. def update_step_state(cls, id, state):
  45. cur = get_db().cursor()
  46. cur.execute("UPDATE %s SET stepstate = ? WHERE id =?" % cls.__table_name__, (json.dumps(state),id))
  47. get_db().commit()
  48. @classmethod
  49. def sort(cls, new_order):
  50. cur = get_db().cursor()
  51. for e in new_order:
  52. cur.execute("UPDATE %s SET '%s' = ? WHERE id = ?" % (cls.__table_name__, "order"), (e[1], e[0]))
  53. get_db().commit()
  54. class StepView(BaseView):
  55. model = Step
  56. def _pre_post_callback(self, data):
  57. order = self.model.get_max_order()
  58. data["order"] = 1 if order is None else order + 1
  59. data["state"] = "I"
  60. @route('/sort', methods=["POST"])
  61. def sort_steps(self):
  62. Step.sort(request.json)
  63. cbpi.emit("UPDATE_ALL_STEPS", self.model.get_all())
  64. return ('', 204)
  65. @route('/', methods=["DELETE"])
  66. def deleteAll(self):
  67. self.model.delete_all()
  68. cbpi.emit("UPDATE_ALL_STEPS", self.model.get_all())
  69. return ('', 204)
  70. @route('/action/<method>', methods=["POST"])
  71. def action(self, method):
  72. cbpi.cache["active_step"].__getattribute__(method)()
  73. return ('', 204)
  74. @route('/reset', methods=["POST"])
  75. def reset(self):
  76. self.model.reset_all_steps()
  77. self.stop_step()
  78. cbpi.emit("UPDATE_ALL_STEPS", self.model.get_all())
  79. return ('', 204)
  80. def stop_step(self):
  81. '''
  82. stop active step
  83. :return:
  84. '''
  85. step = cbpi.cache.get("active_step")
  86. cbpi.cache["active_step"] = None
  87. if step is not None:
  88. step.finish()
  89. @route('/reset/current', methods=['POST'])
  90. def resetCurrentStep(self):
  91. '''
  92. Reset current step
  93. :return:
  94. '''
  95. step = cbpi.cache.get("active_step")
  96. if step is not None:
  97. step.reset()
  98. if step.is_dirty():
  99. state = {}
  100. for field in step.managed_fields:
  101. state[field] = step.__getattribute__(field)
  102. Step.update_step_state(step.id, state)
  103. step.reset_dirty()
  104. cbpi.emit("UPDATE_ALL_STEPS", self.model.get_all())
  105. return ('', 204)
  106. def init_step(self, step):
  107. cbpi.log_action("Start Step %s" % step.name)
  108. type_cfg = cbpi.cache.get("step_types").get(step.type)
  109. if type_cfg is None:
  110. # if type not found
  111. return
  112. # copy config to stepstate
  113. # init step
  114. cfg = step.config.copy()
  115. cfg.update(dict(name=step.name, api=cbpi, id=step.id, timer_end=None, managed_fields=get_manged_fields_as_array(type_cfg)))
  116. instance = type_cfg.get("class")(**cfg)
  117. instance.init()
  118. # set step instance to ache
  119. cbpi.cache["active_step"] = instance
  120. @route('/start', methods=['POST'])
  121. def start(self):
  122. cbpi.cache["active_brew"] = cbpi.cache["config"]["brew_name"].__dict__["value"] + \
  123. "_" + datetime.datetime.now().strftime('%y-%m-%dT%H:%M')
  124. return self.next()
  125. @route('/next', methods=['POST'])
  126. def next(self):
  127. active = Step.get_by_state("A")
  128. inactive = Step.get_by_state('I')
  129. if (active is not None):
  130. active.state = 'D'
  131. active.end = int(time.time())
  132. self.stop_step()
  133. Step.update(**active.__dict__)
  134. if (inactive is not None):
  135. self.init_step(inactive)
  136. inactive.state = 'A'
  137. inactive.stepstate = inactive.config
  138. inactive.start = int(time.time())
  139. Step.update(**inactive.__dict__)
  140. else:
  141. cbpi.log_action("Brewing Finished")
  142. cbpi.notify("Brewing Finished", "You are done!", timeout=None)
  143. cbpi.cache["active_brew"] = "none"
  144. cbpi.emit("UPDATE_ALL_STEPS", Step.get_all())
  145. return ('', 204)
  146. def get_manged_fields_as_array(type_cfg):
  147. result = []
  148. for f in type_cfg.get("properties"):
  149. result.append(f.get("name"))
  150. return result
  151. @cbpi.try_catch(None)
  152. def init_after_startup():
  153. '''
  154. Restart after startup. Check is a step is in state A and reinitialize
  155. :return: None
  156. '''
  157. step = Step.get_by_state('A')
  158. # We have an active step
  159. if step is not None:
  160. # get the type
  161. type_cfg = cbpi.cache.get("step_types").get(step.type)
  162. if type_cfg is None:
  163. # step type not found. cant restart step
  164. return
  165. cfg = step.stepstate.copy()
  166. cfg.update(dict(api=cbpi, id=step.id, managed_fields=get_manged_fields_as_array(type_cfg)))
  167. instance = type_cfg.get("class")(**cfg)
  168. instance.init()
  169. cbpi.cache["active_step"] = instance
  170. @cbpi.initalizer(order=2000)
  171. def init(cbpi):
  172. StepView.register(cbpi.app, route_base='/api/step')
  173. def get_all():
  174. with cbpi.app.app_context():
  175. return Step.get_all()
  176. with cbpi.app.app_context():
  177. init_after_startup()
  178. cbpi.add_cache_callback("steps", get_all)
  179. @cbpi.backgroundtask(key="step_task", interval=0.1)
  180. def execute_step(api):
  181. '''
  182. Background job which executes the step
  183. :return:
  184. '''
  185. with cbpi.app.app_context():
  186. step = cbpi.cache.get("active_step")
  187. if step is not None:
  188. step.execute()
  189. if step.is_dirty():
  190. state = {}
  191. for field in step.managed_fields:
  192. state[field] = step.__getattribute__(field)
  193. Step.update_step_state(step.id, state)
  194. step.reset_dirty()
  195. cbpi.emit("UPDATE_ALL_STEPS", Step.get_all())
  196. if step.n is True:
  197. StepView().start()
  198. cbpi.emit("UPDATE_ALL_STEPS", Step.get_all())