Skip to content

Commit 053e9f1

Browse files
committed
Add additional functions and error handling
1 parent f98d5c3 commit 053e9f1

File tree

4 files changed

+89
-30
lines changed

4 files changed

+89
-30
lines changed
Binary file not shown.

esp32/app/ili9341.py

Lines changed: 53 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
"""
44

55
import cmath
6+
import ujson
67
from gui.fonts import arial10, arial35, freesans20
78
from gui.core.writer import CWriter
89
from gui.core.fplot import CartesianGraph, TSequence
@@ -23,6 +24,10 @@ def __init__(self):
2324
"""
2425
Constructor
2526
"""
27+
28+
with open("config.json", "r") as f:
29+
self.config = ujson.load(f)
30+
2631
y_axis_division = [249, 225, 202, 179, 155]
2732
x_axis_division = [15, 30, 48, 66, 83, 98, 115, 133, 150, 168, 186, 204]
2833
arrows_division = [
@@ -125,6 +130,24 @@ def __init__(self):
125130
arrow_label = Label(self.wri, 279, arrow, "^", fgcolor=BLACK, align=2)
126131
self.arrows[f"arrow_{hour}"] = arrow_label
127132

133+
@staticmethod
134+
def set_error():
135+
# type: () -> None
136+
"""
137+
Set config error message on the display.
138+
"""
139+
refresh(ssd, True)
140+
141+
Label(
142+
CWriter(ssd, arial35, RED, BLACK, verbose=False),
143+
30,
144+
15,
145+
"Config Error!",
146+
align=2,
147+
)
148+
149+
refresh(ssd)
150+
128151
def plot_prices(self, prices_today, prices_tomorrow):
129152
# type: (list, list) -> None
130153
"""
@@ -157,15 +180,24 @@ def set_price(self, current_hour, prices_today):
157180

158181
price_levels = ("Billigt", "Normalt", "Dyrt")
159182

160-
if prices_today[current_hour] < 0.5:
161-
color = GREEN
162-
price = price_levels[0]
163-
elif 0.5 <= prices_today[current_hour] < 1.5:
164-
color = YELLOW
165-
price = price_levels[1]
166-
else:
167-
color = RED
168-
price = price_levels[2]
183+
try:
184+
if prices_today[current_hour] < self.config["billigt<"]:
185+
color = GREEN
186+
price = price_levels[0]
187+
elif (
188+
self.config["billigt<"]
189+
<= prices_today[current_hour]
190+
< self.config["normalt<"]
191+
):
192+
color = YELLOW
193+
price = price_levels[1]
194+
else:
195+
color = RED
196+
price = price_levels[2]
197+
except (TypeError, KeyError, IndexError) as e:
198+
print(f"Error in config file: {e}")
199+
GUI.set_error()
200+
raise
169201

170202
cost = prices_today[current_hour]
171203

@@ -205,25 +237,25 @@ def set_clock(self):
205237
uv = lambda phi: cmath.rect(1, phi)
206238
pi = cmath.pi
207239
days = (
208-
"Monday",
209-
"Tuesday",
210-
"Wednesday",
211-
"Thursday",
212-
"Friday",
213-
"Saturday",
214-
"Sunday",
240+
"Måndag",
241+
"Tisdag",
242+
"Onsdag",
243+
"Torsdag",
244+
"Fredag",
245+
"Lördag",
246+
"Söndag",
215247
)
216248
months = (
217249
"Jan",
218250
"Feb",
219-
"March",
251+
"Mar",
220252
"April",
221-
"May",
222-
"June",
223-
"July",
253+
"Maj",
254+
"Juni",
255+
"Juli",
224256
"Aug",
225257
"Sept",
226-
"Oct",
258+
"Okt",
227259
"Nov",
228260
"Dec",
229261
)

esp32/app/price.py

