-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsetup_weather.py
More file actions
144 lines (112 loc) · 4.35 KB
/
Copy pathsetup_weather.py
File metadata and controls
144 lines (112 loc) · 4.35 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
#!/usr/bin/env python3
"""
Dadboard - Weather Location Setup
Configure your location for weather data using BOM (Bureau of Meteorology) API
"""
import urllib.request
import urllib.parse
import json
from config_helper import set_setting, get_setting
def search_location(query):
"""Search for a location by name using BOM API"""
encoded_query = urllib.parse.quote(query)
url = f"https://api.weather.bom.gov.au/v1/locations?search={encoded_query}"
req = urllib.request.Request(url, headers={'User-Agent': 'Mozilla/5.0'})
with urllib.request.urlopen(req, timeout=10) as response:
data = json.loads(response.read().decode())
return data.get('data', [])
def test_weather(geohash):
"""Test fetching weather for the given geohash"""
url = f"https://api.weather.bom.gov.au/v1/locations/{geohash}/forecasts/daily"
req = urllib.request.Request(url, headers={'User-Agent': 'Mozilla/5.0'})
with urllib.request.urlopen(req, timeout=10) as response:
data = json.loads(response.read().decode())
days = data.get('data', [])
if not days:
return None, None, None
today = days[0]
temp_max = today.get('temp_max')
temp_min = today.get('temp_min')
short_text = today.get('short_text', '')
if short_text.endswith('.'):
short_text = short_text[:-1]
return temp_max, temp_min, short_text
def main():
print("")
print("Weather Location Setup")
print("=" * 40)
print("")
print("This uses the BOM (Bureau of Meteorology) API")
print("")
# Check existing config
existing_geohash = get_setting("weather", "geohash", "")
existing_name = get_setting("weather", "location_name", "")
if existing_geohash:
print(f"Current location: {existing_name} (geohash: {existing_geohash})")
choice = input("Keep existing location? (y/n): ").strip().lower()
if choice == 'y':
print("Keeping existing weather location.")
return
# Search for location
while True:
query = input("Enter your suburb name (or 'skip' to skip): ").strip()
if query.lower() == 'skip':
print("Skipping weather setup.")
return
if not query:
continue
print(f"\nSearching for '{query}'...")
try:
results = search_location(query)
except Exception as e:
print(f"Error searching: {e}")
continue
if not results:
print("No locations found. Try a different search term.")
continue
print("\nSelect your location:")
for i, loc in enumerate(results, 1):
name = loc.get('name', 'Unknown')
state = loc.get('state', '')
display = name
if state:
display += f", {state}"
print(f" {i}. {display}")
print(f" 0. Search again")
try:
choice = int(input("\nEnter number: ").strip())
except ValueError:
print("Invalid choice.")
continue
if choice == 0:
continue
if 1 <= choice <= len(results):
selected = results[choice - 1]
geohash = selected.get('geohash', '')
name = selected.get('name', 'Unknown')
state = selected.get('state', '')
location_name = name
if state:
location_name += f", {state}"
print(f"\nSelected: {location_name}")
print(f"Geohash: {geohash}")
# Test the weather API
print("\nTesting weather API...")
try:
temp_max, temp_min, short_text = test_weather(geohash)
if temp_max is not None:
print(f"Today's forecast: High {temp_max}°C, {short_text}, Low {temp_min}°C")
else:
print("Forecast data not available yet")
except Exception as e:
print(f"Warning: Could not fetch weather: {e}")
confirm = input("Save location anyway? (y/n): ").strip().lower()
if confirm != 'y':
continue
# Save to config
set_setting("weather", "geohash", geohash)
set_setting("weather", "location_name", location_name)
print(f"\nWeather location saved: {location_name}")
break
if __name__ == "__main__":
main()