rtl_433 on raspberry pi: Send data to api via http post

1.6k Views Asked by At

I'm receiving the weather data from my weather station with a dongle on my raspberry pi, that has internet connection via wifi. Now I want to send this data to a rails api/app to save it there in a database. The rails app runs on another server, so I want to post the data via http. How can I do this. I can't add the curl dependency to the rtl_433 project (https://github.com/merbanan/rtl_433) to send the data directly to my backend. Am I able to run the rtl_433 for example with a python script like:
rlt_433 -F json and take that output to send it to my backend or how can I realize that?

2

There are 2 best solutions below

0
On BEST ANSWER

I figured it now out, how to get the data from the subprocess and listen to it all the time:

  1. I installed python 3.8 to use the datetime library correctly. This approach is supported with version >= python 3.7

  2. I created a python script, taht is listening to the output of my rtl_433 command. As you can see I'm using: rtl_433 -f 868.300M -F json.

here is my listener.py:

import subprocess
import json
import datetime
from threading import Thread

def parse(printed_text):
    # here you can parse your string input from the subprocess

# sending to api
def sendToApi(text):
    parsed_json = parse(text)
    result = <send_to_api(parsed_json)> # here your http.post
    print(result)

# This method creates a subprocess with subprocess.Popen and takes a List<str> as command
def execute(cmd):
    popen = subprocess.Popen(cmd, stdout=subprocess.PIPE, bufsize=1, universal_newlines=True)
    for stdout_line in iter(popen.stdout.readline, ""):
        yield stdout_line 
    popen.stdout.close()
    return_code = popen.wait()
    if return_code:
        raise subprocess.CalledProcessError(return_code, cmd)

for json in execute(['/path/to/rtl_433/build/src/rtl_433', '-f','868.300M', '-F', 'json']):
    print(text, end="")
    # I'm starting a new thread to avoid data loss. So I can listen to the weather station's output and send it async to the api
    thread = Thread(target = sendToApi, args = (text,))
    thread.start()

after that I can use:

python3.8 listener.py and get all the data that is sent by the weather station

4
On

You should be able to execute rtl_433 as a subprocess using the subprocess module. Normally you would just use subprocess.run, but since rtl_433 produces output until it is killed, you will need to use subprocess.Popen and parse the output.

Another option is to pipe the output of rtl_433 to your program and using input() or sys.stdin.readline() to read lines. Like rtl_433 -flags | python3 script.py.