Exemplo n.º 1
0
def rf2_on(n_clicks):
        if (n_clicks):
                if(rpi_rf_433):
                        rfdevice = RFDevice(17)
                        GPIO.setmode(GPIO.BCM)
                        rfdevice.enable_tx()
                        rfdevice.tx_code(code=5264835, tx_proto=0, tx_pulselength=188, tx_length=24)
                        rfdevice.cleanup()
                else:
                        for ping in range(0,5):
                                #Fire 10 times for reliability
                                #subprocess.check_output("/var/www/rfoutlet/codesend 5264835 -l 184 -p 0", shell=True)
                                subprocess.check_output("/var/www/433Utils/RPi_utils/codesend 5264835 0 188", shell=True)
                                time.sleep(5)
        return
Exemplo n.º 2
0
 def __init__(self, rf_gpio, proto, code, pulselength):
     self.rf_gpio = rf_gpio
     self.dev = None
     if not rf_gpio:
         logPrint("RF control is disabled")
         return
     self.proto = proto
     self.code_ranges = code
     self.pulse_ranges = pulselength
     self.last_timestamp = None
     self.dev = RFDevice(self.rf_gpio)
     self.dev.enable_rx()
     if self.proto:
         logPrint(
             "RF control ready - Waiting for protcol %x Code (%r) Pulse length(%r)"
             % (self.proto, self.code_ranges, self.pulse_ranges))
Exemplo n.º 3
0
Arquivo: server.py Projeto: vpatov/pi
    def send_rf_signal(self, code, protocol=1, pulselength=186, gpio=17):
        date, timestamp = now()
        ip_addr = request.remote_addr
        probable_requestor = ip_map.get(ip_addr, 'Unknown')
        from_lan = ip_addr.startswith('192.168') or ip_addr == '127.0.0.1'
        details = (date, timestamp, self.remote_button, self.name, code,
                   from_lan)

        logstr = '{}    {} [{}: {:25}, code: {}, from_lan: {}, ip: {}, prequestor: {}'.format(
            *details, ip_addr, probable_requestor)
        logging.info(logstr)
        history_logs.append(details)
        rfdevice = RFDevice(gpio)
        rfdevice.enable_tx()
        rfdevice.tx_code(code, protocol, pulselength)
        rfdevice.cleanup()
Exemplo n.º 4
0
def main():

    try:
        rfdevice = RFDevice(RECEIVE_PIN)
        listener(rfdevice)
    except KeyboardInterrupt:
        logger.info("Received keyboard interrupt. Quitting.")
        systemd.notify("STOPPING=1")
        rfdevice.cleanup()
        sys.exit(0)
    except Exception:
        rfdevice.cleanup()
        logger.exception("Unhandled exception during execution.",
                         exc_info=True)
        systemd.notify("STATUS=An exception occured.\nERRNO=1")
        sys.exit(1)
Exemplo n.º 5
0
    def __init__(self,
                 pin: int,
                 code: int,
                 plength: int,
                 protocol: int,
                 length: int = 24,
                 repeat: int = 1):
        self.pin = pin
        self.code = code
        self.plength = plength
        self.protocol = protocol
        self.length = length,

        self.device = RFDevice(pin)
        self.device.enable_tx()
        self.device.tx_repeat = repeat
        print(f"Initialize transmitter on pin {self.pin}")
Exemplo n.º 6
0
def ControlSockets():
    
    global Light
    global Heat
    global Blanket
    
    Radio = RFDevice(17)
    Radio.enable_tx()

    HeatOn = 5330227
    HeatOff = 5330236
    LightOn = 5330691
    LightOff = 5330700
    BlanketOn = 5330371
    BlanketOff = 5330380
    UnusedOn = 5332227
    UnusedOff = 5332236
    
    PIN = 189
    
    while True:
        
        if  Heat == 0:            
            Radio.tx_code(HeatOff, 1, PIN)
        
        elif Heat == 1:           
            Radio.tx_code(HeatOn, 1, PIN)
        
        time.sleep(1)
        
        if  Light == 0:            
            Radio.tx_code(LightOff, 1, PIN)
        
        elif Light == 1:            
            Radio.tx_code(LightOn, 1, PIN)
            
        time.sleep(1)
            
        if  Blanket == 0:           
            Radio.tx_code(BlanketOff, 1, PIN)
        
        elif Blanket == 1:            
            Radio.tx_code(BlanketOn, 1, PIN)
        
        time.sleep(1)
