-
Notifications
You must be signed in to change notification settings - Fork 0
/
airq.py
144 lines (107 loc) · 3.89 KB
/
airq.py
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
#-*- coding:utf-8 -*-
"""
Copyright (C) 2013 - Frank Wickström <frwickst@gmail.com>
Distributed under the BSD license, see LICENSE.txt
airq.py is a web scraper for http://www.ilmanlaatu.fi/
Requirements:
* Mechanize
* PyQuery
Usage:
a = AirQ(rs="430", ss="186") # Turku = 430, Turun kauppatori = 186
sensors = a.getSensors() # Get sensors
values = a.getSensorValues() # Get sensor values
print values # Prints the values
for sensor in sensors: # For all sensors
print sensor, ' : ' ,values[sensor]['current'] # Print the sensor and its current value
"""
import mechanize
from pyquery import PyQuery as PQ
import logging
import time
import datetime
DEBUG = True
if DEBUG:
logging.basicConfig(level=logging.INFO)
else:
logging.basicConfig(level=None)
logger = logging.getLogger("AirQ")
def datetimeInGMT2():
t = time.time()
if time.localtime(t).tm_isdst and time.daylight:
offset = time.altzone
else:
offset = time.timezone
return datetime.datetime.fromtimestamp(t+(7200+offset))
class AirQ():
def __init__(self, **kwargs):
logger.info("Initializing AirQ")
self.br = mechanize.Browser() # Browser
self.br.set_handle_robots(False)
# Get these values from the URL of the station you want to monitor
self.networkID = kwargs.get('as', 'Suomi')
self.cityID = kwargs.get('rs', False)
self.stationID = kwargs.get('ss', False)
self.sensors = False
self.sensorValues = False
logger.info("AirQ initializes")
def getSensors(self):
logger.info("Getting sensors")
if self.cityID and self.stationID:
url = "http://www.ilmanlaatu.fi//ilmanyt/nyt/ilmanyt.php?as="+self.networkID+"&rs="+self.cityID+"&ss="+self.stationID
self.br.open(url)
response = self.br.response()
q = PQ(response.read())
self.sensors = [PQ(option).val() for option in q('#parametrilista option')]
return self.sensors
else:
logger.error("No city or station set")
return False
def getSensorValues(self, sensors = False):
logger.info("Getting sensors values")
if self.sensors and not sensors:
sensors = self.sensors
if sensors:
now = datetimeInGMT2()
hour = str(now.hour-1)
pv = now.strftime("%Y%m%d"+hour+"00")
results = {}
for sensor in sensors:
logger.info("Getting info from sensor: "+sensor)
results[sensor] = {}
url = "http://www.ilmanlaatu.fi/toiminnallisuus/kartta_alku.php?network="+self.networkID+"&pickedStation="+self.stationID+"&imageMapId="+self.cityID+"¶m="+sensor+"&time="+pv
self.br.open(url)
response = self.br.response()
if sensor == "stationindex":
q = PQ(response.read())
results[sensor]['current'] = q('area').attr('onmouseover')
if results[sensor]['current']:
results[sensor]['current'] = results[sensor]['current'].split(',')[-1].strip("');")
else:
results[sensor]['current'] = None
else:
results[sensor]['hours'] = {}
url = "http://www.ilmanlaatu.fi/php/table/observationsInTable.php?step=3600&today=1×equence=23&time="+now.strftime("%Y%m%d%H")+"&station="+self.stationID
self.br.open(url)
response = self.br.response()
q = PQ(response.read())
hours = q('table:first tr')[1:] # First entry is the header
if hours:
for tr in hours:
results[sensor]['hours'][PQ(tr[0]).text()] = PQ(tr[1]).text()
if not PQ(hours[-1][1]).text():
logger.info("No value for the current hour yet, getting last value")
for i in range (1,now.hour):
if PQ(hours[-1-i][1]).text():
current = PQ(hours[-1-i][1]).text()
break
else:
current = PQ(hours[-1][1]).text()
results[sensor]['current'] = current
else:
results[sensor]['current'] = None
logger.info("Can't get values! Day has probably change, and the list is empty.")
self.sensorValues = results
return results
else:
logger.error("No sensors at the current location")
return False