RaspyRFM/apps/rcpulsegw.py

79 lines
2 KiB
Python
Raw Normal View History

#!/usr/bin/env python
2020-11-19 21:26:59 +01:00
import socket
import threading
from raspyrfm import *
import rcprotocols
import json
2020-11-21 01:03:14 +01:00
from argparse import ArgumentParser
parser = ArgumentParser()
parser.add_argument("-m", "--module", type=int, metavar="1-4", help=u"RaspyRFM module 1-4", default=1)
2020-11-30 19:25:11 +01:00
parser.add_argument("-f", "--frequency", type=float, help=u"frequency in MHz", default=433.92)
2020-12-02 20:28:57 +01:00
args = parser.parse_args()
2020-11-19 21:26:59 +01:00
srvsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
2020-11-21 01:03:14 +01:00
srvsock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
2020-11-19 21:26:59 +01:00
srvsock.bind(('', 1989))
srvsock.listen(5)
clients = []
2020-11-30 19:25:11 +01:00
def rxcb(dec, train):
payload = None
if dec is None:
payload = {"raw": train}
else:
if len(dec) > 0:
payload = {"decode": dec, "raw": train}
if payload is not None:
print("RX", payload)
s = json.dumps(payload) + "\n"
for client in clients:
client.send(s)
2020-11-30 19:25:11 +01:00
if not raspyrfm_test(args.module, RFM69):
print("Error! RaspyRFM not found")
exit()
rctrx = rcprotocols.RcTransceiver(args.module, args.frequency, rxcb)
lock = threading.Lock()
2020-11-19 21:26:59 +01:00
class clientthread(threading.Thread):
def __init__(self, socket):
self.__socket = socket
threading.Thread.__init__(self)
def send(self, s):
self.__socket.sendall(s.encode())
2020-11-19 21:26:59 +01:00
def run(self):
buf = ""
2020-11-19 21:26:59 +01:00
while True:
chunk = self.__socket.recv(32).decode()
2020-11-19 21:26:59 +01:00
if len(chunk) == 0:
del self.__socket
break
lock.acquire()
2020-11-19 21:26:59 +01:00
try:
buf += chunk
while "\n" in buf:
line = buf[:buf.find("\n")]
buf = buf[buf.find("\n") + 1:]
d = json.loads(line)
print("TX", d)
rctrx.send(d["protocol"], d["params"])
2020-11-19 21:26:59 +01:00
except:
pass
lock.release()
clients.remove(self)
2020-11-19 21:26:59 +01:00
while True:
(client, address) = srvsock.accept()
ct = clientthread(client)
ct.daemon = True
ct.start()
clients.append(ct)