Exemplo n.º 7
0
def main():
    bot = telepot.Bot(l.telegram['token'])
    signal.signal(signal.SIGINT, exithandler)
    rfdevice = RFDevice(27)
    rfdevice.enable_rx()
    timestamp = None
    logging.info("Listening for codes on GPIO")
    while True:
       if rfdevice.rx_code_timestamp != timestamp:
           timestamp = rfdevice.rx_code_timestamp
           if str(rfdevice.rx_code) == l.DOORBELL_RF_ID:
               bot.sendMessage(l.telegram['to_user_id'], "Doorbell!")
               logging.info("Doorbell sounded")
               time.sleep(1)  # prevent registering multiple times
           elif rfdevice.rx_code == 5592321:
               logging.info("Not doorbell")
       time.sleep(0.001)
    rfdevice.cleanup()
Exemplo n.º 8
0
Arquivo: server.py Projeto: vpatov/pi
def listen_for_rf_signals():
    rfdevice = RFDevice(gpio)
    prev_timestamp = None

    signal.signal(signal.SIGINT, exithandler)
    rfdevice.enable_rx()

    logging.info("Listening for RF codes on GPIO {}".format(gpio))
    while True:
        try:
            if rfdevice.rx_code_timestamp != prev_timestamp:
                prev_timestamp = rfdevice.rx_code_timestamp
                code = rfdevice.rx_code
                logging.info("Received code: {}".format(code))
            time.sleep(1)
        except Exception as e:
            rfdevice.cleanup()
            logging.error(e.with_traceback())
            break
Exemplo n.º 9
0
def transmit(inputval):
    logging.basicConfig(
        level=logging.INFO,
        datefmt='%Y-%m-%d %H:%M:%S',
        format='%(asctime)-15s - [%(levelname)s] %(module)s: %(message)s',
    )

    code = inputval
    protocol = 1
    pulselength = 350
    rfdevice = RFDevice(17)  #gpio number
    rfdevice.enable_tx()

    logging.info(
        str(code) + " [protocol: " + str(protocol) + ", pulselength: " +
        str(pulselength) + "]")

    rfdevice.tx_code(code, protocol, pulselength)
    rfdevice.cleanup()
Exemplo n.º 10
0
def transmit(job_list=[]):
    trans = RFDevice(TRANSMIT_PIN)
    trans.enable_tx()
    trans.tx_repeat = 10
    for job in job_list:
        trans.tx_code(job, PROTOCOL, TRANS_LENGTH, 24)
        if job == ON_MAIN:
            config.main_state = 1
        elif job == OFF_MAIN:
            config.main_state = 0
        elif job == ON_SEC:
            config.sec_state = 1
        elif job == OFF_SEC:
            config.sec_state = 0
        elif job == ON_LAMP:
            config.lamp_state = 1
        elif job == OFF_LAMP:
            config.lamp_state = 0

    trans.cleanup()
Exemplo n.º 11
0
    def __init__(self, logger: Logger, config: Dict):
        self._logger = logger

        self._topic_to_id: Address_Mapping = config["topic_to_rf_code"]

        self._root_topic = config["mqtt_root_topic"]
        self._host = config["mqtt_address"]["host"]
        self._port = config["mqtt_address"]["port"]

        self._repetitions_number = config["repetitions"]["number"]
        self._repetitions_sleep__ms = config["repetitions"]["sleep__s"]

        # init MQTT
        self._client = mqtt.Client()
        self._client.on_connect = self._on_con
        self._client.on_message = self._on_msg

        # init 433MHz
        self._rfdevice = RFDevice(config["rf_gpio"])
        self._rfdevice.enable_tx()
