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 RF_on(set_dic, switch_log): script = 'RF_on.py' msg = ("") msg += (" #############################################\n") msg += (" ## Turning the RF - ON ##\n") from rpi_rf import RFDevice if 'gpio_RF' in set_dic: if not str(set_dic['gpio_RF']).strip() == '': gpio_pin = int(set_dic['gpio_RF']) else: print(" - RF gpio pin not set") else: msg += (" !! NO RF SET !!\n") msg += (" !! run config program or edit config.txt !!\n") msg += (" !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n") pigrow_defs.write_log(script, 'Failed - due to none set in config', switch_log) return msg rfdevice = RFDevice(gpio_pin) rfdevice.enable_tx() rfdevice.tx_code(15465751, 1, 432) rfdevice.tx_repeat = 5 msg += (" ## using GPIO " + str(gpio_pin) + " ##\n") msg += (" #############################################\n") pigrow_defs.set_condition(condition_name="RF", trig_direction="on", cooldown="none") pigrow_defs.write_log(script, 'RF turned on', switch_log) return msg
class RF_Sender: 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 send(self, code, protocol, length): self._rfdevice.tx_code(code, protocol, length) print("TX Pin: {}, Code: {}, Protocol: {}, Length: {}".format( self._pin, code, protocol, length)) def set_on(self, pin): self.send(code[pin]['On'], protocol, length) def set_off(self, pin): self.send(code[pin]['Off'], protocol, length) def cleanup(self): self._rfdevice.cleanup()
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 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 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))
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()
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
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 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 sendSignal(code, protocol, pulselength): rfdevice = RFDevice(args.gpio) rfdevice.enable_tx() logging.info( str(code) + " [protocol: " + str(protocol) + ", pulselength: " + str(pulselength) + "]") rfdevice.tx_code(int(code), int(protocol), int(pulselength)) rfdevice.cleanup() time.sleep(1)
def sendcode(code): rfdevice = RFDevice(17) rfdevice.enable_tx() protocol = 1 pulselength = 350 rfdevice.tx_code(code, protocol, pulselength) rfdevice.cleanup() return
def Sockets(): global Temp Radio = RFDevice(17) Radio.enable_tx() while True: if Temp < Target: Radio.tx_code(5330227,1,189) elif Temp > Target: Radio.tx_code(5330236,1,189) time.sleep(3)
def off(self): logging.basicConfig( level=logging.INFO, datefmt='%Y-%m-%d %H:%M:%S', format='%(asctime)-15s - [%(levelname)s] %(module)s: %(message)s', ) rfdevice = RFDevice(int(self.pin)) rfdevice.enable_tx() rfdevice.tx_code(int(self.code_off), None, None) rfdevice.cleanup()
class transmitter: 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 run(self): self.running = True logging.debug("Transmitter ready") self.consume() def stop(self): self.running = False self.rfdevice.cleanup() def consume(self): while self.running: message = self.queue.get() if self.running: code, repeat = self.code(message.split()) if code: for i in range(repeat): self.rfdevice.tx_code(code, self.protocol, self.pulse) logging.debug("Transmitting '" + str(code) + "'") sleep(0.01) else: logging.warning("Unrecognized message '" + message + "'") def code(self, message: List[str]): return self.code_for_message(message, self.messages) def code_for_message(self, message: List[str], mapping): code = 0 repeat = 0 if len(message) > 1: return self.code_for_message(message[1:], mapping.get(message[0], {})) else: item = mapping.get(message[0]) if isinstance(item, dict): code = item.get("code") repeat = item.get("repeat", 1) elif isinstance(item, int) or (isinstance(item, str) and item.isdigit()): code = int(item) repeat = 1 elif isinstance(message[0], int) or message[0].isdigit(): code = int(message[0]) repeat = 1 return code, repeat
def Sockets(): global Temp global Target Radio = RFDevice(17) Radio.enable_tx() while True: if Temp < Target-1: Radio.tx_code(5332227,1,189) elif Temp > Target+1: Radio.tx_code(5332236,1,189) time.sleep(60)
class RFSender(object): def __init__(self, pin): self.pin = pin self.device = RFDevice(pin) self.device.enable_tx() def __del__(self): self.device.cleanup() def transmit(self, signal): # print("Transmitting code: ", signal.code, signal.protocol, signal.pulselength) self.device.tx_code(signal.code, signal.protocol, signal.pulselength)
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 rf5_off(n_clicks): if (n_clicks): rfdevice = RFDevice(17) GPIO.setmode(GPIO.BCM) rfdevice.enable_tx() rfdevice.tx_code(code=5272844, tx_proto=1, tx_pulselength=184, tx_length=24) rfdevice.cleanup() #subprocess.check_output("/var/www/rfoutlet/codesend 5272844 -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()
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 control_light(code): rfdevice = RFDevice(17) rfdevice.enable_tx() protocol = 1 pulselength = 380 logging.info("code: {0}".format(code) + " [protocol: " + str(protocol) + ", pulselength: " + str(pulselength) + "]") rfdevice.tx_code(codes[code], protocol, pulselength) rfdevice.cleanup()
def off(): rfdevice = RFDevice(17) rfdevice.tx_repeat = 1 rfdevice.enable_tx() 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() print(datetime.datetime.now().strftime("%H:%M:%S"), "Electric heater turned off.") logging.info("%s Electric heater turned off.", datetime.datetime.now().strftime("%H:%M:%S"))
def on(): rfdevice = RFDevice(17) rfdevice.tx_repeat = 1 rfdevice.enable_tx() rfdevice.tx_code(137276512, 3, 83) rfdevice.tx_code(17061062, 1, 190) rfdevice.tx_code(17061272, 3, 83) rfdevice.tx_code(4265267, 1, 190) rfdevice.cleanup() print(datetime.datetime.now().strftime("%H:%M:%S"), "Electric heater turned on.") logging.info("%s Electric heater turned on.", datetime.datetime.now().strftime("%H:%M:%S"))
def transmit_code(code): """tx RF code""" # 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(code) rfdevice.cleanup()
class Transmitter: def __init__(self, config): self.config = config self.rfdevice = RFDevice(config["gpio"]) self.rfdevice.tx_repeat = config["repeat"] def start(self, ): self.rfdevice.enable_tx() def send(self, code, pulse_length): self.rfdevice.tx_code(code, None, pulse_length, self.config["length"]) def stop(self): self.rfdevice.cleanup()
def rf5_off(n_clicks): if (n_clicks): if(rpi_rf_433): rfdevice = RFDevice(17) GPIO.setmode(GPIO.BCM) rfdevice.enable_tx() rfdevice.tx_code(code=5272844, 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 5272844 -l 184 -p 0", shell=True) subprocess.check_output("/var/www/433Utils/RPi_utils/codesend 5272844 0 188", shell=True) time.sleep(5) return
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()
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()