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.

158 linhas
6.3KB

  1. from flask import json, request
  2. from flask_classy import FlaskView, route
  3. from git import Repo, Git
  4. import sqlite3
  5. from modules.app_config import cbpi
  6. from werkzeug.utils import secure_filename
  7. import pprint
  8. import time
  9. import os
  10. from modules.steps import Step,StepView
  11. import xml.etree.ElementTree
  12. class BeerXMLImport(FlaskView):
  13. BEER_XML_FILE = "./upload/beer.xml"
  14. @route('/', methods=['GET'])
  15. def get(self):
  16. if not os.path.exists(self.BEER_XML_FILE):
  17. self.api.notify(headline="File Not Found", message="Please upload a Beer.xml File",
  18. type="danger")
  19. return ('', 404)
  20. result = []
  21. e = xml.etree.ElementTree.parse(self.BEER_XML_FILE).getroot()
  22. result = []
  23. for idx, val in enumerate(e.findall('RECIPE')):
  24. result.append({"id": idx+1, "name": val.find("NAME").text})
  25. return json.dumps(result)
  26. def allowed_file(self, filename):
  27. return '.' in filename and filename.rsplit('.', 1)[1] in set(['xml'])
  28. @route('/upload', methods=['POST'])
  29. def upload_file(self):
  30. try:
  31. if request.method == 'POST':
  32. file = request.files['file']
  33. if file and self.allowed_file(file.filename):
  34. file.save(os.path.join(self.api.app.config['UPLOAD_FOLDER'], "beer.xml"))
  35. self.api.notify(headline="Upload Successful", message="The Beer XML file was uploaded succesfully")
  36. return ('', 204)
  37. return ('', 404)
  38. except Exception as e:
  39. self.api.notify(headline="Upload Failed", message="Failed to upload Beer xml", type="danger")
  40. return ('', 500)
  41. @route('/<int:id>', methods=['POST'])
  42. def load(self, id):
  43. steps = self.getSteps(id)
  44. boil_time_alerts = self.getBoilAlerts(id)
  45. name = self.getRecipeName(id)
  46. self.api.set_config_parameter("brew_name", name)
  47. boil_time = self.getBoilTime(id)
  48. mashstep_type = cbpi.get_config_parameter("step_mash", "MashStep")
  49. mash_kettle = cbpi.get_config_parameter("step_mash_kettle", None)
  50. boilstep_type = cbpi.get_config_parameter("step_boil", "BoilStep")
  51. boil_kettle = cbpi.get_config_parameter("step_boil_kettle", None)
  52. boil_temp = 100 if cbpi.get_config_parameter("unit", "C") == "C" else 212
  53. # READ KBH DATABASE
  54. Step.delete_all()
  55. StepView().reset()
  56. try:
  57. for row in steps:
  58. Step.insert(**{"name": row.get("name"), "type": mashstep_type, "config": {"kettle": mash_kettle, "temp": float(row.get("temp")), "timer": row.get("timer")}})
  59. Step.insert(**{"name": "ChilStep", "type": "ChilStep", "config": {"timer": 15}})
  60. ## Add boiling step
  61. Step.insert(**{
  62. "name": "Boil",
  63. "type": boilstep_type,
  64. "config": {
  65. "kettle": boil_kettle,
  66. "temp": boil_temp,
  67. "timer": boil_time,
  68. ## Beer XML defines additions as the total time spent in boiling,
  69. ## CBP defines it as time-until-alert
  70. ## Also, The model supports five boil-time additions.
  71. ## Set the rest to None to signal them being absent
  72. "hop_1": boil_time - boil_time_alerts[0] if len(boil_time_alerts) >= 1 else None,
  73. "hop_2": boil_time - boil_time_alerts[1] if len(boil_time_alerts) >= 2 else None,
  74. "hop_3": boil_time - boil_time_alerts[2] if len(boil_time_alerts) >= 3 else None,
  75. "hop_4": boil_time - boil_time_alerts[3] if len(boil_time_alerts) >= 4 else None,
  76. "hop_5": boil_time - boil_time_alerts[4] if len(boil_time_alerts) >= 5 else None
  77. }
  78. })
  79. ## Add Whirlpool step
  80. Step.insert(**{"name": "Whirlpool", "type": "ChilStep", "config": {"timer": 15}})
  81. StepView().reset()
  82. self.api.emit("UPDATE_ALL_STEPS", Step.get_all())
  83. self.api.notify(headline="Recipe %s loaded successfully" % name, message="")
  84. except Exception as e:
  85. self.api.notify(headline="Failed to load Recipe", message=e.message, type="danger")
  86. return ('', 500)
  87. return ('', 204)
  88. def getRecipeName(self, id):
  89. e = xml.etree.ElementTree.parse(self.BEER_XML_FILE).getroot()
  90. return e.find('./RECIPE[%s]/NAME' % (str(id))).text
  91. def getBoilTime(self, id):
  92. e = xml.etree.ElementTree.parse(self.BEER_XML_FILE).getroot()
  93. return float(e.find('./RECIPE[%s]/BOIL_TIME' % (str(id))).text)
  94. def getBoilAlerts(self, id):
  95. e = xml.etree.ElementTree.parse(self.BEER_XML_FILE).getroot()
  96. recipe = e.find('./RECIPE[%s]' % (str(id)))
  97. alerts = []
  98. for e in recipe.findall('./HOPS/HOP'):
  99. use = e.find('USE').text
  100. ## Hops which are not used in the boil step should not cause alerts
  101. if use != 'Aroma' and use != 'Boil':
  102. continue
  103. alerts.append(float(e.find('TIME').text))
  104. ## There might also be miscelaneous additions during boild time
  105. for e in recipe.findall('MISCS/MISC[USE="Boil"]'):
  106. alerts.append(float(e.find('TIME').text))
  107. ## Dedupe and order the additions by their time, to prevent multiple alerts at the same time
  108. alerts = sorted(list(set(alerts)))
  109. ## CBP should have these additions in reverse
  110. alerts.reverse()
  111. return alerts
  112. def getSteps(self, id):
  113. e = xml.etree.ElementTree.parse(self.BEER_XML_FILE).getroot()
  114. steps = []
  115. for e in e.findall('./RECIPE[%s]/MASH/MASH_STEPS/MASH_STEP' % (str(id))):
  116. if self.api.get_config_parameter("unit", "C") == "C":
  117. temp = float(e.find("STEP_TEMP").text)
  118. else:
  119. temp = round(9.0 / 5.0 * float(e.find("STEP_TEMP").text) + 32, 2)
  120. if e.find("STEP_TIME").text is None:
  121. stepTime = 0.0
  122. else:
  123. stepTime = float(e.find("STEP_TIME").text)
  124. steps.append({"name": e.find("NAME").text, "temp": temp, "timer": stepTime})
  125. return steps
  126. @cbpi.initalizer()
  127. def init(cbpi):
  128. BeerXMLImport.api = cbpi
  129. BeerXMLImport.register(cbpi.app, route_base='/api/beerxml')