class RadioSwitch: DATA_PIN = 27 def __init__(self): self.rf_device = RFDevice(RadioSwitch.DATA_PIN) self.rf_device.enable_rx() self.last_read_timestamp = None def __del__(self): self.rf_device.cleanup() def is_available(self): if self.rf_device.rx_code_timestamp != self.last_read_timestamp: return True return False def clear(self): self.last_read_timestamp = self.rf_device.rx_code_timestamp def read(self): return { "code": self.rf_device.rx_code, "pulse_length": self.rf_device.rx_pulselength, "protocol": self.rf_device.rx_proto, }
class receiver: def __init__(self, pin=27, handler=lambda x: print(x)): self.rfdevice = RFDevice(pin) self.rfdevice.enable_rx() self.handler = handler self.threshold = 1000000 self.timestamps = defaultdict(int) def run(self): self.running = True logging.debug("Receiver ready") rfdevice = self.rfdevice timestamp = None while self.running: if rfdevice.rx_code_timestamp != timestamp: timestamp = rfdevice.rx_code_timestamp code = rfdevice.rx_code if rfdevice.rx_code_timestamp > self.timestamps[ code] + self.threshold: self.timestamps[code] = rfdevice.rx_code_timestamp logging.debug("Received RF code: " + str(code) + " [pulselength " + str(rfdevice.rx_pulselength) + ", protocol " + str(rfdevice.rx_proto) + "]") self.handler(code) time.sleep(0.01) def stop(self): self.running = False self.rfdevice.cleanup()
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))
class Switch433Controller(Thread): def __init__(self, rx_pin, tx_pin, switches): super(Switch433Controller, self).__init__() self.setDaemon(True) self._evt_q = Queue() self._switches = switches self._rxdevice = RFDevice(rx_pin) self._rxdevice.enable_rx() self._txdevice = RFDevice(tx_pin) self._txdevice.enable_tx() for sw in switches: switches[sw].set_ctl(self) signal.signal(signal.SIGINT, self.exithandler()) def exithandler(self): def exithandler(signal, frame): self._rxdevice.cleanup() self._txdevice.cleanup() sys.exit(0) return exithandler def send(self, codes, repeat=0): if not isinstance(codes, list): codes = [codes] for code in codes: for _ in range(repeat + 1): self._txdevice.tx_code(code, 1, 293) @property def evt_queue(self): return self._evt_q def _check_code(self, code): # print("received code:'{}'".format(code)) for sw in self._switches: if code == self._switches[sw].ON: print("Switch " + sw + " turned on") self.evt_queue.put((sw, True)) elif code == self._switches[sw].OFF: print("Switch " + sw + " turned off") self.evt_queue.put((sw, False)) def run(self): timestamp = None print("Listening for codes") while True: if self._rxdevice.rx_code_timestamp != timestamp: timestamp = self._rxdevice.rx_code_timestamp self._check_code(self._rxdevice.rx_code) time.sleep(1)
class Transmit433MHz: """Transmit/Receive 433MHz commands""" def __init__(self, pin, protocol=1, pulse_length=189): self.device = None self.pin = pin self.protocol = protocol self.pulse_length = pulse_length self.num = 0 self.timestamp = None def enable_receive(self): try: self.device = RFDevice(self.pin) self.device.enable_rx() self.num = 0 except Exception as err: logger.exception( "{cls} raised an exception when enabling receiving: " "{err}".format(cls=type(self).__name__, err=err)) def receive_available(self): try: if self.device.rx_code_timestamp != self.timestamp: self.timestamp = self.device.rx_code_timestamp command = self.device.rx_code pulse_length = self.device.rx_pulselength protocol = self.device.rx_proto return self.num, command, pulse_length, protocol return 0, 0, 0, 0 except Exception as err: logger.exception( "{cls} raised an exception when receiving: " "{err}".format(cls=type(self).__name__, err=err)) def transmit(self, cmd): try: self.device = RFDevice(self.pin) self.device.enable_tx() self.device.tx_code(cmd, self.protocol, self.pulse_length) self.cleanup() except Exception as err: logger.exception( "{cls} raised an exception when transmitting: " "{err}".format(cls=type(self).__name__, err=err)) def cleanup(self): self.device.cleanup()
class RFControl(object): 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)) def cleanup(self): if self.dev: logPrint("RF cleanup") self.dev.cleanup() self.dev = None def should_open_the_gate(self): if not self.dev: return False if self.last_timestamp == self.dev.rx_code_timestamp: return False self.last_timestamp = self.dev.rx_code_timestamp proto = self.dev.rx_proto code = self.dev.rx_code pulselength = self.dev.rx_pulselength if None != self.proto and proto != self.proto: return False logPrint("Got RF signal: code %d pulselength %d" % (code, pulselength)) for pulse_min, pulse_max in self.pulse_ranges: if pulse_min <= pulselength <= pulse_max: break else: return False for code_min, code_max in self.code_ranges: if code_min <= code <= code_max: break else: return False return True
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()
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
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)
class RfClient: """ Author: Ronny Friedland Provides methods to access the rf 433mhz client """ timestamp = None def __init__(self, pin): """ Constructor to initialize der receiver connected to the given pin :param pin: """ self.rfdevice = RFDevice(int(pin)) self.rfdevice.enable_rx() signal.signal(signal.SIGINT, self.cleanup) def cleanup(self): """ If initialized cleanup :return: """ if self.rfdevice is not None: self.rfdevice.cleanup() def read(self): """ Reads the current available data :return: the transmitted code or None if no signal """ if self.rfdevice.rx_code_timestamp != self.timestamp: self.timestamp = self.rfdevice.rx_code_timestamp logging.info( str(self.rfdevice.rx_code) + " [pulselength " + str(self.rfdevice.rx_pulselength) + ", protocol " + str(self.rfdevice.rx_proto) + "]") return self.rfdevice.rx_code else: return None
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()
class Receiver: def __init__(self, pin: int): self.pin = pin self.device = RFDevice(pin) self.device.enable_rx() print(f"Initialize receiver on pin {self.pin}") def start(self): print("Enter Ctrl-C to stop") try: self.__listen() except KeyboardInterrupt: print("Stopping...") def __listen(self): timestamp = None while True: if self.device.rx_code_timestamp != timestamp: timestamp = self.device.rx_code_timestamp print(f"[CODE]: {self.device.rx_code} [LENGTH]: {self.device.rx_pulselength} [PROTOCOL]: {self.device.rx_proto}") time.sleep(0.01)
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()
class Plugin(plugin.Plugin): """ plugin for rf433_receive """ def init(self): """ initialize """ self.rfdevice = None signal.signal(signal.SIGINT, self.exithandler) self.rfdevice = RFDevice(27) def exithandler(signal, frame): """ exit signal handler """ self.rfdevice.cleanup() def setTuyaStatus(self, devid, newstatus, switch=1): done = False for attempt in ("first", "second", "third"): try: logger.logDebug("%s try to set status on %s" % (attempt, devid)) key = CFG.DEVICES[devid] tuyadev = pytuya.OutletDevice(devid, key[0], key[1]) status = tuyadev.status()['dps'][str(switch)] if status == newstatus: logger.logDebug("status already set, skipping %s" % devid) break tuyadev.set_status(newstatus, switch) time.sleep(CFG.SLEEP_INTERVAL) status = tuyadev.status()['dps'][str(switch)] if status == newstatus: logger.logDebug("status successfully set %s" % devid) done = True except: logger.logError("failed to set status of %s" % devid) if done: break def run(self): """ plugin main """ self.rfdevice.enable_rx() timestamp = None lastcode = None while True: if self.rfdevice.rx_code_timestamp != timestamp: try: if lastcode == self.rfdevice.rx_code and self.rfdevice.rx_code_timestamp < timestamp + 1000000: timestamp = self.rfdevice.rx_code_timestamp logger.logDebug("rf433_receive skipping: %s" % str(timestamp)) time.sleep(CFG.SLEEP_INTERVAL) continue except: logger.logDebug("rf433_receive passing: %s" % str(timestamp)) logger.logDebug("rf433_receive timestamp: %s" % str(timestamp)) timestamp = self.rfdevice.rx_code_timestamp lastcode = self.rfdevice.rx_code logger.logDebug("rf433_receive code: %s length %s protocol: %s" % (str(self.rfdevice.rx_code), str(self.rfdevice.rx_pulselength), str(self.rfdevice.rx_proto))) keycode = str(self.rfdevice.rx_code) if keycode in CFG.RF433.keys() and CFG.RF433[keycode][0]: if len(CFG.RF433[keycode]) == 2: self.setTuyaStatus(CFG.RF433[keycode][0], CFG.RF433[keycode][1]) if len(CFG.RF433[keycode]) == 3: self.setTuyaStatus(CFG.RF433[keycode][0], CFG.RF433[keycode][1], CFG.RF433[keycode][2]) time.sleep(CFG.SLEEP_INTERVAL) else: self.sendEvents(EVENT.RF433_PRESSED % self.rfdevice.rx_code) time.sleep(CFG.SLEEP_INTERVAL) rfdevice.cleanup() eventhandler = { } def receiveData(self, data_dict): """ handle received data :param data_dict: received data """ # try autoresponse first self.autoResponder(data_dict) if "method" in data_dict.keys(): # cmds if data_dict["method"] == METHOD.CMD and data_dict["params"]["target"] == self.plugin_name: for cmdstring in data_dict["params"]["cmds"]: try: path = self.items if not cmdstring.split(CONST.DELIMITER)[0] in cfg.MY_PLACES: continue for p in cmdstring.split(CONST.DELIMITER): path = path[p] code = path self.tasker.putTask(code) except Exception as err: logger.logError("Failed to run command %s: %s" % (str(cmdstring), str(err))) # events if data_dict["method"] == METHOD.EVENT: for event in data_dict["params"]["events"]: try: if event in self.eventhandler.keys(): self.eventhandler[event](self) except Exception as err: logger.logError("Failed to handle event '%s' error: %s" % (event, str(err)))
class RadioClient: def __init__(self, config): self.rf_device = RFDevice(config.get("rxPin", 2)) self.rf_device.enable_rx() self.rx_timestamp = None self.debounce = Debounce.Debounce(config.get("rxDebounce", 1500)) self.keymap = {} self.load_keymap("radio.json") self.disallow_type2 = False def authorize(self, radio_code): message = self.get(radio_code) if not message: return False if message['type'] == '1': return True return not self.disallow_type2 def toggle_type2(self): self.disallow_type2 = not self.disallow_type2 def load_keymap(self, filename): with open(filename) as f: self.keymap = json.load(f) def remember(self, radio_code, remote, type='2'): if str(radio_code) in self.keymap: self.keymap.pop(str(radio_code)) self.keymap[str(radio_code)] = { 'message': 'rotate' + str(remote), 'type': str(type) } self.save_keymap("radio.json") def rememberLamp(self, radio_code, remote): if str(radio_code) in self.keymap: self.keymap.pop(str(radio_code)) self.keymap[str(radio_code)] = { 'message': 'lamp' + str(remote), 'type': str('1') } self.save_keymap("radio.json") def get(self, radio_code): if str(radio_code) not in self.keymap: return None return self.keymap[str(radio_code)] def save_keymap(self, filename): text = json.dumps(self.keymap) text_file = open(filename, "w") text_file.write(text) text_file.close() def receive_radio(self): if self.rf_device.rx_code_timestamp == self.rx_timestamp: return None if not self.rf_device.rx_code: return None if not self.rf_device.rx_proto == 1: return None if not self.debounce.debounce(): return None self.rx_timestamp = self.rf_device.rx_code_timestamp return self.rf_device.rx_code
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( str(args.code) + " [protocol: " + str(protocol) + ", pulselength: " + str(pulselength) + "]") rfdevice.tx_code(args.code, args.protocol, args.pulselength) #rfdevice.cleanup()
class Plugin(plugin.Plugin): """ plugin for rf433_receive """ def init(self): """ initialize """ self.rfdevice = None signal.signal(signal.SIGINT, self.exithandler) self.rfdevice = RFDevice(27) def exithandler(signal, frame): """ exit signal handler """ self.rfdevice.cleanup() def setTuyaStatus(self, devid, newstatus, switch=1): done = False for attempt in ("first", "second", "third"): try: logger.logDebug("%s try to set status on %s" % (attempt, devid)) key = CFG.DEVICES[devid] tuyadev = pytuya.OutletDevice(devid, key[0], key[1]) status = tuyadev.status()['dps'][str(switch)] if status == newstatus: logger.logDebug("status already set, skipping %s" % devid) break tuyadev.set_status(newstatus, switch) time.sleep(CFG.SLEEP_INTERVAL) status = tuyadev.status()['dps'][str(switch)] if status == newstatus: logger.logDebug("status successfully set %s" % devid) done = True except: logger.logError("failed to set status of %s" % devid) if done: break def run(self): """ plugin main """ self.rfdevice.enable_rx() timestamp = None lastcode = None while True: if self.rfdevice.rx_code_timestamp != timestamp: try: if lastcode == self.rfdevice.rx_code and self.rfdevice.rx_code_timestamp < timestamp + 1000000: timestamp = self.rfdevice.rx_code_timestamp logger.logDebug("rf433_receive skipping: %s" % str(timestamp)) time.sleep(CFG.SLEEP_INTERVAL) continue except: logger.logDebug("rf433_receive passing: %s" % str(timestamp)) logger.logDebug("rf433_receive timestamp: %s" % str(timestamp)) timestamp = self.rfdevice.rx_code_timestamp lastcode = self.rfdevice.rx_code logger.logDebug( "rf433_receive code: %s length %s protocol: %s" % (str(self.rfdevice.rx_code), str(self.rfdevice.rx_pulselength), str(self.rfdevice.rx_proto))) keycode = str(self.rfdevice.rx_code) if keycode in CFG.RF433.keys() and CFG.RF433[keycode][0]: if len(CFG.RF433[keycode]) == 2: self.setTuyaStatus(CFG.RF433[keycode][0], CFG.RF433[keycode][1]) if len(CFG.RF433[keycode]) == 3: self.setTuyaStatus(CFG.RF433[keycode][0], CFG.RF433[keycode][1], CFG.RF433[keycode][2]) time.sleep(CFG.SLEEP_INTERVAL) else: self.sendEvents(EVENT.RF433_PRESSED % self.rfdevice.rx_code) time.sleep(CFG.SLEEP_INTERVAL) rfdevice.cleanup() eventhandler = {} def receiveData(self, data_dict): """ handle received data :param data_dict: received data """ # try autoresponse first self.autoResponder(data_dict) if "method" in data_dict.keys(): # cmds if data_dict["method"] == METHOD.CMD and data_dict["params"][ "target"] == self.plugin_name: for cmdstring in data_dict["params"]["cmds"]: try: path = self.items if not cmdstring.split( CONST.DELIMITER)[0] in cfg.MY_PLACES: continue for p in cmdstring.split(CONST.DELIMITER): path = path[p] code = path self.tasker.putTask(code) except Exception as err: logger.logError("Failed to run command %s: %s" % (str(cmdstring), str(err))) # events if data_dict["method"] == METHOD.EVENT: for event in data_dict["params"]["events"]: try: if event in self.eventhandler.keys(): self.eventhandler[event](self) except Exception as err: logger.logError( "Failed to handle event '%s' error: %s" % (event, str(err)))
# Elegant shutdown def exithandler(): termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_settings) try: rx.cleanup() tx.cleanup() except: pass sys.exit(0) # Activate our transmitter and received tx = RFDevice(17) tx.enable_tx() rx = RFDevice(27) rx.enable_rx() # Receiving loop def rec(rx): print("Receiving") lastTime = None while True: currentTime = rx.rx_code_timestamp if ( currentTime != lastTime and (lastTime is None or currentTime - lastTime > 350000) ): lastTime = rx.rx_code_timestamp
from rpi_rf import RFDevice rfdevice = None # pylint: disable=unused-argument def exithandler(signal, frame): rfdevice.cleanup() sys.exit(0) 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=27, help="GPIO pin (Default: 27)") 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 logging.info(str(rfdevice.rx_code) + " [pulselength " + str(rfdevice.rx_pulselength) + ", protocol " + str(rfdevice.rx_proto) + "]") time.sleep(0.01) rfdevice.cleanup()
def main(): #Config config = configparser.ConfigParser() config.read('config.ini') cMqtt = config['MQTT'] cGPIO = config['GPIO'] cDevices = config['DEVICES'] #MQTT client = mqtt.Client() client.on_connect = on_connect ##client.on_message = on_message client.username_pw_set(cMqtt['username'], cMqtt['password']) client.connect(cMqtt['host']) client.loop_start() # RF signal.signal(signal.SIGINT, exithandler) rfdevice = RFDevice(int(cGPIO['pin'])) rfdevice.enable_rx() timestamp = None logging.info("Listening for codes on GPIO " + str(cGPIO['pin'])) for device, name in cDevices.items(): client.publish( "homeassistant/device_automation/rpi-433-mqtt/" + str(device) + "/config", json.dumps({ "automation_type": "trigger", "topic": "homeassistant/device_automation/rpi-433-mqtt/" + str(device) + "/topic", "type": "click", "subtype": "on", "payload": "on", "device": { "identifiers": str(device), "name": str(name), "model": "raspberryPI" } })) while True: if rfdevice.rx_code_timestamp != timestamp: timestamp = rfdevice.rx_code_timestamp if str(rfdevice.rx_code) in cDevices: client.publish( "homeassistant/device_automation/rpi-433-mqtt/" + str(rfdevice.rx_code) + "/topic", "on") logging.info( str(rfdevice.rx_code) + " [pulselength " + str(rfdevice.rx_pulselength) + ", protocol " + str(rfdevice.rx_proto) + "]") time.sleep(0.01) rfdevice.cleanup()
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=GPIO_PIN, help="GPIO pin (Default: 27)") args = parser.parse_args() signal.signal(signal.SIGINT, exithandler) rfdevice = RFDevice(args.gpio) rfdevice.disable_tx() rfdevice.enable_rx() timestamp = None logging.info("Listening for codes on GPIO " + str(args.gpio)) # The callback for when the client receives a CONNACK response from the server. def on_connect(client, userdata, flags, rc): print("Connected with result code " + str(rc)) #client = mqtt_client.Client() #client.on_connect = on_connect #client.connect(MQTT_HOST, 1883) count = 0 c = "" while True:
class RfController: def __init__(self): self.rfReceiver = RFDevice(27) self.rfReceiver.enable_rx() self.rfTransmitter = RFDevice(17) self.rfTransmitter.tx_repeat = 20 self.timestamp = None def exithandler(self, signal, frame): self.rfReceiver.cleanup() self.rfTransmitter.cleanup() sys.exit(0) async def receive(self, timeout=None, expected_response=None): start = datetime.now() while True: if self.rfReceiver.rx_code_timestamp != self.timestamp: if self.valid_rx(self.rfReceiver.rx_pulselength, self.rfReceiver.rx_proto): self.timestamp = self.rfReceiver.rx_code_timestamp if self.rfReceiver.rx_code == expected_response: break elif not expected_response: break if timeout: diff = (datetime.now() - start).seconds if diff > timeout: break await asyncio.sleep(0.01) return self.rfReceiver.rx_code def valid_rx(self, pulse_length, protocol): if 349 <= pulse_length <= 354 and protocol == 1: return True else: return False async def get_response(self, timeout=None, expected_response=None): return await self.receive(timeout, expected_response) async def send(self, data): try: log_info_message('Sending ' + str(data)) self.rfReceiver.disable_rx() await asyncio.sleep(0.01) self.rfTransmitter.enable_tx() await asyncio.sleep(0.01) self.rfTransmitter.tx_code(data, 1) await asyncio.sleep(0.01) self.rfTransmitter.disable_tx() await asyncio.sleep(0.01) self.rfReceiver.enable_rx() log_info_message('Sent Data') await asyncio.sleep(1) except Exception as e: print('Exception while sending - retrying: ' + str(e)) await self.send(data) def exit(self): self.rfTransmitter.cleanup() self.rfReceiver.cleanup() return def disable_receiver(self): self.rfReceiver.disable_rx()