Exemplo n.º 12
0
def main():
    # Setup MQTT
    client = mqtt.Client()
    client.on_connect = on_connect  # call these on connect and on message
    client.on_message = on_message
    # client.username_pw_set(username='******', password='******')  # need this
    client.connect(MQTT_BROKER)
    # client.loop_forever()    #  don't get past this
    client.loop_start()  # run in background and free up main thread

    # Setup RF
    timestamp = None  # Keep track of the time of the last received message on a code.
    rfdevice = RFDevice(GPIO_PIN)
    rfdevice.enable_rx()
    while True:
        if rfdevice.rx_code_timestamp != timestamp:  # a new code is received
            timestamp = rfdevice.rx_code_timestamp
            if str(rfdevice.rx_code) == RF_CODE_OF_INTEREST:
                client.publish(MQTT_TOPIC, MQTT_MESSAGE)
                time.sleep(SLEEP_BETWEEN_SIGNALS)
Exemplo n.º 13
0
def send(action, device):

    rfdevice = RFDevice (27)
    rfdevice.enable_tx()
    if action == "ON":
        code = device["onCode"]
    elif action == "OFF":
        code = device["offCode"]
    else:
        code = 0
    protocol = device["protocol"]
    pulselength =  device["pulselength"]
    rfdevice.tx_code(code, protocol, pulselength)
    rfdevice.tx_code(code, protocol, pulselength)
    rfdevice.tx_code(code, protocol, pulselength)
    logging.info(str(code) +
             " [protocol: " + str(1) +
             ", pulselength: " + str(350) + "]")
    rfdevice.cleanup()
    return device["description"] + " Turned " + action
Exemplo n.º 14
0
 def __send_code(self, code):
     try:
         _logger.debug("Sending '{} ({:s})' to '{}'".format(
             code, 'on' if code == self._code_on else 'off',
             self._display_name))
         rfdevice = RFDevice(self._gpio_pin)
         rfdevice.enable_tx()
         rfdevice.tx_repeat = self._send_repeat
         rfdevice.tx_code(code, self._protocol, self._pulse_length,
                          self._code_length)
         rfdevice.cleanup()
         return True
     except:  # pragma: no cover
         err_msg = traceback.format_exc(limit=3)
         _logger.error("Error while sending code: " + err_msg)
         if code == self._code_on:
             msg = _('Error while turning the LPD433 power sockets on:\n')
         else:
             msg = _('Error while turning the LPD433 power sockets off:\n')
         broadcast.error(msg + err_msg, source=broadcast.SRC_LPD433)
         return False
Exemplo n.º 15
0
    def __init__(self, driver, max_switches, pca, config):
        super().__init__(driver, "Dusty Bridge")

        self.config = config

        # Setup RF Transmitter
        self.rf = RFDevice(self.config.rf.pin)
        self.rf.enable_tx()
        self.rf.tx_repeat = self.config.rf.tx_repeat
        self.rf.tx_proto = self.config.rf.tx_proto

        self.dust_collector_on = False
        self.gate_to_close = None
        self.active_switch = None
        self.gate_close_counter = -1
        self.servos = {}
        for pin in range(max_switches):
            self.servos[pin] = servo.ContinuousServo(pca.channels[pin], min_pulse=self.config.servo.min_pulse, max_pulse=self.config.servo.max_pulse)
            self.add_accessory(DustySwitch(self, pin, driver, "Dusty Switch #"+str(pin)))
        shutdown_switch = ShutdownSwitch(driver,"Halt")
        self.add_accessory(shutdown_switch)
class PowerPlug(Resource):

    rfdevice = RFDevice(config.gpio_tx)
    rfdevice.enable_tx()

    plugs = {}

    for command in config.commands:
        # config format: [pulse, on, off, "plug", id]
        if len(command) >= 5 and command[3] == "plug":
            plugs[command[4]] = {
                "id": command[4],
                "pulse": command[0],
                "codes": (command[1], command[2]),
                "status": -1
            }

    @staticmethod
    def exists(id):
        if id not in PowerPlug.plugs:
            abort(404, message="Plug {} does not exist.".format(id))

    def get(self, id):
        PowerPlug.exists(id)
        return PowerPlug.plugs[id]

    def put(self, id, status):
        PowerPlug.exists(id)

        if status is True or status == "on":
            self.rfdevice.tx_code(PowerPlug.plugs[id]["codes"][0], 1,
                                  PowerPlug.plugs[id]["pulse"])
            PowerPlug.plugs[id]["status"] = 1
        else:
            self.rfdevice.tx_code(PowerPlug.plugs[id]["codes"][1], 1,
                                  PowerPlug.plugs[id]["pulse"])
            PowerPlug.plugs[id]["status"] = 0
