-
Notifications
You must be signed in to change notification settings - Fork 0
/
opa.py
200 lines (163 loc) · 5.55 KB
/
opa.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
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
import json
import sys
import urllib.error
import urllib.parse
import urllib.request
from urllib.error import HTTPError, URLError
from socket import timeout
import configparser
import time
class Configuration:
def __init__(self, filename="opa.ini"):
self.config = configparser.ConfigParser()
self.config.read(filename)
def local_IP(self):
return self.config.get("pa_local_api", "ip")
def has_local(self):
return self.config.has_section("pa_local_api") and self.config.has_option(
"pa_local_api", "ip"
)
def has_remote(self):
return self.config.has_section("pa_remote_api") and self.config.has_option(
"pa_remote_api", "api_key"
)
def remote_sensor_index(self):
return self.config.get("pa_remote_api", "sensor_index")
def remote_api_key(self):
return self.config.get("pa_remote_api", "api_key")
def json(self):
return {s: dict(self.config.items(s)) for s in self.config.sections()}
class Response:
text: str
status_code: int
def __init__(self, text, status_code):
self.status_code = status_code
self.text = text
def json(self):
try:
output = json.loads(self.text)
except json.JSONDecodeError:
output = None
return output
def fetch(
url: str,
data: dict = None,
params: dict = None,
headers: dict = None,
method: str = "GET",
):
if not url.casefold().startswith("http"):
raise urllib.error.URLError("Incorrect and possibly insecure protocol in url")
method = method.upper()
request_data = None
headers = headers or {}
data = data or {}
params = params or {}
headers = {"Accept": "application/json", **headers}
if method == "GET":
params = {**params, **data}
data = None
if params:
url += "?" + urllib.parse.urlencode(params, doseq=True, safe="/")
if data:
request_data = json.dumps(data).encode()
headers["Content-Type"] = "application/json; charset=UTF-8"
httprequest = urllib.request.Request(
url, data=request_data, headers=headers, method=method
)
print("fetch(%s): " % url, end="")
sys.stdout.flush()
try:
with urllib.request.urlopen(httprequest, timeout=10) as httpresponse:
print("response status %d" % httpresponse.status)
body = httpresponse.read().decode(
httpresponse.headers.get_content_charset("utf-8")
)
return Response(
status_code=httpresponse.status,
text=body,
)
except HTTPError as e:
print("http error: %s" % e)
except URLError as e:
if isinstance(e.reason, timeout):
print("timeout")
else:
print("error %s" % e.reason)
response = Response(
status_code=0,
text="error",
)
return response
class Exporter:
def __init__(self):
self.config = Configuration()
def run(self):
while True:
if self.config.has_remote():
data = self.fetch_remote_purple_air()
if data is not None:
self.export(data)
if self.config.has_local():
data = self.fetch_local_purple_air()
if data is not None:
self.export(data)
print("Sleeping for two minute")
time.sleep(60 * 2)
def fetch_remote_purple_air(self):
url = (
"https://api.purpleair.com/v1/sensors/" + self.config.remote_sensor_index()
)
r = fetch(url, headers={"X-API-Key": self.config.remote_api_key()})
if r.status_code != 200:
print(
"Sorry, failed to access the local PurpleAir API at %s: http error %d"
% (url, r.status_code)
)
print(r.text)
return None
if r.json() is None:
print(
"Sorry, failed to access the local PurpleAir at %s: Invalid JSON (%s...)"
% (url, r.text[:50])
)
return None
return r.json()
def fetch_local_purple_air(self):
url = "http://" + self.config.local_IP() + "/json"
r = fetch(url)
if r.status_code != 200:
print(
"Sorry, failed to access the local PurpleAir API at %s: http error %d"
% (url, r.status_code)
)
print(r.text)
return None
if r.json() is None:
print(
"Sorry, failed to access the local PurpleAir at %s: Invalid JSON (%s...)"
% (url, r.text[:50])
)
return None
return r.json()
def export(self, data):
url = "https://aqicn.org/sensor/upload"
r = fetch(url, data={"opa": data, "config": self.config.json()}, method="POST")
if r.status_code != 200:
print(
"Sorry, failed to upload to the WAQI server at %s: http error %d"
% (url, r.status_code)
)
print(r.text)
return None
response_json = r.json()
if response_json is None:
print("Invalid response (not JSON): %s" % r.text)
elif response_json["status"] != "ok":
print(
"Sorry, failed to upload to the WAQI server at %s: response %s"
% (url, json.dumps(response_json, indent=2))
)
else:
print("all fine\n%s" % (json.dumps(response_json, indent=2)))
Exporter().run()