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()
class Heater: rfdevice = None protocol = 1 pulselength = 164 currentlyOn = True # assume its on to start and turn off. def on(self): if not self.currentlyOn: self.rfdevice.tx_code(1398067,self.protocol,self.pulselength,24) self.currentlyOn = True def off(self): if self.currentlyOn: self.rfdevice.tx_code(1398076,self.protocol,self.pulselength,24) self.currentlyOn = False def __init__(self): self.rfdevice = RFDevice(gpio) self.rfdevice.enable_tx() self.rfdevice.tx_repeat = 100 self.protocol = 1 self.pulselength = 164 self.off() def __del__(self): print("Destuctor called") self.off() self.rfdevice.cleanup()
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)
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, }
def __init__(self, gpio=17): # Init AC state self.reset(False) # Init RF self.rfdevice = RFDevice(gpio) self.rfdevice.enable_tx() self.rfdevice.tx_repeat = 10
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 self.device = RFDevice(self.pin)
def __init__(self, queue, messages=dict(), pin=17, protocol=1, pulse=180): self.rfdevice = RFDevice(pin) self.rfdevice.enable_tx() self.protocol = protocol self.pulse = pulse self.queue = queue self.messages = messages logging.debug("Loaded messages mapping: '" + str(self.messages) + "'")
def __init__(self): self.rfdevice = RFDevice(gpio) self.rfdevice.enable_tx() self.rfdevice.tx_repeat = 100 self.protocol = 1 self.pulselength = 164 self.off()
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
class RFController: def __init__(self, config): self.rfdevice = RFDevice(config['gpio']) self.rfdevice.enable_tx() self.config = config self.state_topic = config['state_topic'] self.command_topic = config['command_topic'] self.protocol = config['protocol'] self.states = {} self.dirty = [] self.lock = Lock() def setup(self, client): self.client = client logger.info("Subscribing to topic: {}".format(self.command_topic)) self.client.subscribe(self.command_topic) def pop(self): with self.lock: if len(self.dirty) > 0: logger.info("Elements on queue: {}".format(len(self.dirty))) return self.dirty.pop(0) else: return None def size(self): with self.lock: return len(self.dirty) def update(self): while self.size() > 0: code = self.pop() logger.info("Update!") self.broadcast(code) def send_state(self, new_states): states = json.dumps(new_states) logger.info("Sending states {}".format(self.states)) self.client.publish(topic=self.state_topic, payload=states, retain=True, qos=1) def broadcast(self, code): logger.info("Broadcasting all states!") for x in range(0,2): for pulse_length in PULSE_LENGTH: logger.info("RFDevice code={} protocol={} pulse_length={}".format(code, self.protocol, pulse_length)) self.rfdevice.tx_code(code, self.protocol, pulse_length) time.sleep(0.1) def handle_message(self, msg): logger.info("Got message") logger.info(msg.payload) if msg.topic == self.command_topic: message = json.loads(msg.payload.decode('utf-8')) with self.lock: self.states[str(message['name'])] = int(message['code']) self.dirty.append(int(message['code'])) self.send_state(self.states)
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 __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 __init__(self, gpio, invert_output=False): self.device = RFDevice(gpio) self.device.tx_repeat = 5 self.gpio = gpio #~self.low = GPIO.HIGH if invert_output else GPIO.LOW #~self.high = GPIO.LOW if invert_output else GPIO.HIGH self.low = GPIO.LOW self.high = GPIO.HIGH
def init(self): """ initialize """ self.rfdevice = None signal.signal(signal.SIGINT, self.exithandler) self.rfdevice = RFDevice(27)
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 __init__(self, config): self.rfdevice = RFDevice(config['gpio']) self.rfdevice.enable_tx() self.config = config self.state_topic = config['state_topic'] self.command_topic = config['command_topic'] self.protocol = config['protocol'] self.states = {} self.dirty = [] self.lock = Lock()
def __init__(self, logger=None, pin=11): self._pin = pin self._protocol = 1 self._length = 444 self._logger = logger if self._logger == None: self._logger = Logger('RF_Send', Logger.INFO) self._logger.debug("Initialize RF Sender on channel {}".format(pin)) self._rfdevice = RFDevice(pin) self._rfdevice.enable_tx()
def data_tx(code: int, rfpin: int): rfdevice = RFDevice(rfpin) rfdevice.enable_tx() rfdevice.tx_repeat = 10 print('sent code:' + str(code)) rfdevice.tx_code(code, 1, 500, 24) rfdevice.cleanup()
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)
def turnon_light(): try: rfdevice = RFDevice(17) rfdevice.enable_tx() rfdevice.tx_repeat = 10 rfdevice.tx_code(4478259, 1, 186, 24) rfdevice.cleanup() return Response('Light turned on!') except: return Response('Error with turning on light.')
def handle_rpirfhomeon(self, message): rfdevice = RFDevice(17) #default gpio pin rfdevice.enable_tx() rfdevice.tx_code(267571, 1, 172) #globes code, protocol, pulse rfdevice.tx_code(267715, 1, 172) #stand code, protocol, pulse rfdevice.cleanup() self.speak_dialog('rpirf')
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 radioControl(self, i): """ Program function: 433Mhz radio code transmission""" logging.info('Entering Radio Control Function') flag = False t_start = time.time() rfdevice = RFDevice(self.gpiopin) #default gpio pin rfdevice.enable_tx() if (i == '2'): flag = rfdevice.tx_code( self.radioCode1, 1, 170) #Calibrated radio signals for 433Mhz chip #tutorial: if (flag == True): if (self.status_s1 == 'off'): self.status_s1 = 'on' else: self.status_s1 = 'off' if (i == '3'): flag = rfdevice.tx_code(self.radioCode2, 1, 170) if (flag == True): if (self.status_s2 == 'off'): self.status_s2 = 'on' else: self.status_s2 = 'off' rfdevice.cleanup() t_end = time.time() logging.info('RadioTx duration:{} secs'.format((t_end - t_start))) time.sleep(2) return flag
def send_key(self, remote_name, key): rfdevice = RFDevice(self.gpio) rfdevice.enable_tx() code = self.remote_definitions[remote_name][key] rfdevice.tx_code(int(code), self.protocol, self.pulselength) rfdevice.cleanup() return
def rf4_off(n_clicks): if (n_clicks): rfdevice = RFDevice(17) rfdevice.enable_tx() rfdevice.tx_code(code=5266700, tx_pulselength=184) rfdevice.cleanup() #subprocess.check_output("/var/www/rfoutlet/codesend 5266700 -l 184 -p 0", shell=True) return
def send_decimal(code): logger.debug(f"'send_decimal' called. Sending code {code} using rpi_rf") try: rf_device = RFDevice(GPIO_PIN) rf_device.enable_tx() rf_device.tx_repeat = 20 rf_device.tx_code(code, tx_pulselength=500) except: logger.exception("Error while sending code to socket using rpi_rf") finally: rf_device.cleanup()
def send_code(socketnr, code): logger.debug("'send_code' called. Sending code %s to socket %d using rpi_rf", code, socketnr) try: rf_device = RFDevice(GPIO_PIN) rf_device.enable_tx() rf_device.tx_repeat = 20 rf_device.tx_code(CODES[socketnr][code], tx_pulselength=500) except: logger.exception("Error while sending code to socket using rpi_rf") finally: rf_device.cleanup()
def send(rfsocket_num, sig): rfd = RFDevice(_pin) rfd.enable_tx() rfd.tx_repeat = 10 if rfsocket_num in _codes: rfsocket_codes = _codes[rfsocket_num] if sig in rfsocket_codes: rfd.tx_code(rfsocket_codes[sig]) rfd.cleanup()
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))
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 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))
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 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)))
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(): 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))