From 0f45bb8f57754d1f92a53ae0c53ecb94e701105d Mon Sep 17 00:00:00 2001 From: WorldTeacher <41587052+WorldTeacher@users.noreply.github.com> Date: Wed, 23 Oct 2024 10:30:20 +0200 Subject: [PATCH] add internal converter function --- src/convert.py | 45 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 src/convert.py diff --git a/src/convert.py b/src/convert.py new file mode 100644 index 0000000..845a317 --- /dev/null +++ b/src/convert.py @@ -0,0 +1,45 @@ +import json +import datetime +import os +import sys + +def unix_to_real(unix): + return datetime.datetime.fromtimestamp(unix/1000).strftime('%Y-%m-%d %H:%M:%S') + +def list_to_dict(input): + output = {} + #take the input and split the timestamp date from the time + for i in input: + sensor = i["sensor"] + date = i["timestamp"].split(" ")[0] + time = i["timestamp"].split(" ")[1] + #check if sensor is not in output + if sensor not in output: + output[sensor] = {} + #check if date is not in output for the sensor + if date not in output[sensor]: + output[sensor][date] = {"on": [], "off": []} + #check if the state is on or off + if i["state"] == "on": + output[sensor][date]["on"].append(time) + else: + output[sensor][date]["off"].append(time) + return output + +def convert_to_dict(file): + with open(file, "r") as f: + data = f.read() + lines = data.split("\n") + line_data = [] + for line in lines: + if line == "" or not line.startswith("{"): + continue + data = {} + line = json.loads(line) + data["state"] = line["payload"] + data["timestamp"] = unix_to_real(line["detected"]) + data["sensor"] = line["data"]["entity_id"] + line_data.append(data) + #convert the list to a dict + data = list_to_dict(line_data) + return data \ No newline at end of file