|
| 1 | +# SPDX-FileCopyrightText: Copyright (c) 2023 Scott Shawcroft for Adafruit Industries |
| 2 | +# |
| 3 | +# SPDX-License-Identifier: Unlicense |
| 4 | + |
| 5 | +import sys |
| 6 | +import time |
| 7 | + |
| 8 | +import adafruit_json_stream as json_stream |
| 9 | + |
| 10 | +# import json_stream |
| 11 | + |
| 12 | + |
| 13 | +class FakeResponse: |
| 14 | + def __init__(self, file): |
| 15 | + self.file = file |
| 16 | + |
| 17 | + def iter_content(self, chunk_size): |
| 18 | + while True: |
| 19 | + yield self.file.read(chunk_size) |
| 20 | + |
| 21 | + |
| 22 | +f = open(sys.argv[1], "rb") # pylint: disable=consider-using-with |
| 23 | +obj = json_stream.load(FakeResponse(f).iter_content(32)) |
| 24 | + |
| 25 | + |
| 26 | +def find_keys(obj, keys): |
| 27 | + """If we don't know the order in which the keys are, |
| 28 | + go through all of them and pick the ones we want""" |
| 29 | + out = dict() |
| 30 | + # iterate on the items of an object |
| 31 | + for key, value in obj.items(): |
| 32 | + if key in keys: |
| 33 | + # if it's a sub object, get it all |
| 34 | + if isinstance(value, json_stream.Transient): |
| 35 | + value = value.as_object() |
| 36 | + out[key] = value |
| 37 | + return out |
| 38 | + |
| 39 | +def time_to_date(stamp): |
| 40 | + tt = time.localtime(stamp) |
| 41 | + month = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"][tt.tm_mon] |
| 42 | + return f"{tt.tm_mday:2d}th of {month}" |
| 43 | + |
| 44 | +def ftoc(temp): |
| 45 | + return (temp - 32) * 5 / 9 |
| 46 | + |
| 47 | +currently = obj["currently"] |
| 48 | +print("Currently:") |
| 49 | +print(" ", time_to_date(currently["time"])) |
| 50 | +print(" ", currently["icon"]) |
| 51 | + |
| 52 | +# iterate on the content of a list |
| 53 | +for i, day in enumerate(obj["daily"]["data"]): |
| 54 | + day_items = find_keys(day, ("time", "summary", "temperatureHigh")) |
| 55 | + date = time_to_date(day_items["time"]) |
| 56 | + print( |
| 57 | + f'On {date}: {day_items["summary"]},', |
| 58 | + f'Max: {int(day_items["temperatureHigh"])}F', |
| 59 | + f'({int(ftoc(day_items["temperatureHigh"]))}C)' |
| 60 | + ) |
| 61 | + |
| 62 | + if i > 4: |
| 63 | + break |
0 commit comments