Lines changed: 18 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,10 +2,10 @@
22
Instantiates class to fetch spot prices.
33
"""
44

5-
from datetime import datetime, timedelta, timezone
65
import urequests
76
import ujson
87
import machine
8+
from datetime import datetime, timedelta, timezone
99

1010
DAYS = (
1111
datetime.now(timezone(timedelta())),
@@ -43,6 +43,20 @@ def get_url(self):
4343
for day in DAYS
4444
]
4545

46+
def get_url_tomorrow(self):
47+
# type: () -> str
48+
"""
49+
Get the URL for the API for tomorrow which causes desplay to reboot.
50+
51+
Returns:
52+
str: A URL for fetching the electricity prices for tomorrow.
53+
54+
"""
55+
56+
tomorrow = datetime.now(timezone(timedelta())) + timedelta(hours=24)
57+
58+
return f"{self.config['url']}{self.config['api']}{tomorrow.year:04}/{tomorrow.month:02}-{tomorrow.day:02}_{self.config['zone']}.json"
59+
4660
def get_prices(self):
4761
# type: () -> None
4862
"""
@@ -64,10 +78,12 @@ def get_prices(self):
6478
]
6579
}
6680
)
81+
response.close()
6782
else:
6883
print(
69-
f"Failed to fetch JSON, status code: {response.status_code}\nPrices might not be published yet."
84+
f"Failed to fetch JSON, status code: {response.status_code}\nPrices might not be published yet or URL is incorrect."
7085
)
86+
response.close()
7187
continue
7288

7389
except OSError as e:

esp32/app/utils.py

Lines changed: 18 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -9,12 +9,13 @@
99
- Update the display with current prices
1010
"""
1111

12-
from datetime import timedelta
1312
import ujson
1413
import network
1514
import ntptime
1615
import machine
1716
import urequests
17+
from datetime import timedelta
18+
from app.ili9341 import GUI
1819

1920

2021
def wifi():
@@ -28,8 +29,14 @@ def wifi():
2829
wlan.config(pm=0)
2930
wlan.config(txpower=20)
3031
if not wlan.isconnected():
31-
with open("config.json", "r") as f:
32-
config = ujson.load(f)
32+
try:
33+
with open("config.json", "r") as f:
34+
config = ujson.load(f)
35+
except ValueError as e:
36+
print(f"Error reading config file: {e}")
37+
GUI.set_error()
38+
raise
39+
3340
print(f"Connecting to {config['ssid']}...")
3441
wlan.connect(config["ssid"], config["password"])
3542
while not wlan.isconnected():
@@ -67,6 +74,7 @@ def ntp_sync():
6774
print(f"Failed to sync time: {e}")
6875
machine.soft_reset()
6976

77+
7078
def fetch_prices_from_file(api, time):
7179
# type: (ElectricityPriceAPI, SweTime) -> tuple
7280
"""
@@ -115,6 +123,7 @@ def update_display(
115123

116124
hour = swe_localtime.hour
117125
minute = swe_localtime.minute
126+
second = swe_localtime.second
118127

119128
if hour != current_hour:
120129
if hour == 0:
@@ -125,11 +134,13 @@ def update_display(
125134
gui.set_price(hour, prices_today)
126135
gui.set_arrow(hour)
127136

137+
# Checking if new prices are available.
128138
if hour >= 13 and prices_tomorrow is None:
129-
print(f"Checking if new prices are available @ {hour}:{minute}...")
130-
response = urequests.get(api.get_url()[1])
131-
if response.status_code != 404:
132-
print(f"New prices available, rebooting @ {hour}:{minute}...")
139+
response = urequests.get(api.get_url_tomorrow())
140+
if response.status_code == 200:
141+
print(
142+
f"New prices available, fetching from: {api.get_url_tomorrow()} and rebooting @ {hour}:{minute}:{second}..."
143+
)
133144
machine.soft_reset()
134145
response.close()
135146

0 commit comments

Comments
 (0)