import requests import matplotlib.pyplot as plt from datetime import datetime import json file_path = "history.json" history_url = "http://192.168.178.84:9587/bettwaage/history" convert_time_to_seconds = True # Script data = None if file_path is None: data = requests.get(history_url) data = data.json() else: with open(file_path, "r") as fp: data = json.load(fp) # Experiment: Solving for missing foot with known total weight bed_weight = 78290 person_weight = 63000 known_total_weight = bed_weight + person_weight bed_only_weight = {} for d in data: if d["total"] == bed_weight: bed_only_weight = { "tl": d["tl"], "tr": d["tr"], "bl": bed_weight - (d["tl"] + d["tr"] + d["br"]), "br": d["br"], } break in_bed_data = None threshhold = 100000 min_length = 100 for d in data: t = d["total"] if t >= threshhold: if in_bed_data is None: in_bed_data = [] in_bed_data.append(d) elif in_bed_data is not None: if len(in_bed_data) < min_length: in_bed_data = [] else: break # Calculate bottom left for d in data: d["bl"] = known_total_weight - (d["br"] + d["tr"] + d["tl"]) # Set known total weight d["total"] = known_total_weight data = in_bed_data # Array data x = [d["timestamp"] for d in data] x = [datetime.strptime(d, "%Y-%m-%d %H:%M:%S.%f") for d in x] if convert_time_to_seconds: max_time = max(x) x = [(d - max_time).total_seconds() for d in x] total = [d["total"] for d in data] tl = [d["tl"] for d in data] tr = [d["tr"] for d in data] bl = [d["bl"] for d in data] br = [d["br"] for d in data] top = [l + r for l, r in zip(tl, tr)] bottom = [l + r for l, r in zip(bl, br)] left = [t + b for t, b in zip(tl, bl)] right = [t + b for t, b in zip(tr, br)] # Experiment: Calculate position over time bed_size = (140, 200) left_bed_only = bed_only_weight["tl"] + bed_only_weight["bl"] top_bed_only = bed_only_weight["tr"] + bed_only_weight["tl"] position_over_time = [] for t, l in zip(top, left): position_over_time.append( ( bed_size[0] * (l - left_bed_only) / person_weight, bed_size[1] * (t - top_bed_only) / person_weight, ) ) # Plot data fig, (ax0, ax1) = plt.subplots(nrows=2) ax0.set_xlabel("Time (s)") ax0.set_ylabel("Weight (kg)") ax0.plot(x, total, color="tab:blue") ax0.plot(x, tl, color="tab:red") ax0.plot(x, tr, color="tab:green") ax0.plot(x, bl, color="tab:orange") ax0.plot(x, br, color="tab:purple") ax0.plot(x, top, color="tab:pink") ax0.plot(x, bottom, color="tab:grey") ax0.legend( ["Total", "Top Left", "Top Right", "Bottom Left", "Bottom Right", "Top", "Bottom"] ) # Experiment: Plot position import math import colorsys segments = 100 seg_length = math.ceil(len(position_over_time) / segments) horizontal, vertical = zip(*position_over_time) for i in range(0, segments): low = int(i * seg_length) high = min(int((i + 1) * seg_length), len(position_over_time)) ax1.plot( horizontal[low:high], vertical[low:high], color=colorsys.hsv_to_rgb(i / segments * 0.5, 1, 0.7), linewidth=0.3, ) ax1.set_xlim((0, bed_size[0])) ax1.set_ylim((0, bed_size[1])) ax1.invert_yaxis() plt.show()