-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTSfetch.py
49 lines (38 loc) · 1.23 KB
/
TSfetch.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
# coding: utf-8
#
# Weather station display for Raspberry and Waveshare 2.7" e-Paper display
# (fetch ThingSpeak data)
#
# Copyright by Antal Rutz
#
# Documentation and full source code:
# https://github.com/arutz12/Raspberry-Weather-EPD
#
import os
import requests
import json
from dotenv import load_dotenv
base_dir = os.path.dirname(os.path.abspath(__file__))
dotenv_path = os.path.join(base_dir, '.env')
load_dotenv(dotenv_path)
TS_READ_API_KEY = os.environ.get('TS_READ_API_KEY')
TS_CHANNEL_ID = os.environ.get('TS_CHANNEL_ID')
TS_READ_URL = 'https://api.thingspeak.com/channels/{}/feeds.json?api_key={}&results=1'.format(TS_CHANNEL_ID, TS_READ_API_KEY)
def fetchThingSpeak():
TS_DATA = {}
try:
r = requests.get(TS_READ_URL)
except Exception as e:
print(e)
return {'TEMP': 0, 'VOLT': 0, 'UPDATED': 0}
ts_result = json.loads(r.content)
if not ts_result:
return {'TEMP': 0, 'VOLT': 0, 'UPDATED': 0}
TS_DATA['TEMP'] = ts_result['feeds'][0]['field1']
TS_DATA['VOLT'] = ts_result['feeds'][0]['field2']
TS_DATA['UPDATED'] = ts_result['feeds'][0]['created_at']
return TS_DATA
if __name__ == '__main__':
from pprint import pprint
ts_data = fetchThingSpeak()
pprint(ts_data)