| 1 |
from dataclasses import dataclass |
| 2 |
from threading import Thread |
| 3 |
from time import sleep |
| 4 |
|
| 5 |
from pytermgui import Container, StyleManager, real_length, tim |
| 6 |
|
| 7 |
|
| 8 |
@dataclass |
| 9 |
class WeatherData: |
| 10 |
state: str |
| 11 |
wind: str |
| 12 |
clouds: str |
| 13 |
|
| 14 |
|
| 15 |
class Weather(Container): |
| 16 |
|
| 17 |
styles = StyleManager.merge( |
| 18 |
Container.styles, |
| 19 |
sunny="yellow", |
| 20 |
cloudy="grey", |
| 21 |
rainy="darkblue", |
| 22 |
snowy="snow", |
| 23 |
detail="245", |
| 24 |
) |
| 25 |
|
| 26 |
|
| 27 |
chars = { |
| 28 |
**Container.chars, |
| 29 |
**{ |
| 30 |
"sunny": "☀", |
| 31 |
"cloudy": "☁", |
| 32 |
"rainy": "☂", |
| 33 |
"snowy": "☃", |
| 34 |
}, |
| 35 |
} |
| 36 |
|
| 37 |
def __init__(self, location: str, timeout: int, **attrs) -> None: |
| 38 |
super().__init__(**attrs) |
| 39 |
|
| 40 |
self.location = location |
| 41 |
self.timeout = timeout |
| 42 |
|
| 43 |
& |
| 44 |
Thread(target=self._monitor_loop, daemon=True).start() |
| 45 |
|
| 46 |
& |
| 47 |
& self.data = WeatherData("sunny", "15kph N/W", "scattered") |
| 48 |
& self.update_content() |
| 49 |
|
| 50 |
def _request_data(self) -> WeatherData: |
| 51 |
& return WeatherData("sunny", "15kph N/W", "scattered") |
| 52 |
... |
| 53 |
|
| 54 |
def _monitor_loop(self) -> None: |
| 55 |
while True: |
| 56 |
self.data = self._request_data() |
| 57 |
self.update_content() |
| 58 |
sleep(self.timeout) |
| 59 |
|
| 60 |
def update_content(self) -> None: |
| 61 |
state = self.data.state |
| 62 |
|
| 63 |
style = self.styles[state] |
| 64 |
char = self._get_char(state) |
| 65 |
icon = style(char) |
| 66 |
|
| 67 |
self.set_widgets( |
| 68 |
[ |
| 69 |
f"{icon} It is currently {state} in {self.location}. {icon}", |
| 70 |
"", |
| 71 |
f"{self.styles.detail('Wind')}: {self.data.wind}", |
| 72 |
f"{self.styles.detail('Clouds')}: {self.data.clouds}", |
| 73 |
] |
| 74 |
) |
| 75 |
|
| 76 |
|
| 77 |
&widget = Weather("Los Angeles", 1, static_width=60) |
| 78 |
&for line in widget.get_lines(): |
| 79 |
& print(line) |
| 80 |
&termage.fit(widget) |