Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

231 linhas
6.6KB

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