1
0
mirror of https://github.com/MarkParker5/STARK.git synced 2025-07-02 22:36:54 +02:00
Files
STARK/Features/SmartHome/SmartHome.py

81 lines
2.1 KiB
Python
Raw Normal View History

2020-11-13 23:27:41 +02:00
import RPi.GPIO as GPIO
2021-04-17 16:37:11 +03:00
from .lib_nrf24 import NRF24
2020-11-13 23:27:41 +02:00
import spidev
2021-04-17 16:18:46 +03:00
import time
import json as JSON
from threading import Thread
from ..Command import Command
GPIO.setmode(GPIO.BCM)
2021-04-17 16:18:46 +03:00
pipe = [0xf0, 0xf0, 0xf0, 0xf0, 0xe1]
2020-11-13 23:27:41 +02:00
radio = NRF24(GPIO, spidev.SpiDev())
radio.begin(0, 17)
radio.setRetries(15,15)
radio.setPayloadSize(32)
radio.setChannel(0x60)
radio.setDataRate(NRF24.BR_250KBPS)
radio.setPALevel(NRF24.PA_HIGH)
radio.setAutoAck(True)
radio.enableDynamicPayloads()
radio.enableAckPayload()
2021-04-17 16:18:46 +03:00
radio.openWritingPipe(pipe)
radio.openReadingPipe(1, pipe)
radio.startListening()
radio.stopListening()
2020-11-13 23:27:41 +02:00
2021-04-17 16:18:46 +03:00
radio.startListening()
2020-11-13 23:27:41 +02:00
class SmartHome(Command):
radio = radio
2021-04-17 16:18:46 +03:00
send_queue = []
2020-11-13 23:27:41 +02:00
def start(this, string): # main method
pass
@staticmethod
def send(data):
2021-04-17 16:18:46 +03:00
SmartHome.send_queue.append(data)
@staticmethod
def _send(data):
2021-04-18 03:44:26 +03:00
radio.stopListening()
SmartHome.send_queue.remove(data)
print(data)
2021-04-17 16:18:46 +03:00
string = JSON.dumps(data)
for char in string: radio.write(char)
2021-04-18 03:44:26 +03:00
radio.startListening()
2021-04-17 16:18:46 +03:00
@staticmethod
def receiveAndTransmit():
json = ''
while True:
2021-04-18 03:44:26 +03:00
for command in SmartHome.send_queue: SmartHome._send(command)
2021-04-17 16:18:46 +03:00
# listening radio
2021-04-18 03:44:26 +03:00
if not radio.available(): continue
2021-04-17 16:18:46 +03:00
recv_buffer = []
radio.read(recv_buffer, radio.getDynamicPayloadSize())
if recv_buffer[0] != 10:
json += chr(recv_buffer[0])
continue
print(json)
# parsing of received data
2021-04-18 03:44:26 +03:00
try: data = JSON.loads(json)
except: data = {}
2021-04-17 23:11:40 +03:00
if data.get('target') != 'hub':
json = ''
continue
2021-04-18 03:44:26 +03:00
if name := data.get('cmd'):
2021-04-17 16:18:46 +03:00
params = data.get('params') or {}
if cmd := Command.getCommand(name):
try: cmd.start(params)
except: pass
json = ''
receiveAndTransmitThread = Thread(target=SmartHome.receiveAndTransmit)
receiveAndTransmitThread.start()