-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpyweather.py
More file actions
executable file
·115 lines (84 loc) · 4.11 KB
/
pyweather.py
File metadata and controls
executable file
·115 lines (84 loc) · 4.11 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
#!/usr/bin/python
import argparse, json, os, psycopg2, re, signal, sys, yaml
from lib.weather_underground import WeatherUnderground
from datetime import datetime
from time import sleep
class PyWeather:
def __init__(self, city, state, auth_key, db_info=None):
self.terminate = False
signal.signal(signal.SIGTERM, self.stop)
# create Weather Underground API object
self.weather = WeatherUnderground(city, state, auth_key)
# use database?
self.db_conn = None
if db_info is not None:
try:
self.db_conn = psycopg2.connect(database=db_info['dbname'], user=db_info['dbuser'], password=db_info['dbpass'], host=db_info['dbhost'])
except psycopg2.Error as e:
print("Unable to connect to database!\n{:s}".format(str(e)))
self.db_conn = None
def start(self):
while (not self.terminate):
#dt = datetime.now()
#print("PyWeather! {:s}".format(dt.strftime("%A, %d. %B %Y %I:%M:%S%p")))
# get Nest API data
weather_data = self.weather.get_data()
#print json.dumps(weather_data, indent=4, sort_keys=True)
# store in database
if (weather_data is not None) and (self.db_conn is not None):
try:
observation_data = weather_data["current_observation"]
re_humidity = re.match(r"([0-9]+)", observation_data["relative_humidity"])
if re_humidity is not None:
relative_humidity = re_humidity.group(1)
cursor = self.db_conn.cursor()
cursor.execute("INSERT INTO weather_observations (weather, temp_f, wind_mph, relative_humidity, pressure_mb, precip_1hr_in, feelslike_f, raw_data, created_at, updated_at) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, now(), now())", (
observation_data['weather'],
observation_data['temp_f'],
observation_data['wind_mph'],
relative_humidity,
observation_data['pressure_mb'],
observation_data['precip_1hr_in'],
observation_data['feelslike_f'],
json.dumps(weather_data),
)
)
self.db_conn.commit()
cursor.close()
except KeyError as ke:
print("PyWeather missing data dict key!")
print(str(re))
print("Contents of 'weather_data' ({:s}):".format(observation_data.__class__.__name__))
print(observation_data)
# wait till next polling period
sleep(600.0)
print("Terminating...")
def stop(self, signum, frame):
self.terminate = True
if __name__ == '__main__':
# parse command-line arguments
#===========================================================================
arg_parser = argparse.ArgumentParser()
arg_parser.add_argument("-d", "--no-db",
help="Disables the use of a database store",
action="store_true")
args = arg_parser.parse_args()
disable_database = args.no_db
# start the application
#===========================================================================
# environment setup
auth_key = os.environ['WEATHER_UNDERGROUND_KEY']
city = os.environ['WEATHER_LOCATION_CITY']
state = os.environ['WEATHER_LOCATION_STATE']
# data logger service
db_info = None
if not disable_database:
db_info = {
'dbname': os.environ['PYWEATHER_DB_NAME'],
'dbuser': os.environ['PYWEATHER_DB_USER'],
'dbpass': os.environ['PYWEATHER_DB_PASS'],
'dbhost': os.environ['PYWEATHER_DB_HOST'],
}
pyweather = PyWeather(city, state, auth_key, db_info)
pyweather.start()
sys.exit(0)