import os import time import requests def get_data(ts_start: int, ts_end: int, device_id: str, module_id: str, metrics: list[str]) -> dict[str, dict[int, float]]: """ Returns {'Temperature': {timestamp: value}, 'Humidity': {timestamp: value}} """ headers = { 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64; rv:127.0) Gecko/20100101 Firefox/127.0', 'Accept': 'application/json, text/plain, */*', 'Accept-Language': 'en-US,en;q=0.5', # 'Accept-Encoding': 'gzip, deflate, br, zstd', 'Authorization': 'Bearer 52d42bfc1777599b298b456c|24df9731beeed2ddfc71aaea971a367e', 'Content-Type': 'application/json;charset=utf-8', 'Origin': 'https://weathermap.netatmo.com', 'DNT': '1', 'Sec-GPC': '1', 'Connection': 'keep-alive', 'Referer': 'https://weathermap.netatmo.com/', 'Sec-Fetch-Dest': 'empty', 'Sec-Fetch-Mode': 'cors', 'Sec-Fetch-Site': 'cross-site', } json_data = { 'date_begin': str(ts_start), 'date_end': str(ts_end), 'scale': 'max', 'device_id': device_id, 'module_id': module_id, 'type': ','.join(metrics), } response = requests.post('https://app.netatmo.net/api/getmeasure', headers=headers, json=json_data) response.raise_for_status() res = {} data = response.json()['body'] for el in data: #print("\n\n") ts = el['beg_time'] for vals in el['value']: for ielem in range(len(vals)): val = vals[ielem] metric = metrics[ielem] res_vals = res.get(metric, {}) res_vals[ts] = val res[metric] = res_vals #print(f'{ts}: {metric} = {val}') if 'step_time' in el: ts += el['step_time'] else: break return res def send_tsdb(sensor:str, data: dict[str, dict[int, float]]) -> None: tsdb_token = os.environ['TSDB_TOKEN'] for metric, vals in data.items(): for (ts, value) in vals.items(): d = { "metric": f"weather.{metric}", "value": value, "timestamp": ts, "tags": {"sensor": sensor, "source": "netatmo"} } url = f'https://opentsdb.k3s.fr/put' params = { 'token': tsdb_token } #print(f'SAVE {sensor}/{metric} @{ts} ={value}') r = requests.post(url, json=d, params=params) r.raise_for_status() if __name__ == '__main__': sensors = [ ('stcergues_charriere', ('70:ee:50:9c:f8:ea', '02:00:00:a2:55:6a'), ['Temperature', 'Humidity']), #Temp_humid ('stcergues_charriere', ('70:ee:50:9c:f8:ea', '05:00:00:0a:2a:7c'), ['Rain']), #Rain ('stcergues_fontaines', ('70:ee:50:13:6b:76', '02:00:00:13:72:e8'), ['Temperature', 'Humidity']), #Temp_humid ('juvigny_plantaz', ('70:ee:50:82:7f:b8', '02:00:00:5f:40:58'), ['Temperature', 'Humidity']), #Temp_humid ] ts_end = int(time.time()) ts_start = ts_end - 3600*32 for (sensor, (device_id, module_id), metrics) in sensors: print(f'Will import {sensor} with {device_id}/{module_id} and {metrics}') data = get_data(ts_start, ts_end, device_id, module_id, metrics) send_tsdb(sensor, data) time.sleep(100)