Skip to content

Commit 687fe8e

Browse files
committed
Add HTTP API example scripts
1 parent fc89aab commit 687fe8e

File tree

3 files changed

+289
-0
lines changed

3 files changed

+289
-0
lines changed

examples/rtl_433_http_events.py

+95
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,95 @@
1+
#!/usr/bin/env python3
2+
3+
"""Custom data handling example for rtl_433's HTTP (chunked) streaming API of JSON events."""
4+
5+
# Start rtl_433 (`rtl_433 -F http`), then this script.
6+
# Needs the Requests package to be installed.
7+
8+
import requests
9+
import json
10+
from time import sleep
11+
12+
# You can run rtl_433 and this script on different machines,
13+
# start rtl_433 with `-F http:0.0.0.0`, and change
14+
# to e.g. `HTTP_HOST = "192.168.1.100"` (use your server ip) below.
15+
HTTP_HOST = "127.0.0.1"
16+
HTTP_PORT = 8433
17+
18+
19+
def stream_events():
20+
url = f'http://{HTTP_HOST}:{HTTP_PORT}/events'
21+
headers = {'Accept': 'application/json'}
22+
23+
# You will receive JSON events, one per line terminated with CRLF.
24+
# On Events and Stream endpoints a keep-alive of CRLF will be send every 60 seconds.
25+
response = requests.get(url, headers=headers, timeout=70, stream=True)
26+
print(f'Connected to {url}')
27+
28+
for chunk in response.iter_content(chunk_size=None):
29+
yield chunk
30+
31+
32+
def handle_event(line):
33+
try:
34+
# Decode the message as JSON
35+
data = json.loads(line)
36+
37+
#
38+
# Change for your custom handling below, this is a simple example
39+
#
40+
label = data["model"]
41+
if "channel" in data:
42+
label += ".CH" + str(data["channel"])
43+
elif "id" in data:
44+
label += ".ID" + str(data["id"])
45+
46+
# E.g. match `model` and `id` to a descriptive name.
47+
if data["model"] == "LaCrosse-TX" and data["id"] == 123:
48+
label = "Living Room"
49+
50+
if "battery_ok" in data:
51+
if data["battery_ok"] == 0:
52+
print(label + ' Battery empty!')
53+
54+
if "temperature_C" in data:
55+
print(label + ' Temperature ', data["temperature_C"])
56+
57+
if "humidity" in data:
58+
print(label + ' Humidity ', data["humidity"])
59+
60+
except KeyError:
61+
# Ignore unknown message data and continue
62+
pass
63+
64+
except ValueError as e:
65+
# Warn on decoding errors
66+
print(f'Event format not recognized: {e}')
67+
68+
69+
def rtl_433_listen():
70+
"""Listen to all messages in a loop forever."""
71+
72+
# Loop forever
73+
while True:
74+
try:
75+
# Open the HTTP (chunked) streaming API of JSON events
76+
for chunk in stream_events():
77+
# print(chunk)
78+
chunk = chunk.rstrip()
79+
if not chunk:
80+
# filter out keep-alive empty lines
81+
continue
82+
# Decode the JSON message
83+
handle_event(chunk)
84+
85+
except requests.ConnectionError:
86+
print('Connection failed, retrying...')
87+
sleep(5)
88+
89+
90+
if __name__ == "__main__":
91+
try:
92+
rtl_433_listen()
93+
except KeyboardInterrupt:
94+
print('\nExiting.')
95+
pass

examples/rtl_433_http_stream.py