Exemplo n.º 17
0
def RF_run():
    logging.basicConfig(level=logging.INFO, datefmt='%Y-%m-%d %H:%M:%S',
                        format='%(asctime)-15s - [%(levelname)s] %(module)s: %(message)s', )


    parser = argparse.ArgumentParser(description='Receives a decimal code via a 433/315MHz GPIO device')
    parser.add_argument('-g', dest='gpio', type=int, default=4,
                        help="GPIO pin (Default: 4)")
    args = parser.parse_args([])

    signal.signal(signal.SIGINT, exithandler)
    rfdevice = RFDevice(args.gpio)
    rfdevice.enable_rx()
    timestamp = None
    logging.info("Listening for codes on GPIO " + str(args.gpio))

    while True:
        if rfdevice.rx_code_timestamp != timestamp:
            timestamp = rfdevice.rx_code_timestamp
            if rfdevice.rx_code > 100000:


                if RunCheckStatus("rf", "up", "no"):
                    RF_rec("up", rfdevice.rx_code, rfdevice.rx_pulselength, rfdevice.rx_proto)
                elif RunCheckStatus("rf", "down", "no"):
                    RF_rec("down", rfdevice.rx_code, rfdevice.rx_pulselength, rfdevice.rx_proto)
                elif RunCheckStatus("rf", "open", "no"):
                    pass
                else:
                    RF_read(rfdevice.rx_code, rfdevice.rx_pulselength, rfdevice.rx_proto)
                    logging.info("Чтение")
                    logging.info(str(rfdevice.rx_code) +
                                 " [pulselength " + str(rfdevice.rx_pulselength) +
                                 ", protocol " + str(rfdevice.rx_proto) + "]")
        time.sleep(0.01)
    rfdevice.cleanup()
Exemplo n.º 18
0
import MFRC522
import signal
import lcddriver
import json
import random
import pymysql
import os
import time
import signal

stamp = dict()
realstamp = dict()
mqttdevices = dict()
tordevices = torturedevices()
slaves = slaves()
rfdevice = RFDevice( 27 )
rfsend   = RFDevice( 17 )
rfdevice.enable_rx()
rfsend.enable_tx()
rfdevice.tx_repeat = 10
timestamp = None
old_slave_count = -1
old_device_count = -1
logger = logging.getLogger( 'Punisher' )
logger.setLevel( logging.DEBUG )
log = logging.FileHandler('logs/punisher.log')
log.setLevel( logging.DEBUG )
logger.addHandler( log )
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
log.setFormatter( formatter )
logger.addHandler( log )
Exemplo n.º 19
0
                    dest='gpio',
                    type=int,
                    default=18,
                    help="GPIO pin (Default: 18)")
parser.add_argument('-p',
                    dest='pulselength',
                    type=int,
                    default=None,
                    help="Pulselength (Default: 350)")
parser.add_argument('-t',
                    dest='protocol',
                    type=int,
                    default=None,
                    help="Protocol (Default: 1)")
args = parser.parse_args()
rfdevice = RFDevice(args.gpio)
rfdevice.enable_tx()

rfRX = RFDevice(23)
rfRX.enable_rx()
timestamp = None

if args.protocol:
    protocol = args.protocol
else:
    protocol = "default"
if args.pulselength:
    pulselength = args.pulselength
else:
    pulselength = "default"
