-
Notifications
You must be signed in to change notification settings - Fork 9
/
get.py
executable file
·179 lines (147 loc) · 5.7 KB
/
get.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
#!/usr/bin/env python3
import requests
from influxdb import InfluxDBClient
from datetime import datetime, timezone
CLIENT_ID = ''
CLIENT_SECRET = ''
NETATMO_USERNAME = ''
NETATMO_PASSWORD = ''
_ALLOWED_TYPES = ('Temperature', 'CO2', 'Humidity', 'Pressure', 'Noise', 'Rain', 'WindStrength', 'WindAngle', 'GustStrenght', 'GustAngle')
def getAccessToken():
'''
returns:
{ access_token, expires_in, refresh_token }
'''
payload = {
'client_id': CLIENT_ID,
'client_secret': CLIENT_SECRET,
'grant_type': 'password',
'username': NETATMO_USERNAME,
'password': NETATMO_PASSWORD,
'scope': 'read_station'
}
r = requests.post('https://api.netatmo.com/oauth2/token', data=payload)
return r.json()
def refreshToken(refreshToken):
'''
returns:
{ access_token, expires_in, refresh_token }
'''
payload = {
'client_id': CLIENT_ID,
'client_secret': CLIENT_SECRET,
'grant_type': 'refresh_token',
'refresh_token': refresh_token
}
r = requests.post('https://api.netatmo.com/oauth2/token', data=payload)
return r.json()
def getStationInfo(access_token):
payload = {
'access_token': access_token,
}
r = requests.get('https://api.netatmo.com/api/getstationsdata', params=payload)
return r.json()
def getMeasure(access_token, device_id, module_id, measurement_type, date_begin):
if measurement_type not in _ALLOWED_TYPES:
print('not allowed type "%s"'%measurement_type)
return
payload = {
'access_token': access_token,
'device_id': device_id,
'module_id': module_id,
'scale': 'max',
'optimize': 'false',
'type': measurement_type,
'date_begin': date_begin
}
r = requests.get('https://api.netatmo.com/api/getmeasure', params=payload)
return r.json()
def printStation(station):
if 'station_name' in station:
name = station['station_name'] + ' - ' + station['module_name']
indent = ''
last_seen = station['last_status_store']
else:
if 'module_name' in station:
name = station['module_name']
else:
name = station['_id']
indent = '\t'
last_seen = station['last_seen']
last_seen = datetime.fromtimestamp(last_seen)
print('%sName: %s ID: %s Last seen: %s\n%sData types: %s '%(
indent, name, station['_id'], last_seen.isoformat(), indent, station['data_type']
))
def getInfluxDBClient():
client = InfluxDBClient()
if {'name': 'netatmo'} not in client.get_list_database():
client.create_database('netatmo')
return client
def iterateStations(access_token):
client = getInfluxDBClient()
station_info = getStationInfo(access_token)
if 'body' not in station_info:
raise Exception(station_info)
stations = station_info['body']['devices']
for station in stations:
printStation(station)
for measurement_type in station['data_type']:
fetchMeasurements(access_token, station['_id'], "", measurement_type, station['station_name'], station['module_name'], client, station['last_status_store'])
print('Modules:')
for substation in station['modules']:
printStation(substation)
for measurement_type in substation['data_type']:
if 'module_name' in substation:
name = substation['module_name']
else:
name = substation['_id']
fetchMeasurements(access_token, station['_id'], substation['_id'], measurement_type, station['station_name'], name, client, substation['last_seen'])
def fetchMeasurements(access_token, device_id, module_id, measurement_type, station_name, module_name, client, last_update):
get_latest_timestamp_query = "SELECT value FROM %s WHERE station='%s' AND module='%s' ORDER BY time DESC LIMIT 1"%(measurement_type, station_name, module_name)
result = client.query(get_latest_timestamp_query, database='netatmo')
time = 0
points = result.get_points()
for point in points:
time = int(datetime.strptime(point['time'], '%Y-%m-%dT%H:%M:%SZ').replace(tzinfo=timezone.utc).timestamp())
break
if last_update <= time:
print('No value to update')
return
time += 1
measurements = getMeasure(access_token, device_id, module_id, measurement_type, time)
if 'body' not in measurements:
raise Exception(measurements)
measurements = measurements['body']
min_time = 0
max_time = 0
data = []
for time in measurements:
timestamp = int(time)
data.append({
"measurement": measurement_type,
"tags": {
"station": station_name,
"module": module_name
},
"time": timestamp,
"fields": {
"value": float(measurements[time][0])
}
})
if min_time == 0 or min_time > timestamp:
min_time = timestamp
if max_time == 0 or max_time < timestamp:
max_time = timestamp
if client.write_points(
data,
time_precision='s',
database='netatmo'
):
print('%i points written - %s, %s, %s - start %s - end %s'%(len(data), station_name, module_name, measurement_type, datetime.fromtimestamp(min_time).isoformat(), datetime.fromtimestamp(max_time).isoformat()))
if len(data) == 1024:
fetchMeasurements(access_token, device_id, module_id, measurement_type, station_name, module_name, client, last_update)
else:
print('write failed')
token_info = getAccessToken()
# token_info = refreshToken(token_info['refresh_token'])
iterateStations(token_info['access_token'])