-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy paththingspeak_api.py
More file actions
65 lines (49 loc) · 1.7 KB
/
Copy paththingspeak_api.py
File metadata and controls
65 lines (49 loc) · 1.7 KB
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
#!/usr/bin/env python3
import requests, time, os
from dotenv import load_dotenv
from read_env import read_environment
from openweather import get_from_ow
load_dotenv()
THINGSPEAK_WRITE_API_KEY = os.getenv('RPI_API_KEY')
OWTS_API_KEY= os.getenv('OWTS_API_KEY')
THINGSPEAK_CHANNEL_URL = "https://api.thingspeak.com/update"
THINGSPEAK_PUBLISH_PERIOD = 3600
def send_to_thingspeak(temperature, humidity):
payload = {
'api_key': THINGSPEAK_WRITE_API_KEY,
'field1': temperature,
'field2': humidity
}
response = requests.get(THINGSPEAK_CHANNEL_URL, params=payload)
if response.status_code == 200:
print("RPI Data sent to ThingSpeak.")
else:
print(f"Failed to send data. Status code: {response.status_code}")
def ow_to_thingspeak(owTemp, owHumidity):
payload = {
'api_key': OWTS_API_KEY,
'field1': owTemp,
'field2': owHumidity
}
response = requests.get(THINGSPEAK_CHANNEL_URL, params=payload)
if response.status_code == 200:
print("OW Data sent to ThingSpeak.")
else:
print(f"Failed to send data. Status code: {response.status_code}")
def main():
next_pub = time.monotonic()
while True:
now = time.monotonic()
if now >= next_pub:
env = read_environment()
ow = get_from_ow()
temperature = env["temperature"]
humidity = env["humidity"]
owTemp = ow["owTemp"]
owHumidity = ow["owHumidity"]
send_to_thingspeak(temperature, humidity)
ow_to_thingspeak(owTemp, owHumidity)
next_pub = now + THINGSPEAK_PUBLISH_PERIOD
time.sleep(0.1)
if __name__ == "__main__":
main()