+95
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,95 @@
1+
#!/usr/bin/env python3
2+
3+
"""Custom data handling example for rtl_433's HTTP (line) streaming API of JSON events."""
4+
5+
# Start rtl_433 (`rtl_433 -F http`), then this script.
6+
# Needs the Requests package to be installed.
7+
8+
import requests
9+
import json
10+
from time import sleep
11+
12+
# You can run rtl_433 and this script on different machines,
13+
# start rtl_433 with `-F http:0.0.0.0`, and change
14+
# to e.g. `HTTP_HOST = "192.168.1.100"` (use your server ip) below.
15+
HTTP_HOST = "127.0.0.1"
16+
HTTP_PORT = 8433
17+
18+
19+
def stream_lines():
20+
url = f'http://{HTTP_HOST}:{HTTP_PORT}/stream'
21+
headers = {'Accept': 'application/json'}
22+
23+
# You will receive JSON events, one per line terminated with CRLF.
24+
# On Events and Stream endpoints a keep-alive of CRLF will be send every 60 seconds.
25+
response = requests.get(url, headers=headers, timeout=70, stream=True)
26+
print(f'Connected to {url}')
27+
28+
for chunk in response.iter_lines():
29+
yield chunk
30+
31+
32+
def handle_event(line):
33+
try:
34+
# Decode the message as JSON
35+
data = json.loads(line)
36+
37+
#
38+
# Change for your custom handling below, this is a simple example
39+
#
40+
label = data["model"]
41+
if "channel" in data:
42+
label += ".CH" + str(data["channel"])
43+
elif "id" in data:
44+
label += ".ID" + str(data["id"])
45+
46+
# E.g. match `model` and `id` to a descriptive name.
47+
if data["model"] == "LaCrosse-TX" and data["id"] == 123:
48+
label = "Living Room"
49+
50+
if "battery_ok" in data:
51+
if data["battery_ok"] == 0:
52+
print(label + ' Battery empty!')
53+
54+
if "temperature_C" in data:
55+
print(label + ' Temperature ', data["temperature_C"])
56+
57+
if "humidity" in data:
58+
print(label + ' Humidity ', data["humidity"])
59+
60+
except KeyError:
61+
# Ignore unknown message data and continue
62+
pass
63+
64+
except ValueError as e:
65+
# Warn on decoding errors
66+
print(f'Event format not recognized: {e}')
67+
68+
69+
def rtl_433_listen():
70+
"""Listen to all messages in a loop forever."""
71+
72+
# Loop forever
73+
while True:
74+
try:
75+
# Open the HTTP (line) streaming API of JSON events
76+
for chunk in stream_lines():
77+
# print(chunk)
78+
chunk = chunk.rstrip()
79+
if not chunk:
80+
# filter out keep-alive empty lines
81+
continue
82+
# Decode the JSON message
83+
handle_event(chunk)
84+
85+
except requests.ConnectionError:
86+
print('Connection failed, retrying...')
87+
sleep(5)
88+
89+
90+
if __name__ == "__main__":
91+
try:
92+
rtl_433_listen()
93+
except KeyboardInterrupt:
94+
print('\nExiting.')
95+
pass

examples/rtl_433_http_ws.py

+99
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,99 @@
1+
#!/usr/bin/env python3
2+
3+
"""Custom data handling example for rtl_433's HTTP WebSocket API of JSON events."""
4+
5+
# Start rtl_433 (`rtl_433 -F http`), then this script.
6+
# Needs the websocket-client package to be installed.
7+
8+
import websocket
9+
import json
10+
from time import sleep
11+
12+
# You can run rtl_433 and this script on different machines,
13+
# start rtl_433 with `-F http:0.0.0.0`, and change
14+
# to e.g. `HTTP_HOST = "192.168.1.100"` (use your server ip) below.
15+
HTTP_HOST = "127.0.0.1"
16+
HTTP_PORT = 8433
17+
18+
19+
def ws_events():
20+
url = f'ws://{HTTP_HOST}:{HTTP_PORT}/ws'
21+
ws = websocket.WebSocket()
22+
ws.connect(url)
23+
24+
# You will receive JSON events, one per message.
25+
print(f'Connected to {url}')
26+
27+
while True:
28+
yield ws.recv()
29+
30+
31+
def handle_event(line):
32+
try:
33+
# Decode the message as JSON
34+
data = json.loads(line)
35+
36+
#
37+
# Change for your custom handling below, this is a simple example
38+
#
39+
label = data["model"]
40+
if "channel" in data:
41+
label += ".CH" + str(data["channel"])
42+
elif "id" in data:
43+
label += ".ID" + str(data["id"])
44+
45+
# E.g. match `model` and `id` to a descriptive name.
46+
if data["model"] == "LaCrosse-TX" and data["id"] == 123:
47+
label = "Living Room"
48+
49+
if "battery_ok" in data:
50+
if data["battery_ok"] == 0:
51+
print(label + ' Battery empty!')
52+
53+
if "temperature_C" in data:
54+
print(label + ' Temperature ', data["temperature_C"])
55+
56+
if "humidity" in data:
57+
print(label + ' Humidity ', data["humidity"])
58+
59+
except KeyError:
60+
# Ignore unknown message data and continue
61+
pass
62+
63+
except ValueError as e:
64+
# Warn on decoding errors
65+
print(f'Event format not recognized: {e}')
66+
67+
68+
def rtl_433_listen():
69+
"""Listen to all messages in a loop forever."""
70+
71+
# Loop forever
72+
while True:
73+
try:
74+
# Open the HTTP WebSocket API of JSON events
75+
for chunk in ws_events():
76+
# print(chunk)
77+
chunk = chunk.rstrip()
78+
if not chunk:
79+
# filter out keep-alive empty lines
80+
continue
81+
# Decode the JSON message
82+
handle_event(chunk)
83+
84+
except ConnectionRefusedError:
85+
print('Connection refused, retrying...')
86+
sleep(5)
87+
pass
88+
89+
except websocket._exceptions.WebSocketConnectionClosedException:
90+
print('Connection failed, retrying...')
91+
sleep(5)
92+
93+
94+
if __name__ == "__main__":
95+
try:
96+
rtl_433_listen()
97+
except KeyboardInterrupt:
98+
print('\nExiting.')
99+
pass

0 commit comments

Comments
 (0)