import argparse from datetime import date, datetime, timedelta import json import requests import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt import matplotlib.patches as mpatches import numpy as np DAYS_ABBR = ["Mo", "Di", "Mi", "Do", "Fr", "Sa", "So"] def parse_time(string): return datetime.strptime(string, "%Y-%m-%d %H:%M:%S") def plot(raw, target="wiai.png"): data = np.zeros([7, 24]) last = (parse_time(raw[0]['timestamp']), 0) first = last increment = timedelta(hours=1) for log in raw: date = parse_time(log['timestamp']) state = log["doorstate"] delta = date - last[0] if last[1] and delta >= increment: for i in range(1, int(delta / increment)): intermediate = last[0] + (increment * i) data[intermediate.weekday()][intermediate.hour] += last[1] if (not last[0].hour == date.hour) or (date - last[0]) > increment: data[date.weekday()][date.hour] += state last = (date, state) values = np.unique(data.ravel()) fig, ax = plt.subplots() im = ax.imshow(data) ax.set_yticks(np.arange(7)) ax.set_yticklabels(DAYS_ABBR) ax.set_xticks(np.arange(24)) colors = [ im.cmap(im.norm(value)) for value in values ] patches = [ mpatches.Patch(color=colors[i], label=str(values[i])) for i in range(len(values))] plt.legend(handles=patches, bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.) plt.title("Aggregated opening count FS WIAI") plt.figtext(0.5, 0.25, "created: "+str(date.today()), ha="center") plt.figtext(0.5, 0.2, str(first[0])+" → "+str(last[0]), ha="center") plt.savefig(target, format="PNG", transparent=True, bbox_inches="tight") return target def local(target): with open("log") as src: raw = json.load(src) plot(raw,target=target) def prod(target): plot(requests.get('https://isfswiaiopen.wiai.de/log').json(), target=target) def get_plot(target): return plot(requests.get('https://isfswiaiopen.wiai.de/log').json(), target=target) if __name__ == '__main__': parser = argparse.ArgumentParser(description="plot openness of FS WIAI") parser.add_argument('-l', '--local', action='store_true') parser.add_argument('-o', '--output', default="wiai.png") args = parser.parse_args() if args.local: local(args.output) else: prod(args.output)