logging.info(
debounce = 10
short = 4
long = 0.5
global count
count = 0


# pylint: disable=unused-argument
def exithandler(signal, frame):
    rfdevice.cleanup()
    sys.exit(0)


signal.signal(signal.SIGINT, exithandler)

rfdevice = RFDevice(gpio=27)
rfdevice.enable_rx()
timestamp = None
oldtime = time.perf_counter()
oldtime1 = time.perf_counter()
oldtime2 = time.perf_counter()
oldtime3 = time.perf_counter()
print(short)
print(long)
#Received code 835186. is L Switch near entrance
#Received code 818562. is L Switch in hall way
#-------
#Received code 3764961. is big button on car remote <---- Living Room
#Received code 3764962. is next button on car remote <----Leo
#Received code 3764964. is next button on car remote <----My room
#Received code 3764968. is small button on car remote <--- all off
Exemplo n.º 21
0
#!/usr/bin/env python3
from rpi_rf import RFDevice

rfdevice = RFDevice(17)
rfdevice.enable_tx()
rfdevice.tx_repeat = 1

rfdevice.tx_code(4265276, 1, 188)
rfdevice.tx_code(4265276, 1, 191)
rfdevice.tx_code(4265276, 1, 191)
rfdevice.tx_code(4265276, 1, 191)
rfdevice.cleanup()
Exemplo n.º 22
0
gpio.setmode(gpio.BCM)
gpio.setwarnings(False)

rfpin = 17
hallpin = 18
hallpout = 23
pulselengthIn = 157
protocolIn = 3
codeIn = 12016

pulselengthOut = 608
protocolOut = 1
codeOut = 22016

rfdevice = RFDevice(rfpin)
rfdevice.enable_tx()
gpio.setup(hallpin, gpio.IN)
gpio.setup(hallpout, gpio.IN)

def execute():

		while True:
		if(gpio.input(hallpout) == False) :
			print("Came Out")
			rfdevice.tx_code(codeOut, protocolOut, pulselengthOut)
	
		time.sleep(0.3)

if __name__ == '__main__':
		my_thread = threading.Thread(target=execute)
Exemplo n.º 23
0
import time
from rpi_rf import RFDevice
rfdevice = RFDevice(27)
rfdevice.enable_rx()
timestamp = None
while True:
    if rfdevice.rx_code_timestamp != timestamp:
        timestamp = rfdevice.rx_code_timestamp
        if rfdevice.rx_bitlength == 49:
            id = rfdevice.rx_code >> 44
            seq = (rfdevice.rx_code >> 40) & 0x0F
            temp = (rfdevice.rx_code >> 30) & 0x3FF
            humid = (rfdevice.rx_code >> 20) & 0x3FF
            pres = (rfdevice.rx_code >> 8) & 0xFFF
            crc = rfdevice.rx_code & 0xFF
            print("%X" % rfdevice.rx_code)
            print(
                "id: %d, seq %d, temp: %d, humid: %d, pres: %d, crc: %d, pulselength: %d, protocol: %d"
                % (id, seq, temp, humid, pres, crc, rfdevice.rx_pulselength,
                   rfdevice.rx_proto))
        else:
            id = rfdevice.rx_code >> 28
            var = (rfdevice.rx_code >> 24) & 0x0F
            val = (rfdevice.rx_code >> 8) & 0xFFFF
            crc = (rfdevice.rx_code) & 0xFF
            print(
                str(id) + " " + str(var) + " " + str(val) + " " + str(crc) +
                " [pulselength " + str(rfdevice.rx_pulselength) +
                ", protocol " + str(rfdevice.rx_proto) + ", bitlength ",
                rfdevice.rx_bitlength, "]")
    time.sleep(0.01)
Exemplo n.º 24
0
        # load environment variables
        load_dotenv()

        # setup logger
        logging.basicConfig(format = "%(asctime)s %(levelname)-10s %(message)s", level = logging.INFO)

        # setup mqtt
        client = mqtt.Client("rf_client")
        client.on_connect = on_connect
        client.on_log = on_log
        client.enable_logger()
        client.connect(os.getenv("MQTT_HOST_ADDRESS"))
        client.loop_start()

        # setup rf
        rfdevice = RFDevice(gpio_pin)
        rfdevice.enable_rx()

        # start listening for rf messages
        logging.info("Listening for codes on GPIO " + str(gpio_pin))
        timestamp = None

        while True:
            if rfdevice.rx_code_timestamp != timestamp:
                timestamp = rfdevice.rx_code_timestamp

                # logging.info(
                #     "Received message: %s (pulselength %s, protocol %s)", 
                #     rfdevice.rx_code,
                #     rfdevice.rx_pulselength,
                #     rfdevice.rx_proto
Exemplo n.º 25
0
from rpi_rf import RFDevice

GPIO = 17
TX_PROTO = 1
TX_REPEAT = 8
TX_PULSELENGTH = None

# init the gpio device
rfdevice = RFDevice(gpio=GPIO,
                    tx_proto=TX_PROTO,
                    tx_pulselength=TX_PULSELENGTH,
                    tx_repeat=TX_REPEAT)
#tx_length=24,
#rx_tolerance=80)

# send code
rfdevice.enable_tx()
rfdevice.tx_code(123456789)
rfdevice.cleanup()
Exemplo n.º 26
0
import time
import requests
from datetime import datetime, timedelta
import math
from rpi_rf import RFDevice
from ..misc import config as _config
config = _config.get().rf

rfdevice = RFDevice(config.gpio_rx)
rfdevice.enable_rx()

timestamp = None
last_command_id = -1
last_command_time = datetime.now()
while True:
    if rfdevice.rx_code_timestamp != timestamp:
        timestamp = rfdevice.rx_code_timestamp

        if rfdevice.rx_proto != 1:
            continue

        print("DEBUG" + str(rfdevice.rx_pulselength) + " " +str(rfdevice.rx_code))

        # search for the right command
        status = -1
        for i, command in enumerate(config.commands):
            # pulse, on, off, [type, id]
            if math.fabs(command[0] - rfdevice.rx_pulselength) < 5 and math.fabs(command[1] - rfdevice.rx_code) < 1:
                status = 1
                break
            if math.fabs(command[0] - rfdevice.rx_pulselength) < 5 and math.fabs(command[2] - rfdevice.rx_code) < 1:
Exemplo n.º 27
0
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# Wait until connection suceeds before continuing
while True:
    try:
        client_socket.connect((address, port))
        break
    except:    
        print("Connection failed!")
        time.sleep(5)
        print("Trying again...")
        continue
print("Connected to server!")

# RF device setup
rfdevice = RFDevice(SEND_PIN)
rfdevice.enable_tx()

# Create connection as file-object
# wb: write only in binary format 
connection = client_socket.makefile('wb')
try:
    #Create thread pool and locks
    connection_lock = threading.Lock()
    pool = []
    pool_lock = threading.Lock()
    #Streaming objects class
    class ImageStreamer(threading.Thread):
        def __init__(self):
            super(ImageStreamer, self).__init__()
            self.stream = io.BytesIO()
Exemplo n.º 28
0
def main():
    parser = argparse.ArgumentParser(
        description='Sends/Receives a decimal code via a 433/315MHz GPIO device'
    )
    parser.add_argument('-d',
                        dest='direction',
                        type=int,
                        default=2,
                        help="Send (1) or Receive (2) (Default: 2)")
    parser.add_argument('-g',
                        dest='gpio',
                        type=int,
                        default=17,
                        help="GPIO pin (Default: 17)")

    # Send-specific commands
    parser.add_argument('-c',
                        dest='code',
                        type=int,
                        required=False,
                        help="Decimal code to send")
    parser.add_argument('-p',
                        dest='pulselength',
                        type=int,
                        default=None,
                        help="Pulselength (Default: 350)")
    parser.add_argument('-t',
                        dest='protocol',
                        type=int,
                        default=None,
                        help="Protocol (Default: 1)")
    args = parser.parse_args()

    if args.direction == 1:
        rfdevice = RFDevice(args.gpio)
        rfdevice.enable_tx()

        if args.protocol:
            protocol = args.protocol
        else:
            protocol = "default"
        if args.pulselength:
            pulselength = args.pulselength
        else:
            pulselength = "default"

        print(
            str(args.code) + " [protocol: " + str(protocol) +
            ", pulselength: " + str(pulselength) + "]")

        rfdevice.tx_code(args.code, args.protocol, args.pulselength)
        rfdevice.cleanup()

    elif args.direction == 2:
        rfdevice = RFDevice(args.gpio)
        rfdevice.enable_rx()
        timestamp = None
        print("Listening for codes on GPIO " + str(args.gpio))
        try:
            while True:
                if rfdevice.rx_code_timestamp != timestamp:
                    timestamp = rfdevice.rx_code_timestamp
                    print(
                        str(rfdevice.rx_code) + " [pulselength " +
                        str(rfdevice.rx_pulselength) + ", protocol " +
                        str(rfdevice.rx_proto) + "]")
                time.sleep(0.01)
        except KeyboardInterrupt:
            print("Keyboard Interupt")
        finally:
            rfdevice.cleanup()

    else:
        print("Invalid option: '{opt}'. "
              "You may either Send (1) or Receive (2). ".format(
                  opt=args.direction))
Exemplo n.º 29
0
                    type=int,
                    default=17,
                    help="GPIO pin (Default: 17)")
