def get_and_merge_data(sensor_name, nhours): start_time = to_utc() - datetime.timedelta(hours = nhours) end_time = to_utc() value_doc = mongoClient.get_all_sensor_values(sensor_name, start_time.strftime("%Y-%m-%d"), end_time.strftime("%Y-%m-%d")) values = [] for doc in value_doc: values.extend(doc["samples"]) if len(values) == 0: value_doc = None else: value_doc = {'samples': values} if value_doc is None: df = pd.DataFrame({"val": []}) else: if "samples" not in value_doc: df = pd.DataFrame({"val": []}) else: df = pd.DataFrame(value_doc["samples"]) df.index = pd.to_datetime(df['ts'], unit = "s", utc = True) new_index = to_utc() df = df.append(pd.DataFrame(index = [new_index], data = df.tail(1).values, columns = df.columns)) df = df.loc[start_time.strftime("%Y-%m-%d %H:%M"):] if len(df) > 0: df.index = df.index.tz_convert("Europe/Brussels") return df
def make_details(): mcards = [] latest = mongoClient.get_latest_sensor_value("bme1_humidity") mcards.append((dbc.CardImg(src = "assets/humidity_in.png", style = {"width": "50px"}), dbc.CardBody(f"{latest} %"))) latest = mongoClient.get_latest_sensor_value("428F_94_hum") mcards.append((dbc.CardImg(src = "assets/humidity_out.png", style = {"width": "50px"}), dbc.CardBody(f"{latest} %"))) latest = mongoClient.get_latest_sensor_value("bme1_pressure") values = get_and_merge_data("bme1_pressure", 24) values = values.asof(to_utc() - datetime.timedelta(hours = 6))["val"] updown = "stable" if np.abs(latest - values) < 1 else ("up" if (latest - values > 0) else "down") mcards.append((dbc.CardImg(src = f"assets/barometer_in_{updown}.png", style = {"width": "50px"}), dbc.CardBody(html.P(f"{latest} mm Hg")))) obs = owm.get_latest_info()["obs"] feels = obs.temperature("celsius")["feels_like"] mcards.append((dbc.CardImg(src = "assets/feel.png", style = {"width": "50px"}), dbc.CardBody(f"{feels}\u00B0C"))) wind = obs.wind()["speed"] mcards.append((dbc.CardImg(src = "assets/wind.png", style = {"width": "50px"}), dbc.CardBody(f"{wind} km/h"))) rain = obs.rain if len(rain) == 0: rain = "N/A" else: rain = f"{rain['1h']} mm" mcards.append((dbc.CardImg(src = "assets/rain_level.png", style = {"width": "50px"}), dbc.CardBody(f"{rain}"))) return dbc.Row(dbc.CardDeck([dbc.Col(c, width = 5) for c in mcards], className = "weather"))
def __do_update(self): self.last_update = to_utc() self.owm_object["obs"] = self.owm_mgr.weather_at_id( self.city_id).weather self.owm_object["forecast"] = self.owm_mgr.forecast_at_id( self.city_id, '3h')
def check_control(): db = get_db() ctrl_list = db.get_controllers_list() day = to_utc().strftime("%Y-%m-%d") for controller in ctrl_list: ctrl_values = db.get_sensor_values(controller["sensor"], day) if not "setpoint" in ctrl_values: continue last_sp = ctrl_values["setpoint"][-1] if not "samples" in ctrl_values or ctrl_values["samples"][-1][ "val"] != last_sp["val"]: client = get_client() client.publish(f"arduino/cmd/{controller['sensor']}", payload=f"{last_sp['val']}".encode("ASCII"), retain=True)
def get_and_merge_data(sensor_name, sd, ed): value_doc = mongoClient.get_all_sensor_values( sensor_name, dateutil.parser.parse(sd).strftime("%Y-%m-%d"), dateutil.parser.parse(ed).strftime("%Y-%m-%d")) sensor_doc = mongoClient.get_sensor_by_name(sensor_name) values = [] for doc in value_doc: values.extend(doc["samples"]) if len(values) == 0: value_doc = None else: value_doc = {'samples': values} with_setpoint = False if value_doc is None: df = pd.DataFrame({"val": []}) else: if "samples" not in value_doc: df = pd.DataFrame({"val": []}) else: df = pd.DataFrame(value_doc["samples"]) df.index = pd.to_datetime(df['ts'], unit="s", utc=True) if "setpoint" in value_doc: dsp = pd.DataFrame(value_doc["setpoint"]) dsp.index = pd.to_datetime(dsp['ts'], unit="s", utc=True) dsp = dsp.rename(columns={"val": "sp"}) df = pd.merge(df, dsp, how='outer', left_index=True, right_index=True) with_setpoint = True new_index = to_utc() df = df.append( pd.DataFrame(index=[new_index], data=df.tail(1).values, columns=df.columns)) if len(df) > 0: df.index = df.index.tz_convert("Europe/Brussels") min_max = [df.index[0], df.index[-1]] else: min_max = [from_utc(), from_utc()] return df, sensor_doc, min_max, with_setpoint
def check_control(): db = get_db() ctrl_list = db.get_controllers_list() day = to_utc().strftime("%Y-%m-%d") for controller in ctrl_list: ctrl_values = db.get_sensor_values(controller["sensor"], day) if not "setpoint" in ctrl_values: continue last_sp = ctrl_values["setpoint"][-1] if not "samples" in ctrl_values or ctrl_values["samples"][-1][ "val"] != last_sp["val"]: req = requests.put( url=clientAddress, data=f"/api/v1/{controller['sensor']}:{last_sp['val']}\r\n". encode("ASCII"), headers={ "Content-Type": "text/html", "User-Agent": None }) return "<h1>Control updated</h1>" return "<h1>Control checked</h1>"
def get_latest_info(self): if self.last_update is None or ( to_utc() - self.last_update).total_seconds() > 60 * 15: self.__do_update() return self.owm_object
def update_string_metrics(_, sensor_name, control_switches, sd, ed): day = to_utc().strftime("%Y-%m-%d") value_doc = mongoClient.get_sensor_values(sensor_name["sensor"], sd, ed) if not value_doc: return "" return "".join([_["val"] for _ in value_doc["samples"]])
def build_sensor_card(sensor): sensor_element = None if sensor["data-type"] == "string": sensor_element = [ html.H5(sensor["display"]), dcc.Textarea( value='', style={ 'width': '100%', 'height': '300px' }, id={ "type": "string_sensor", "sensor": sensor["sensor"] }, readOnly=True, contentEditable=True, persistence=False, rows=30, ) ] elif sensor["data-type"] == "bool": sensor_element = [ dcc.Graph( id={ "type": "bool_sensor", "sensor": sensor["sensor"] }, # config = {'displayModeBar': False}, animate=True, ) ] if "controller" in sensor and sensor["controller"]: day = to_utc().strftime("%Y-%m-%d") controller_last_value = mongoClient.get_controller_values( sensor["sensor"], day) sensor_element.append( dbc.Checklist( options=[{ "label": "", "value": 1 }], value=[] if (controller_last_value is None or len(controller_last_value) == 0 or controller_last_value[-1]["val"] == 0) else [1], id={ "type": "bool_controller", "sensor": sensor["sensor"] }, switch=True, )) sensor_element.append( html.P(id={ "type": "dummy", "sensor": sensor["sensor"] })) elif sensor["data-type"] == "float": sensor_element = [ dcc.Graph( id={ "type": "float_sensor", "sensor": sensor["sensor"] }, # config = {'displayModeBar': False}, animate=True, ) ] return dbc.Card(sensor_element)