def init(cbpi): global pushover cbpi.app.logger.info("INITIALIZE Pushover PLUGIN") pushoverUser() pushoverToken() if pushover_token is None or not pushover_token: cbpi.notify("Pushover Error", "Check Pushover API Token is set", type="danger", timeout=None) elif pushover_user is None or not pushover_user: cbpi.notify("Pushover Error", "Check Pushover User Key is set", type="danger", timeout=None) else: pushover = "OK"
def init(cbpi): cbpi.app.logger.info("Initialize TPLink") getUser() if username == "": cbpi.notify( "TPLink Error", "Unable to read TP Link config, update CraftBeerPi Parameter settings and reboot.", type="danger", timeout=None) return getToken() global TPplugs if (tplink_token != None and tplink_token != ""): TPplugs = getPlugs() else: TPplugs = [] cbpi.app.logger.info("Initialize TPLink - Done -")
def getjson(ip, data_load): log("Local TP Link %s / %s" % (ip, data_load)) port = 9999 try: sock_tcp = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock_tcp.connect((ip, port)) sock_tcp.send(encrypt(data_load)) data = sock_tcp.recv(2048) sock_tcp.close() return decrypt(data[4:]) except socket.error: log("Could not connect to host %s:%s" % (ip, port)) cbpi.notify("TPLink Local IP Error", "Check local ip address or remove to use Cloud.", type="danger", timeout=10000) return False
def ThingspeakUpdate(data): global thingspeak_ok global drop_first url = "api.thingspeak.com" if thingspeak_ok is None: thingspeakFields() thingspeak_ok = True if (thingspeak_api_write == ""): log("ThingSpeak Write API not got from site") cbpi.notify("ThingSpeak Error", "Please try to update config parameter and reboot.", type="danger") return False path = "/update.json" data_api = "{'api_key':'%s'" % thingspeak_api_write data = data_api + data result = httpCon(url, path, data)
def on(self, power=None): """Switch the actor on. Set the power to the given value or the current power setting.""" channel = int(self.b_channel) if self.d_power_ctrl == "Actor": self.api.switch_actor_on(int(self.e_power_actor)) self.state = 1 if power: self.set_power(power) else: self.dac.set_value(channel, self.value) if self.z_debug == "On": value = self.dac.get_value(channel) cbpi.notify("MCP4728 Current Value", "Channel {:d}: Value {:d}".format(channel, value), timeout=self.timeout)
def init_TPLink(MyUUID4): log("Get token for TPLink") url = "https://wap.tplinkcloud.com" data_input = '{ "method": "login", "params": { "appType": "Kasa_Android", "cloudUserName": "******", "cloudPassword": "******", "terminalUUID": "%s" } }' data_input = data_input % (username, password, MyUUID4) ## Sending http command "" my_response = httpTPlink(url, data_input) if my_response == False: return False # log("Response %s" % my_response) if (my_response["error_code"] >= 0): token = my_response["result"]["token"] else: token = "" err = my_response["msg"] cbpi.notify("TPLinkPlug Error", err, type="danger", timeout=10000) return token
def getPlugs(): cbpi.app.logger.info("Get TP Plugs IDs") arr = [] url = "https://wap.tplinkcloud.com?token=%s" % (tplink_token) data_input = '{"method":"getDeviceList"}' resp = httpTPlink(url, data_input) if resp == False: return [] try: deviceList = resp["result"]["deviceList"] except: cbpi.notify("TPLink Error", "Unable to read device list from cloud, check token.", type="danger", timeout=None) deviceList = [] return deviceList
def BM_RecipeCreation(): global bm_recipe_creation bm_recipe_creation = cbpi.get_config_parameter("bm_recipe_creation", None) if bm_recipe_creation is None: print("INIT BM Recipe Creation Flag") try: cbpi.add_config_parameter("bm_recipe_creation", "NO", "select", "Braumeister Recipe Creation Flag", ["YES", "NO"]) bm_recipe_creation = cbpi.get_config_parameter( "bm_recipe_creation", None) except: cbpi.notify( "Braumeister Error", "Unable to update database. Update CraftBeerPi and reboot.", type="danger", timeout=None)
def toggle(self, id): fermenter = cbpi.cache.get(self.cache_key)[id] try: if fermenter.state is False: # Start controller if fermenter.logic is not None: cfg = fermenter.config.copy() cfg.update( dict(api=cbpi, fermenter_id=fermenter.id, heater=fermenter.heater, sensor=fermenter.sensor)) instance = cbpi.get_fermentation_controller( fermenter.logic).get("class")(**cfg) instance.init() fermenter.instance = instance #print "auomatic run......" #lcp def run(instance): instance.run() fermenter.state = not fermenter.state cbpi.emit("UPDATE_FERMENTER", cbpi.cache.get(self.cache_key).get(id)) t = cbpi.socketio.start_background_task(target=run, instance=instance) fermenter.state = not fermenter.state cbpi.emit("UPDATE_FERMENTER", cbpi.cache.get(self.cache_key).get(id)) else: # Stop controller fermenter.instance.stop() fermenter.state = not fermenter.state cbpi.emit("UPDATE_FERMENTER", cbpi.cache.get(self.cache_key).get(id)) except Exception as e: print e cbpi.notify("Toogle Fementer Controller failed", "Pleae check the %s configuration" % fermenter.name, type="danger", timeout=None) return ('', 500) return ('', 204)
def set_power(self, power): """Set the power as a percentage of the range between minimum and maximum power""" channel = int(self.b_channel) self.power = power self.value = int((4095 * power) / 100) if self.d_power_ctrl == "Zero DAC": if self.state == 0: pass elif self.state == 1: self.dac.set_value(channel, self.value) else: self.dac.set_value(channel, self.value) if self.z_debug == "On": value = self.dac.get_value(channel) cbpi.notify("MCP4728 Set Value", "Channel {:d}: Value {:d}".format(channel, value), timeout=self.timeout)
def httpTPlink(url, data_load): log("Cloud TP Link %s / %s" % (url, data_load)) try: data = json.loads(data_load) req = urllib2.Request("%s" % (url)) req.add_header('Content-Type', 'application/json') resp = urllib2.urlopen(req, json.dumps(data)) json_object = resp.read() response_dict = json.loads(json_object) return response_dict except Exception as e: cbpi.app.logger.error("FAILED when contacting TP Link site: %s" % (url)) cbpi.notify("TPLink http Error", "Check username and password.", type="danger", timeout=10000) return False
def UbidotsUpdate(data): global ubidots_token global ubidots_label log("Ubidots update") url = "http://things.ubidots.com" if (ubidots_token == "" or ubidots_label == ""): log("Ubidots Token or label incorrect") cbpi.notify("Ubidots Error", "Please try to update config parameter and reboot.", type="danger") return False for count, (key, value) in enumerate(cbpi.cache["kettle"].iteritems(), 1): if value.target_temp is not None: data += ", \"target_temp_%s\":%s" % (count,value.target_temp) for count, (key, value) in enumerate(cbpi.cache["actors"].iteritems(), 1): if value.state is not None: data += ", \"actor_%s\":%s" % (value.name,value.state) data += "}" path = "/api/v1.6/devices/%s/" % ubidots_label param = "{'token':'%s'}" % ubidots_token result = httpJSON(url, path, param, data)
def init(cbpi): log("Auto Starting Fermenters...") config = get_config() if config['auto_start_fermenter_enabled'] != 'YES': log("\tAuto Start not enabled.") return fermenter_ids = [ int(fid.strip()) for fid in config['auto_start_fermenter_list'].split(',') ] if not fermenter_ids: log("\tFermenter list is empty. Please set the auto_start_fermenter_list parameter." ) return for fid in fermenter_ids: fermenter = FermenterView().get_fermenter(fid) if not fermenter: log("No fermenter id [{}] could be found, skipping.".format(fid)) continue log("Toggling fermenter, Name: {}, CURRENT STATE: {}".format( fermenter.name, fermenter.state)) FermenterView().toggle(fid) log("Toggling fermenter, Name: {}, CURRENT STATE: {}".format( fermenter.name, fermenter.state)) if fermenter.state == True: log("Auto start fermenter [{}], id [{}] success!".format( fermenter.name, fid)) cbpi.notify("auto_start_fermentation", "Auto start fermenter [{}], id [{}] success!".format( fermenter.name, fid), type="success", timeout=None) else: log("Auto start fermenter [{}], id [{}] failed!".format( fermenter.name, fid)) cbpi.notify("auto_start_fermentation", "Auto start fermenter [{}], id [{}] failed!".format( fermenter.name, fid), type="danger", timeout=None)
def __init__(self, gpio): self.count = 0 self.last = self.prior = 0.0 try: GPIO.setup(gpio, GPIO.IN, pull_up_down=GPIO.PUD_UP) GPIO.add_event_detect(gpio, GPIO.RISING, callback=self.pulse_input, bouncetime=20) cbpi.app.logger.info( "FlowSensor pulse counter initialized for GPIO {}".format( gpio)) except Exception as e: cbpi.notify("Failure to initialize FlowSensor pulse counter", "Could not create callback for GPIO {}".format(gpio), type="danger", timeout="None") cbpi.app.logger.error( "Failure to initialize FlowSensor pulse counter \n{}".format( e))
def httpCon(url, path='', data_load='', meth='GET'): log("%s to URL %s - %s - %s" % (meth, url, path, data_load)) try: data_load = eval(data_load) params = urllib.urlencode(data_load) conn = httplib.HTTPSConnection(url) path += "?" + params if params != "" else "" log("Path: %s" % path) conn.request(meth, path) response = conn.getresponse() try: json_result = response.read() json_result = json.loads(json_result) return json_result except Exception as e: return response except Exception as e: cbpi.app.logger.error("FAILED when contacting site: %s" % (url)) cbpi.notify("IOT Error", "Check API and Channel ID.", type="danger", timeout=10000) return False
def send(self, command): print((self.key)) if self.key is None or self.key == '': cbpi.notify("IFTTT Key Error", "The IFTTT maker key must be set", type="warning", timeout=None) url = self.ifttt_url.format(command, self.key) try: response = requests.get(url) response.raise_for_status() except requests.exceptions.RequestException as err: cbpi.notify( "IFTTT Send Error", "There was an error sending the request to IFTTT. Please check your key", type="danger", timeout=20000) self.api.app.logger.error( "FAILED to switch IFTTT actor: {}".format(command))
def init(cbpi): cbpi.app.logger.info("brewfather_iSpindel plugin Initialize") log("Brewfather_iSpindel params") # the unique id value (the bit following id= in the "Cloud URL" in the setting screen global brewfather_iSpindel_id brewfather_iSpindel_id = cbpi.get_config_parameter( "brewfather_iSpindel_id", None) log("Brewfather brewfather_iSpindel_id %s" % brewfather_iSpindel_id) if brewfather_iSpindel_id is None: log("Init brewfather_iSpindel config URL") try: # TODO: is param2 a default value? cbpi.add_config_parameter("brewfather_iSpindel_id", "", "text", "Brewfather_iSpindel id") except: cbpi.notify("Brewfather_iSpindel Error", "Unable to update Brewfather_iSpindel id parameter", type="danger") log("Brewfather_iSpindel params ends")
def brewersfriend_background_task(api): api_key = bf_api_key() if api_key == "": cbpi.notify( "Brewer's Friend Error", "API key not set. Update brewersfriend_api_key parameter within System > Parameters.", type="danger", timeout=None) return for i, fermenter in cbpi.cache.get("fermenter").items(): if fermenter.state is not False: try: name = fermenter.name temp = fermenter.instance.get_temp() unit = cbpi.get_config_parameter("unit", "C") data = {"name": name, "temp": temp, "temp_unit": unit} response = requests.post(bf_uri + api_key, json=data) if response.status_code != 200: cbpi.notify( "Brewer's Friend Error", "Received unsuccessful response. Ensure API key is correct. HTTP Error Code: " + str(response.status_code), type="danger", timeout=None) except: cbpi.notify("Brewer's Friend Error", "Unable to send message.", type="danger", timeout=None) pass
def thingspeakFields(): global thingspeak_ok global thingspeak_api global thingspeak_api_write url = "api.thingspeak.com" if (thingspeak_api == "" or thingspeak_chnid == ""): log("ThingSpeak Config error") cbpi.notify("ThingSpeak Error", "Please update config parameter", type="danger") return False brewery_name = cbpi.get_config_parameter("brewery_name", "CraftBeerPi") data_api = "{'api_key':'%s'" % thingspeak_api path = "/channels/%s.json" % thingspeak_chnid result = httpCon(url, path, data_api + "}") log("JSON: %s" % result) data = "" data += Fillfield(result, "tags", "Brew, CraftBeerPi, Beer, RaspBerryPi") data += Fillfield( result, "description", "The CraftBeerPi temperature sensor logging for the brewery %s." % brewery_name) path = "/channels/%s/feeds.json" % thingspeak_chnid result = httpCon(url, path, data_api + ", 'results':'0'}") log("JSON: %s" % result) path = "/channels/%s.json" % thingspeak_chnid cnt = 1 for key, value in list(cbpi.cache.get("sensors").items()): field = 'field%s' % cnt try: data += Fillfield(result["channel"], field, value.name) except: data += Fillfield({}, field, value.name) cnt += 1 data += "}" data = data_api + data result = httpCon(url, path, data, 'PUT') thingspeak_api_write = result["api_keys"][0]["api_key"] log("API Write: %s" % thingspeak_api_write)
def actor_execute(api): global function_actor_ids for id in function_actor_ids: actor = cbpi.cache.get("actors").get(id) #test for deleted Func actor if actor is None: function_actor_ids.remove(id) else: try: # try to call execute. Remove if execute fails. Added back when settings updated actor.instance.execute_func() except Exception as e: traceback.print_exc() cbpi.notify( "Actor Error", "Failed to execute actor %s. Please update the configuraiton" % actor.name, type="danger", timeout=0) cbpi.app.logger.error( "Execute of Actor %s failed, removed from execute list" % id) function_actor_ids.remove(id)
def start(self): active = Step.get_by_state("A") inactive = Step.get_by_state('I') if (active is not None): active.state = 'D' active.end = int(time.time()) self.stop_step() Step.update(**active.__dict__) if (inactive is not None): self.init_step(inactive) inactive.state = 'A' inactive.stepstate = inactive.config inactive.start = int(time.time()) Step.update(**inactive.__dict__) else: cbpi.log_action("Brewing Finished") cbpi.notify("Brewing Finished", "You are done!", timeout=None) cbpi.emit("UPDATE_ALL_STEPS", Step.get_all()) return ('', 204)
def NotifyStats(name, ip, url, device): log("TPLink Notify") if ip == "": data_load = '{"method":"passthrough", "params": {"deviceId": "%s", "requestData": "{\\"system\\":{\\"get_sysinfo\\":null},\\"emeter\\":{\\"get_realtime\\":null}}"}}' % device else: data_load = '{"system":{"get_sysinfo":null},"emeter":{"get_realtime":{}},"time":{"get_time":null}}' resp = receive(data_load, ip, url) resp = json.loads(resp) output = "" if "system" in resp: sysinfo = resp["system"]["get_sysinfo"] relay_state = sysinfo["relay_state"] output += "Plug is " output += "On" if relay_state == 1 else "Off" timeon = sysinfo["on_time"] output += " for %s" % ddhhmmss(timeon) output += ". " if "emeter" in resp: emeter = resp["emeter"]["get_realtime"] output += "Voltage %.1fV, Current %.1fA Power %.0fW, Total %.2fkWh" % (emeter["voltage"], emeter["current"], emeter["power"],emeter["total"]) if len(output) > 5: cbpi.notify("TPLinkPlug %s (%s)" % (name, sysinfo["alias"]), output, timeout = 90000)
def setAutoMode(self, auto_state): try: kettle = cbpi.cache.get("kettle")[int(self.kettle)] if (kettle.state is False) and (auto_state is True): # turn on if kettle.logic is not None: cfg = kettle.config.copy() cfg.update( dict(api=cbpi, kettle_id=kettle.id, heater=kettle.heater, sensor=kettle.sensor)) instance = cbpi.get_controller( kettle.logic).get("class")(**cfg) instance.init() kettle.instance = instance def run(instance): instance.run() t = cbpi.socketio.start_background_task(target=run, instance=instance) kettle.state = not kettle.state cbpi.emit("UPDATE_KETTLE", cbpi.cache.get("kettle")[int(self.kettle)]) elif (kettle.state is True) and (auto_state is False): # turn off kettle.instance.stop() kettle.state = not kettle.state cbpi.emit("UPDATE_KETTLE", cbpi.cache.get("kettle")[int(self.kettle)]) except Exception as e: cbpi.notify("Error", "Failed to set Auto mode {}".format(["OFF", "ON" ][auto_state]), type="danger", timeout=None) cbpi.app.logger.error(e)
def init(cbpi): cbpi.app.logger.info("brewfather plugin Initialize") log("Brewfather params") # the comment that goes along with each post (visible in the edit data screen) global brewfather_tilt_comment # the unique id value (the bit following id= in the "Cloud URL" in the setting screen global brewfather_tilt_id brewfather_tilt_comment = cbpi.get_config_parameter( "brewfather_tilt_comment", None) log("Brewfather brewfather_tilt_comment %s" % brewfather_tilt_comment) brewfather_tilt_id = cbpi.get_config_parameter("brewfather_tilt_id", None) log("Brewfather brewfather_tilt_id %s" % brewfather_tilt_id) if brewfather_tilt_comment is None: log("Init brewfather config Comment") try: # TODO: is param2 a default value? cbpi.add_config_parameter("brewfather_tilt_comment", "", "text", "Brewfather comment") except: cbpi.notify("Brewfather Error", "Unable to update Brewfather comment parameter", type="danger") if brewfather_tilt_id is None: log("Init brewfather config URL") try: # TODO: is param2 a default value? cbpi.add_config_parameter("brewfather_tilt_id", "", "text", "Brewfather id") except: cbpi.notify("Brewfather Error", "Unable to update Brewfather id parameter", type="danger") log("Brewfather params ends")
def init(cbpi): cbpi.app.logger.info("LittleBock_iSpindel plugin Initialize") log("LittleBock_iSpindel params") # The Base URL Value for your iSpindel # On the iSpindle page on LittleBock, in Server URL you'll see # /api/log/ispindle/XXX/YYY # base_url is XXX global littleBock_base_url littleBock_base_url = cbpi.get_config_parameter( "littleBock_base_url", None) log("LittleBock littleBock_base_url %s" % littleBock_base_url) if littleBock_base_url is None: log("Init littleBock_base_url config URL") try: cbpi.add_config_parameter( "littleBock_base_url", "", "text", "LittleBock base URL /api/log/ispindel/XXX") except: cbpi.notify("LittleBock_iSpindel Error", "Unable to update LittleBock_iSpindel base_url parameter", type="danger") global littleBock_iSpindel_xRef littleBock_iSpindel_xRef = cbpi.get_config_parameter( "littleBock_iSpindel_xRef", None) log("littleBock_iSpindel_xRef %s" % littleBock_iSpindel_xRef) if littleBock_iSpindel_xRef is None: log("Init littleBock_iSpindel_xRef XRef Table") try: cbpi.add_config_parameter( "littleBock_iSpindel_xRef", "", "text", "LittleBock/iSpindel XRef Table. /api/log/ispindel/XXX/YYY. Must be list of iSpindel/YYY separated by , ") except: cbpi.notify("LittleBock_iSpindel Error", "Unable to update LittleBock_iSpindel xRef parameter", type="danger") log("LittleBock_iSpindel params ends")
def reset_sensor(self): ser.write('s\n') line = ser.read_until('\n') if "ok" in line: cbpi.notify("Sensor Reset", "Sensor reset successfull!", "info", timeout=None) else: cbpi.notify("Sensor Reset", "Sensor reset failed!", "danger", timeout=None) cbpi.notify("Sensor says", str(line), "info", timeout=None) pass
def brewfather_background_task(api): api_id = bf_api_id() if api_id == "": cbpi.notify( "Brewfather Error", "Id not set. Update brewfather_api_id parameter within System > Parameters.", type="danger", timeout=None) return for i, fermenter in cbpi.cache.get("fermenter").iteritems(): # if we have a beer name, we will log the temperatures if fermenter.brewname and fermenter.brewname.strip(): try: queryString = {"id": api_id} data = { "name": fermenter.name, "beer": fermenter.brewname, "temp": cbpi.get_sensor_value(fermenter.sensor), "aux_temp": cbpi.get_sensor_value(fermenter.sensor2), "ext_temp": cbpi.get_sensor_value(fermenter.sensor3), "temp_unit": cbpi.get_config_parameter("unit", "C") } response = requests.post(bf_uri, params=queryString, json=data) if response.status_code != 200: cbpi.notify( "Brewfather Error", "Received unsuccessful response. Ensure API Id is correct. HTTP Error Code: " + str(response.status_code), type="danger", timeout=None) except BaseException as error: cbpi.notify("Brewfather Error", "Unable to send message." + str(error), type="danger", timeout=None) pass
def ferm_supervisor_background_task(a): auto_start = cbpi.cache['config']["auto_start"].value for key, value in cbpi.cache.get("fermenter").iteritems(): #print key, " ", value.name if hasattr(value, 'instance'): #print value.instance.alarmed if value.instance.alarmed == 1 and value.instance.alarm_time < time.time( ): # set time for next notificacion if value.instance.rep_time > 0: value.instance.alarm_time = time.time() + float( value.instance.rep_time) * 60 else: # or never notify again value.instance.rep_time = 999999999999 stemp = cbpi.cache['sensors'][int( value.sensor)].instance.last_value server = smtplib.SMTP( cbpi.cache['config']['mail_server'].value, int(cbpi.cache['config']['mail_port'].value)) server.starttls() server.login(cbpi.cache['config']['mail_user'].value, cbpi.cache['config']['mail_psw'].value) msg = "Subject: CraftBeerPi Alarm \r\n\r\n Alarm on " + value.name + " temp " + stemp.__str__( ) + " set point " + value.target_temp.__str__( ) + " at " + strftime("%H:%M:%S on %Y %b %d ", localtime()) server.sendmail(cbpi.cache['config']['mail_user'].value, cbpi.cache['config']['mail_dest'].value, msg) server.quit() if auto_start == 'Yes' and (not value.state) and len(value.steps) > 0: for step in value.steps: if step.state == "A": print "Starting ", key, step.state try: print value.state # Start controller if value.logic is not None: cfg = value.config.copy() cfg.update( dict(api=cbpi, fermenter_id=value.id, heater=value.heater, sensor=value.sensor)) instance = cbpi.get_fermentation_controller( value.logic).get("class")(**cfg) instance.init() value.instance = instance def run(instance): instance.run() t = cbpi.socketio.start_background_task( target=run, instance=instance) value.state = not value.state cbpi.emit("UPDATE_FERMENTER", value) except Exception as e: print e cbpi.notify("Toogle Fementer Controller failed", "Pleae check the %s configuration" % value.name, type="danger", timeout=None) pass pass
def init(cbpi): cbpi.app.logger.info("brewfather plugin Initialize") log("Brewfather params") # the comment that goes along with each post (visible in the edit data screen) global brewfather_comment # the unique id value (the bit following id= in the "Cloud URL" in the setting screen global brewfather_id # 2018.11.09 - Remove _beer parameters and processing # the batch number for the Red Tilt # global brewfather_RED_beer # the batch number for the Pink Tilt # I guess for now you just keep adding these for each additonal tilt # global brewfather_PINK_beer # 2018.11.09 - End Changed code brewfather_comment = cbpi.get_config_parameter("brewfather_comment", None) log("Brewfather brewfather_comment %s" % brewfather_comment) brewfather_id = cbpi.get_config_parameter("brewfather_id", None) log("Brewfather brewfather_id %s" % brewfather_id) # 2018.11.09 - Remove _beer parameters and processing # brewfather_RED_beer = cbpi.get_config_parameter("brewfather_RED_beer", None) # log("Brewfather brewfather_RED_beer %s" % brewfather_RED_beer) # brewfather_PINK_beer = cbpi.get_config_parameter("brewfather_PINK_beer", None) # log("Brewfather brewfather_PINK_beer %s" % brewfather_PINK_beer) # 2018.11.09 - End Changed code if brewfather_comment is None: log("Init brewfather config Comment") try: # TODO: is param2 a default value? cbpi.add_config_parameter("brewfather_comment", "", "text", "Brewfather comment") except: cbpi.notify("Brewfather Error", "Unable to update Brewfather comment parameter", type="danger") if brewfather_id is None: log("Init brewfather config URL") try: # TODO: is param2 a default value? cbpi.add_config_parameter("brewfather_id", "", "text", "Brewfather id") except: cbpi.notify("Brewfather Error", "Unable to update Brewfather id parameter", type="danger") # 2018.11.09 - Remove _beer parameters and processing # if brewfather_RED_beer is None: # log("Init brewfather config RED_beer") # try: ## TODO: is param2 a default value? # cbpi.add_config_parameter("brewfather_RED_beer", "", "text", "Brewfather RED_beer") # except: # cbpi.notify("Brewfather Error", "Unable to update Brewfather RED_beer parameter", type="danger") # if brewfather_PINK_beer is None: # log("Init brewfather config PINK_beer") # try: ## TODO: is param2 a default value? # cbpi.add_config_parameter("brewfather_PINK_beer", "", "text", "Brewfather PINK_beer") # except: # cbpi.notify("Brewfather Error", "Unable to update Brewfather PINK_beer parameter", type="danger") # 2018.11.09 - End Changed code log("Brewfather params ends")
def brewerschronicle_background_task(api): api_key = bc_api_key() if api_key == "": return for i, fermenter in list(cbpi.cache.get("fermenter").items()): if fermenter.state is not False: try: writeReadingsToBC = True logBC(" ") try: fermentInfo_uri = bc_base_uri + "fermentLogs/GetFermentLogInfoByAssetName" data = { "AssetName": fermenter.name, "AssetAPIId": fermenter.name, "ReadingValue": "", "ControlSoftwareName": "CraftBeerPi" } headers = { 'content-type': 'application/json', 'Authorization': 'Bearer ' + api_key } response = requests.post(fermentInfo_uri, json=data, headers=headers, timeout=1) responseData = response.json() logBC("response.status_code: {0}".format( response.status_code)) if response.status_code == 400 or response.status_code == 500: brewName = "" targetTemperature = -50.0 currentGravity = "-" else: logBC("trying to get responseData") brewName = responseData['Name'] targetTemperature = responseData['TargetTemperature'] currentGravity = responseData['LatestGravity'] if currentGravity == None: currentGravity = "-" try: set_name_uri = "http://localhost:5000/api/fermenter/{0}/brewname".format( fermenter.id) headers = {'content-type': 'application/json'} data = {"brewname": brewName} requests.post(set_name_uri, json=data, headers=headers, timeout=1) except Exception as e: logBC("exception writing brew name: {0}".format(e)) pass try: if targetTemperature == -50.0: targetTemperature = fermenter.instance.get_target_temp( ) if targetTemperature != -50.0: targetTemp_api_url = "http://localhost:5000/api/fermenter/{0}/targettemp/{1}".format( fermenter.id, targetTemperature) headers = {'content-type': 'application/json'} requests.post(targetTemp_api_url, data="", headers=headers, timeout=1) except Exception as e: logBC( "exception writing target temp to CBPi from BC info: {0}" .format(e)) pass cbpi.cache['sensors'][int( fermenter.sensor3)].instance.gravity = currentGravity if bool(writeReadingsToBC) is True: logBC("writing readings to BC") try: bc_post_reading = bc_base_uri + "fermentLogs/PostReadingByAPIId" temp = fermenter.instance.get_temp() sensorName = cbpi.cache['sensors'][int( fermenter.sensor)].name data = { "AssetName": fermenter.name, "AssetAPIId": sensorName, "ReadingValue": temp, "ControlSoftwareName": "CraftBeerPi" } headers = { 'content-type': 'application/json', 'Authorization': 'Bearer ' + api_key } response = requests.post(bc_post_reading, json=data, headers=headers, timeout=1) if response.status_code == 400: cbpi.notify("BC", response.content, type="danger", timeout=30000) if targetTemperature != -50.0: logBC("logging target temp") sensorName = fermenter.name + " target temp" data = { "AssetName": fermenter.name, "AssetAPIId": sensorName, "ReadingValue": targetTemperature, "ControlSoftwareName": "CraftBeerPi" } headers = { 'content-type': 'application/json', 'Authorization': 'Bearer ' + api_key } response = requests.post(bc_post_reading, json=data, headers=headers, timeout=1) cbpi.notify( "Brewers Chronicle", "Readings for fermentor {0} submitted to Brewers Chronicle" .format(fermenter.name), timeout=15000) logBC("readings written successfully to BC") except Exception as e: logBC( "exception writing target temp to BrewersChronicle: {0}" .format(e)) pass except Exception as e: logBC("exception getting info from BC: {0}".format(e)) except Exception as e: logBC("Exception: {0}".format(e)) pass