parser.add_argument('-p',
                    dest='pulselength',
                    type=int,
                    default=None,
                    help="Pulselength (Default: 350)")
parser.add_argument('-t',
                    dest='protocol',
                    type=int,
                    default=None,
                    help="Protocol (Default: 1)")
args = parser.parse_args()

rfdevice = RFDevice(args.gpio)
rfdevice.enable_tx()

if args.protocol:
    protocol = args.protocol
else:
    protocol = "default"
if args.pulselength:
    pulselength = args.pulselength
else:
    pulselength = "default"
logging.info(
    str(args.vanne) + " " + str(args.stat) + " [protocol: " + str(protocol) +
    ", pulselength: " + str(pulselength) + "]")

const = 125
Exemplo n.º 30
0
def main():
    parser = argparse.ArgumentParser(
        description=
        'Receives a decimal code via a 433/315MHz GPIO device and send it to an MQTT broker'
    )
    parser.add_argument('-g',
                        dest='gpio',
                        type=int,
                        default=27,
                        help="GPIO pin (Default: 27)")
    parser.add_argument('-m',
                        dest='mqtt_broker_addr',
                        type=str,
                        default='127.0.0.1',
                        help="Address of the MQTT broker (default: 127.0.0.1)")
    parser.add_argument('-p',
                        dest='mqtt_broker_port',
                        type=int,
                        default=1883,
                        help="Port of the MQTT broker (default: 1883)")
    parser.add_argument('-t',
                        dest='mqtt_topic',
                        type=str,
                        default='rc',
                        help="Topic to send the messages to (default: rc)")
    parser.add_argument(
        '-r',
        dest='rate_limit',
        type=int,
        default=200,
        help=
        "Rate limit in milliseconds to filter burst of codes sent by RF remotes (default: 200)"
    )
    parser.add_argument('-v',
                        dest='verbose',
                        action='store_true',
                        help="More verbose logs")
    args = parser.parse_args()

    if args.verbose:
        log.setLevel(logging.DEBUG)

    MQTT_CONNECT_TIMEOUT = 120
    timeout = 0
    while timeout < MQTT_CONNECT_TIMEOUT:
        try:
            mqtt_client = mqtt_connect(args.mqtt_broker_addr,
                                       args.mqtt_broker_port)
        except ConnectionRefusedError:
            log.info(
                "Could not connect to mqtt broker, Trying again in 5 sec...")
            time.sleep(5)
            timeout += 5
            continue
        break

    signal.signal(signal.SIGINT, exithandler)
    rfdevice = RFDevice(args.gpio)
    rfdevice.enable_rx()
    timestamp = None
    previous_signal = (0, 0)
    log.info("Listening for codes on GPIO " + str(args.gpio))
    while True:
        if rfdevice.rx_code_timestamp != timestamp:
            timestamp = rfdevice.rx_code_timestamp
            code = rfdevice.rx_code
            protocol = rfdevice.rx_proto
            pulselength = rfdevice.rx_pulselength

            log.debug("code: {}, protocol: {}, timestamp: {}, pulselength: {}".
                      format(
                          code,
                          protocol,
                          timestamp,
                          pulselength,
                      ))
            previous_code, previous_timestamp = previous_signal
            min_delta_t = args.rate_limit * 1000
            if code == previous_code:
                delta_t = timestamp - previous_timestamp
                if delta_t < min_delta_t:
                    log.debug(
                        "Rate limiting, got same code: {} and delta t: {}/{}".
                        format(
                            code,
                            delta_t,
                            min_delta_t,
                        ))
                    continue
            mqtt_send(mqtt_client, args.mqtt_topic, str(code))
            previous_signal = (code, timestamp)

        time.sleep(0.01)
    rfdevice.cleanup()