def main(): configureLogger("WSO2IOT_RPiStats") UtilsThread() SubscribeToMQTTQueue( ) # connects and subscribes to an MQTT Queue that receives MQTT commands from the server # Startup the fauxmo server fauxmo.DEBUG = True p = fauxmo.poller() u = fauxmo.upnp_broadcast_responder() u.init_socket() p.add(u) # Register the device callback as a fauxmo handler d = device_handler() for x in d.TRIGGERS: trig, port = x.items()[0] fauxmo.fauxmo(trig, u, p, None, port, d) # Loop and poll for incoming Echo requests logging.debug("Entering fauxmo polling loop") while True: try: # Allow time for a ctrl-c to stop the process p.poll(100) time.sleep(0.1) except Exception, e: logging.critical("Critical exception: " + str(e)) break
def __init__(self, group=None, target=None, name=None, args=(), kwargs=None): threading.Thread.__init__(self, group=group, target=target, name="Alexa") self.shutdown_flag = threading.Event() self.args = args self.kwargs = kwargs if kwargs["log"] != None: self.log = kwargs["log"] if kwargs["shutter"] != None: self.shutter = kwargs["shutter"] if kwargs["config"] != None: self.config = kwargs["config"] # Startup the fauxmo server self.poller = fauxmo.poller(log = self.log) self.upnp_responder = fauxmo.upnp_broadcast_responder(log = self.log) self.upnp_responder.init_socket() self.poller.add(self.upnp_responder) # Register the device callback as a fauxmo handler dbh = device_handler(log=self.log, shutter=self.shutter, config=self.config) for shutter, shutterId in sorted(self.config.ShuttersByName.items(), key=lambda kv: kv[1]): portId = 50000 + (abs(int(shutterId,16)) % 10000) self.LogInfo ("Remote address in dec: " + str(int(shutterId,16)) + ", WeMo port will be n°" + str(portId)) fauxmo.fauxmo(shutter, self.upnp_responder, self.poller, None, portId, dbh, log=self.log) return
def fauxmoControl(): global motorHandler skylux_faux = ['Skylight', motorHandler] p = fauxmo.poller() u = fauxmo.upnp_broadcast_responder() u.init_socket() p.add(u) switch = fauxmo.fauxmo(skylux_faux[0], u, p, None, None, action_handler=skylux_faux[1]) print("Fauxmo control running...") while True: try: p.poll() except Exception as e: fauxmo.dbg(e) break yield () print("Fauxmo control failed due to exception.")
def __init__(self, group=None, target=None, name=None, args=(), kwargs=None): threading.Thread.__init__(self, group=group, target=target, name="Alexa") self.shutdown_flag = threading.Event() self.args = args self.kwargs = kwargs if kwargs["log"] != None: self.log = kwargs["log"] if kwargs["shutter"] != None: self.shutter = kwargs["shutter"] if kwargs["config"] != None: self.config = kwargs["config"] # Startup the fauxmo server self.poller = fauxmo.poller(log=self.log) self.upnp_responder = fauxmo.upnp_broadcast_responder(log=self.log) self.upnp_responder.init_socket() self.poller.add(self.upnp_responder) # Register the device callback as a fauxmo handler dbh = device_handler(log=self.log, shutter=self.shutter, config=self.config) for shutter, shutterId in sorted(self.config.ShuttersByName.items(), key=lambda kv: kv[1]): portId = 50000 + (abs(int(shutterId, 16)) % 10000) self.LogInfo("Remote address in dec: " + str(int(shutterId, 16)) + ", WeMo port will be n°" + str(portId)) fauxmo.fauxmo(shutter, self.upnp_responder, self.poller, None, portId, dbh, log=self.log) return
def __init__(self, eventQueue): logger.info("Starting") self.eventQueue = eventQueue # Startup the fauxmo server fauxmo.DEBUG = True self.p = fauxmo.poller() self.u = fauxmo.upnp_broadcast_responder() self.u.init_socket() self.p.add(self.u) # Register the device callback as a fauxmo handler self.d = device_handler( self.eventQueue ) for trig, port in TRIGGERS.items(): fauxmo.fauxmo(trig, self.u, self.p, None, port, self.d) t=threading.Thread( target=self.main ) t.daemon = True t.start()
def main(): # Startup the fauxmo server fauxmo.DEBUG = True p = fauxmo.poller() u = fauxmo.upnp_broadcast_responder() u.init_socket() p.add(u) # Register the device callback as a fauxmo handler d = device_handler() for trig, port in d.TRIGGERS.items(): fauxmo.fauxmo(trig, u, p, None, port, d) # Loop and poll for incoming Echo requests logging.debug("Entering fauxmo polling loop") while True: try: # Allow time for a ctrl-c to stop the process p.poll(100) time.sleep(0.1) except Exception, e: logging.critical("Critical exception: " + str(e)) break
class device_handler(debounce_handler): """Publishes the on/off state requested, and the IP address of the Echo making the request. """ TRIGGERS = {"server": 52000, "raspberry": 52001} def act(self, client_address, state, name): print("State", state, "on ", name, "from client @", client_address) if name == "server": if state == True: os.system( "sshpass -pjoseph2268 ssh -o StrictHostKeyChecking=no [email protected] \"reboot\"" ) print("joseph is genious", state) elif state == False: os.system( "sshpass -pjoseph2268 ssh -o StrictHostKeyChecking=no [email protected] \"poweroff\"" ) print("joseph is genious", state) else: print("what state?", state) elif name == "raspberry": if state == True: os.system("sleep 1;sudo reboot") print("joseph is genious", state) else: print("joseph is genious", state) else: print("Device not found!") return True G = True p = fauxmo.poller() u = fauxmo.upnp_broadcast_responder() u.init_socket() p.add(u)
TiVo_IP_Address = "192.168.0.47" print 'port:', port, " state:", state if state == True: print "" else: print "" def act(self, client_address, state, name): print "State", state, "on", name, "from client @", client_address, "gpio port:",gpio_ports[str(name)] self.trigger(gpio_ports[str(name)],state) return True if __name__ == "__main__": # Startup the fauxmo server fauxmo.DEBUG = True p = fauxmo.poller() u = fauxmo.upnp_broadcast_responder() u.init_socket() p.add(u) # Register the device callback as a fauxmo handler d = device_handler() for trig, port in d.TRIGGERS.items(): fauxmo.fauxmo(trig, u, p, None, port, d) # Loop and poll for incoming Echo requests logging.debug("Entering fauxmo polling loop") print " " while True: try: # Allow time for a ctrl-c to stop the process
elif client_address == ECHO_KITCHEN: self.mqtt.publish("kitchen", state) print "Published to kitchen" return True if __name__ == "__main__": # Startup the MQTT client in a separate thread client = mqtt.Client() client.connect(MQTT_HOST, MQTT_PORT, 60) ct = threading.Thread(target=client.loop_forever) ct.daemon = True ct.start() # Startup the fauxmo server fauxmo.DEBUG = True p = fauxmo.poller() u = fauxmo.upnp_broadcast_responder() u.init_socket() p.add(u) # Register each device callback as a fauxmo handler h = light_handler(client) for trig, port in h.TRIGGERS.items(): fauxmo.fauxmo(trig, u, p, None, port, h) # Loop and poll for incoming Echo requests logging.debug("Entering fauxmo polling loop") while True: try: # Allow time for a ctrl-c to stop the process p.poll(100)
def getLogHandler(): #!/usr/bin/env python ######################### # # Python script using Amazon Alexa or Echo to control Raspberry Pi using an older version # fauxmo. It only supports one device and two commands. # # To control a device say: # # Alexa, turn <device> <command> # # The scripts here are based on this Instructable # https://www.instructables.com/id/Control-Raspberry-Pi-GPIO-Using-Amazon-Echo-Fauxmo/ # # The script can be run on the command or as a systemd servioce: # To run the script from the command line use: # # $ python rpi-echo.py # # Once the script is running, say to Amazon Alexa: Alexa, discover devices # # $ ps aux | grep rpi-echo # # should show two entries for rpi-echo, one is the command above and the other is the script # # Wait for dsicovery to complete # # If a mistake is made, then delete discovered devices from Alexa app on smartphone # # MAKE THE CHANGES IS INDICATED IN THE CODE BELOW # # Nothing else needs to be added to this script or any of the others # # be sure to rm *.pyc if any changes are made # ######################### ######################### # the following lines must go here, otherwise fauxmo does not initialize properly import mylog global Log Log = mylog.mylog('/home/pi', 'rpi-echo.log') mylog.setLogObject(Log) import fauxmo import time import datetime import subprocess # set to True when debugging, otherwise set to False Log.setDebug(False) # Starting port, which should be greater than 1024. Each command requires a unique port # The starting port doesn't need to be changed startingPort = 5070 # THE BELOW ITEMS SHOULD BE THE ONLY CHANGES REQUIRED # Enter your device name for Alex/Echo device = ['security'] # These are the actions to be taken when the echo command is received # # The number of actions must equal the number of commands # # An action is any command that can be executed from the command line # example actions: # sudo shutdown -h 0 # sudo reboot # python script.py actions = ['python /usr/local/bin/sleep.py', 'python /usr/local/bin/disarm.py'] # THE ABOVE ITEMS SHOULD BE THE ONLY CHANGES REQUIRED # I modified these lines in fauxmo.py, which hard codes ON and OFF. # The commented lines are the originals. # # success = self.action_handler.on(client_address[0], self.name) # success = self.action_handler.on(client_address[0], 'ON') # # # success = self.action_handler.off(client_address[0], self.name) # success = self.action_handler.off(client_address[0], 'OFF') # # If the commands are changed, then you must change fuaxmo.py commands = ['ON', 'OFF'] ######################### def getLogHandler(): return Log class debounce_handler(object): # prevent multiple Echos from responding to one voice command DEBOUNCE_SECONDS = 0.3 def __init__(self): self.lastEcho = time.time() def on(self, client_address, name): if self.debounce(): return True return self.act(client_address, True, name) def off(self, client_address, name): if self.debounce(): return True return self.act(client_address, False, name) def act(self, client_address, state): pass def debounce(self): if (time.time() - self.lastEcho) < self.DEBOUNCE_SECONDS: return True self.lastEcho = time.time() return False class device_handler(debounce_handler): def trigger(self, port, state): Log.printMsg('trigger: port: ' + str(port) ) def act(self, client_address, state, name): global commands global actions notFound = True try: i = 0 for cmd in commands: if name == cmd: Log.printMsg("action: " + name + " from Echo " + str(client_address)) subprocess.call(actions[i], shell=True) notFound = False i = i + 1 except: Log.printMsg("rpi-echo: device_handler: act: try failed: " + name) if notFound: Log.printMsg("unhandled command received: " + name) return True if __name__ == "__main__": Log.printMsg("*** STARTING WEMO SERVER ***") # setup parameters for fauxmo # Plug-and-Play Listener l = fauxmo.upnp_broadcast_responder() l.init_socket() # Poller p = fauxmo.poller() p.add(l) # Register the device callback for handler d = device_handler() # Name the device # fauxmo.fauxmo corresponds to fauxmo.py: fauxmo: __init__ port = startingPort for dev in device: fauxmo.fauxmo(dev, l, p, None, port, d) port = port + 1 # Loop forever waiting for incoming Echo requests Log.printMsg("Entering WeMo polling loop") try: while True: # Allow time for a ctrl-c to stop the process p.poll(100) time.sleep(0.1) except Exception, e: Log.printMsg("ERROR: critical exception occurred: " + str(e)) except KeyboardInterrupt: # trap a CTRL+C keyboard interrupt Log.printMsg("keyboard exception occurred")