예제 #1
0
class WemoSampler:
    def __init__(self):
        self.wemo_env = Environment()
        self.wemo_env.start()
        # TODO: run discovery periodically instead of just on startup to
        # discover new devices that have been enabled?
        self.discover()

    def discover(self):
        logging.info("searching for WeMo devices")
        self.wemo_env.discover(seconds=1)
        logging.info("WeMo devices found: {0}".format(self.wemo_env.devices))

    def get_switch(self, switch_name):
        return self.wemo_env.get_switch(switch_name)

    def get_sample(self, key, arg):
        if key == "power":
            if not arg:
                raise ValueError("wemo.power requires arg (switch name)")
            switch = self.get_switch(arg)
            # current_power seems to be in mW, convert to W
            return switch.current_power / 1000.0
        elif key == "state":
            if not arg:
                raise ValueError("wemo.state requires arg (switch name)")
            switch = self.get_switch(arg)
            return switch.get_state()
        else:
            raise ValueError("unknown key: {0}".format(key))
예제 #2
0
파일: wemo_env.py 프로젝트: fjacob21/MAX
class wemo_env(object):

    def __init__(self):
        self._watcheux = {}
        self._env = Environment()
        try:
            self._env.start()
            self._env.discover(3)
        except:
            print("WeMo environment cannot start ;( !!!!")

    def start_watching(self):
        statechange.connect(self.update_state,
                        unique=False,
                        dispatch_uid=id(self))

    def get_device(self, name):
        return self._env.get(name)

    def register(self, name, fct):
        if name not in self._watcheux:
            self._watcheux[name] = []
        self._watcheux[name].append(fct)
        if len(self._watcheux) > 0:
            self.start_watching()

    def update_state(self, sender, **kwargs):
        state = kwargs.get('state')
        if state != 0:
            state = 1
        if sender.name in self._watcheux:
            for watcheu in self._watcheux[sender.name]:
                watcheu(state)
예제 #3
0
    def initialize(self):
        LOGGER.debug("Initializing WeMo Environment")

        self.env = Environment(self.on_switch, self.on_motion)
        self.env.start()
        self.env.discover(seconds=5)

        self.load_data_files(dirname(__file__))
        prefixes = ['toggle', 'tockle', 'taco']
        self.__register_prefixed_regex(prefixes, "(?P<ToggleWords>.*)")

        listprefixes = ['list wemo', 'identify wemo', 'get wemo']
        self.__register_prefixed_regex(listprefixes, "(?P<ListWords>.*)")

        # switch intent
        intent = IntentBuilder("WemoSwitchIntent").require(
            "WemoSwitchKeyword").require("ToggleWords").build()
        self.register_intent(intent, self.handle_wemo_switch_intent)

        # discover intent
        intent = IntentBuilder("WemoDiscoverIntent").require(
            "WemoDiscoverKeyword").build()
        self.register_intent(intent, self.handle_wemo_discover_intent)

        # list switches intent
        intent = IntentBuilder("WemoListIntent").require(
            "WemoListKeyword").require("ListWords").build()
        self.register_intent(intent, self.handle_wemo_list_intent)
예제 #4
0
    def __init__(self, discovery_seconds=3):
        super().__init__()

        self.discovery_seconds = discovery_seconds
        self.env = Environment()
        self.env.start()
        self.refresh_devices()
 def __init__(self, config=None, name_set=set(), data_queue=queue.Queue()):
     threading.Thread.__init__(self)
     self._name_set = METERS_NAME_SET
     self._config = config['switch_set_maintainer']
     self._config_querier = config['switch_querier']
     self._data_queue = data_queue
     self._env = Environment()
예제 #6
0
    def __init__(self, num_devices=1, debug=True):
        self.debug = debug
        print "initalizing the wemos for %s devices" % (num_devices)
        self.NUM_DEVICES = num_devices
        self.switches = {}
        self.devices = range(0, self.NUM_DEVICES)
        self.q = Queue()

        try:
            self.env = Environment()
            self.env.start()
        except:
            print """
                Failed to access internet information. 
                Are you connected to the router wifi?"""
            sys.exit(1)

        self.load_switches()

        if len(self.switches) == 0:
            print "could not connect any devices. are you on the router wifi?"
            sys.exit(1)

        print """
                Done connecting devices.  
                Starting asynchronous wemo reloader now!"""

        self.thread = Thread(target=self.reload_switch_spinner)
        self.thread.start()
예제 #7
0
class WemoSwitch(DeviceLifetimeCycles):
    def __init__(self, root_logger: RootLogger) -> None:
        self.__root_logger = root_logger
        self.__env = None

    def connect(self) -> None:
        try:
            self.__env = Environment()
            self.__env.start()
            self.__env.discover(seconds=5)
        except Exception as e:
            message = 'Got error while init WemoSwitch: {0} '.format(str(e))
            self.__root_logger.error(message)
            raise Exception(message)

    def disconnect(self) -> None:
        pass

    def change_state(self, actuator_name: str, state: bool) -> bool:
        try:
            switch = self.__env.get_switch(actuator_name)
            if (state):
                switch.on()
            else:
                switch.off()
        except UnknownDevice:
            self.__root_logger.error(
                'Wemo device with name; {0} not found'.format(actuator_name))
            return False

        return True
예제 #8
0
 def __init__(self, discover_time=1):
     self.env = Environment()
     self.env.start()
     self.env.discover(discover_time)
     device_list = self.env.list_switches()
     self.devices = []
     for name in device_list:
         self.devices.append(name)
예제 #9
0
 def connect(self) -> None:
     try:
         self.__env = Environment()
         self.__env.start()
         self.__env.discover(seconds=5)
     except Exception as e:
         message = 'Got error while init WemoSwitch: {0} '.format(str(e))
         self.__root_logger.error(message)
         raise Exception(message)
예제 #10
0
    def handle_wemo_discover_intent(self, message):
        try:
            self.env = Environment(self.on_switch, self.on_motion)
            self.env.start()
            self.env.discover(seconds=5)

        except:
            LOGGER.debug("Error occurred discovering Wemo devices")
            self.speak("ahr. ah.")
예제 #11
0
파일: wemo.py 프로젝트: rudimk/kasa
def main():
    '''
    Server routine
    '''
    port = "9801"
    context = zmq.Context.instance()

    # Receive input from the outside world
    socket = context.socket(zmq.DEALER)
    # Specify unique identity
    socket.setsockopt(zmq.IDENTITY, b"WeMo")
    socket.connect("tcp://127.0.0.1:%s" % port)

    print "Ready to receive"

    # Where we will store references to the worker threads
    worker_sockets = {}

    # Start the ouimeaux environment for discovery
    env = Environment(with_subscribers = False, with_discovery=True, with_cache=False)
    env.start()
    discovered.connect(discovered_wemo)

    # Run the polling mechanism in the background
    BackgroundDiscovery(env).start()

    while True:
        # Get the outside message in several parts
        # Store the client_addr
        client_addr, _, msg = socket.recv_multipart()
        print "Received request {} from '{}'".format(msg, client_addr)
        msg = msg.split(' ')

        command = msg[0]

        # General commands
        if command == 'list':
            # Send the current set of devices (only switches supported)
            socket.send_multipart([client_addr, b'', ",".join(env.list_switches())])
            continue

        # Commands on objects
        switch_name = msg[1]
        print switch_name
        s = env.get_switch(switch_name)

        if command == 'on':
            s.on()
            socket.send_multipart([client_addr, b'', 'OK'])
        elif command == 'off':
            s.off()
            socket.send_multipart([client_addr, b'', 'OK'])
        elif command == 'state':
            st = s.get_state()
            st = 'on' if st else 'off'
            socket.send_multipart([client_addr, b'', st])
예제 #12
0
 def connect(self):
     self._env = Environment(self._on_switch, self._on_motion)
     try:
         self._env.start()
     except TypeError:
         print "Start error"
     try:
         self._env.discover(seconds=3)
     except TypeError:
         print "Discovery error"
예제 #13
0
    def __init__(self):
        print "Setting up devices for control"
        #do the config stuff here
        self.taskConfig = parse("/var/www/html/tasks.xml")
        self.allTasks = self.taskConfig.getElementsByTagName('task')
        self.switches = []
        self.motions = []

        self.env = Environment(self.on_switch, self.on_motion)
        self.env.start()
        self.env.discover()
예제 #14
0
class WemoControl:
    def __init__(self, wemoConfig):
        self.wemoConfig = wemoConfig

    def process(self):
        try:
            self.env = Environment(bridge_callback=self.on_bridge, with_subscribers=False)
            self.env.start()
            self.env.discover(10)
        except Exception, e:
            log.exception("Failed to start environment.")
예제 #15
0
 def __init__(self, callback):
     self.callback = callback
     self.motion = False
     self.env = Environment(with_cache=False)
     self.event = None
     receiver(statechange)(self.state)
     self.mappings = {
         "zone1": Zone(0, callback),
         "zone2": Zone(1, callback),
         "zone3": Zone(2, callback),
         "zone4": Zone(3, callback)
     }
예제 #16
0
def mainloop(names, pubsub_client, times=0, delay=10):
    env = Environment(with_cache=False)
    env.start()
    env.discover(5)

    if times < 1:
        while True:
            do(env,names,pubsub_client)
            time.sleep(delay)
    else:
        for i in range(0, times):
            do(env,names,pubsub_client)
            time.sleep(delay)
예제 #17
0
class WemoClient():
    def __init__(self):
        self.env = Environment(_on_switch, _on_motion)
        self.env.start()
        self.env.discover(4)

    def toggle(self):
        _switch_map.values()[0].toggle()

    def switch_on(self):
        _switch_map.values()[0].on()

    def switch_off(self):
        _switch_map.values()[0].off()
예제 #18
0
def initialize(bind=None, auth=None):
    global ENV
    if ENV is None:
        ENV = Environment(bind=bind)
        ENV.start()
        gevent.spawn(ENV.discover, 10)
    if auth is not None:
        elems = auth.split(':', 1)
        username = elems[0]
        password = elems[1]
        print("Protected server with basic auth username/password: ", username, password)
        app.config['BASIC_AUTH_USERNAME'] = username
        app.config['BASIC_AUTH_PASSWORD'] = password
        app.config['BASIC_AUTH_FORCE'] = True
        basic_auth = BasicAuth(app)
예제 #19
0
파일: wemo.py 프로젝트: maxvitek/footman
    def __init__(self):
        IPlugin.__init__(self)
        self.command_priority = 1
        self.voice = None
        bind_port = 54321  # number
        host = get_ip_addresses()[0]  # we just grab the first one that isn't local
        while bind_port < 54329:
            bind = '{0}:{1}'.format(host, str(bind_port))
            try:
                self.env = Environment(bind=bind, with_subscribers=False)
                self.env.start()
                break
            except:
                bind_port += 1

        # retrieve or create device cache
        self.devices = mc.get('footman_wemo_cache')
        if not self.devices:
            self.env.discover(5)
            self.devices = self.env.list_switches()
            mc.set('footman_wemo_cache', self.devices)
        self.log = logging.getLogger(__name__)

        self.commands = {
            '.*turn (?P<command>on|off).*(?P<device>' + '|'.join([d.lower() for d in self.devices]) + ').*': [
                {
                    'command': self.command,
                    'args': (None, None,),
                    'kwargs': {},
                    'command_priority': 0,
                }
            ]
        }
예제 #20
0
 def process(self):
     try:
         self.env = Environment(bridge_callback=self.on_bridge, with_subscribers=False)
         self.env.start()
         self.env.discover(10)
     except Exception, e:
         log.exception("Failed to start environment.")
예제 #21
0
def wemo_main():
    print "Start WEMO Daemon."

    print "Set Environment."
    #キャッシュを参照しようとすると動作が激重orストップするので参照しない
    wemo = Environment(with_cache=False)
    print "Finished init Environment."

    print "Starting WEMO module."
    wemo.start()
    print "Finished."

    print "Discovering..."
    wemo.discover(5)
    print "Finished discovering."

    print "Get Switch Instances."
    east = wemo.get_switch("Lab East")
    west = wemo.get_switch("Lab West")
    heater = wemo.get_switch("Lab Heater")
    print "Finished."

    print "Set GPIO pins."
    open("/sys/class/gpio/export", "w").write(str(44))
    open("/sys/class/gpio/export", "w").write(str(19))
    open("/sys/class/gpio/export", "w").write(str(110))

    print "All init is finished."

    print "Start Loop."
    while True:
        if int(open("/sys/class/gpio/gpio44/value", "r").read().split("\n")[0]) == 0:
            #左ボタンが押された時の処理
            print "east toggle"
            east.toggle()
            print "waiting..."
            #チャタリングと長押し対策
            time.sleep(0.5)
            continue
        if int(open("/sys/class/gpio/gpio19/value", "r").read().split("\n")[0]) == 0:
            #中央ボタンが押された時の処理
            print "west toggle"
            west.toggle()
            print "waiting..."
            #チャタリングと長押し対策
            time.sleep(0.5)
            continue
        if int(open("/sys/class/gpio/gpio110/value", "r").read().split("\n")[0]) == 0:
            #右ボタンが押された時の処理
            print "heater toggle"
            heater.toggle()
            print "waiting..."
            #チャタリングと長押し対策
            time.sleep(0.5)
            continue
        print "nothing loop"
        time.sleep(0.2)
예제 #22
0
파일: wemo_env.py 프로젝트: fjacob21/MAX
 def __init__(self):
     self._watcheux = {}
     self._env = Environment()
     try:
         self._env.start()
         self._env.discover(3)
     except:
         print("WeMo environment cannot start ;( !!!!")
예제 #23
0
    def __init__(self, name, callback_function, queue, threadlist):
        HomeAutomationQueueThread.__init__(self, name, callback_function, queue, threadlist)

        self.env = Environment()
        self.lights = {}
        self.relevant_light_attrs = ('name', 'on', 'saturation', 'hue', 'brightness')
        self.cache = []
        self.lock = threading.Lock()
예제 #24
0
class wemo_accessor:
    def __init__(self):
        # Init the enviroment.
        self.env = Environment()
        self.env.start()
        self.env.discover(seconds=2)
        self.sleep_time = 2

    def schedule_switch(self, switch_name, schedule):
        """
    switch_name: String
    schedule: numpy array
    """
        switch = self.env.get_switch(switch_name)
        # Schedule
        does_reset = False
        current_hour = 0
        while (not does_reset):
            # current_hour = datetime.datetime.now().second
            if schedule[current_hour % 24] == 1:
                switch.on()
            else:
                switch.off()
            does_reset = ((current_hour % 24) == 23)
            print(current_hour, schedule[current_hour % 24])
            time.sleep(self.sleep_time)
            current_hour += 1
        switch.off()

    def schedule_policies(self, policies):
        """
    policies: Dictionary
    """
        print(policies)
        daemon_threads = []
        for switch, schedule in policies.items():
            thread = td.Thread(target=self.schedule_switch,
                               args=(
                                   switch,
                                   schedule,
                               ))
            daemon_threads.append(thread)

        for thread in daemon_threads:
            thread.start()
예제 #25
0
def control(command):
    env = Environment()
    env.start()
    env.discover()
    wemo = env.list_switches()
    print(wemo)
    wemo_switch = env.get_switch(wemo[0])
    if command == 'on':
        wemo_switch.on()
    if command == 'off':
        wemo_switch.off()
예제 #26
0
def wemo_off():
    env = Environment(on_switch)
    env.start()
    env.discover(seconds=1)
    desk = env.get_switch('Wemo Mini')
    power_off = desk.off()

    return power_off
예제 #27
0
파일: wemo3.py 프로젝트: leac-mit/green_net
def get_device(name):
    env = Environment()
    # TODO: run from 10am to 10pm
    env.start()
    print "Discovering Device %s" %name
    env.discover(8)
    this_switch = env.get(name)
    return this_switch
예제 #28
0
파일: wemo.py 프로젝트: leac-mit/green_net
def get_device(name):
    env = Environment()
    # TODO: run from 10am to 10pm
    env.start()
    print "Discovering Device"
    env.discover(5)
    h = env.get(name)
    return h
예제 #29
0
파일: wemo.py 프로젝트: pierreca/Tyler
    def connect(self):
	self._env = Environment(self._on_switch, self._on_motion)
	try:
	    self._env.start()
	except TypeError:
	    print "Start error"
	try:
	    self._env.discover(seconds=3)
	except TypeError:
	    print "Discovery error"
예제 #30
0
 def startStopWemoEnvironment(self, startstop):
     if startstop == "start":
         try:
             try:
                 self.wemoenvironment = Environment()
             except AttributeError:
                 self.wemoenvironment = Environment() #Create the variable if we destroyed it elsewhere
             self.wemoenvironment.start()
             self.wemoenvironment.discover(self.config.get("Seconds For Environment Discovery"))
         except Exception as e:
             logging.exception("Failed to initialize new wemo environment! " + str(e.message))
             raise
     if startstop == "stop":
         try:
             self.wemoenvironment.upnp.server.stop()
             self.wemoenvironment.registry.server.stop()
             del self.wemoenvironment
         except Exception as e:
             logging.exception("Failed to stop and delete wemo environment! " + str(e.message))
예제 #31
0
 def __init__(self, callback):
     self.callback = callback
     self.motion = False
     self.env = Environment(with_cache=False)
     self.event = None
     receiver(statechange)(self.state)
     self.mappings = {
         "zone1": Zone(0, callback),
         "zone2": Zone(1, callback),
         "zone3": Zone(2, callback),
         "zone4": Zone(3, callback)
     }
예제 #32
0
class Controller(object):

    def __init__(self, callback):
        self.callback = callback
        self.motion = False
        self.env = Environment(with_cache=False)
        self.event = None
        receiver(statechange)(self.state)
        self.mappings = {
            "zone1": Zone(0, callback),
            "zone2": Zone(1, callback),
            "zone3": Zone(2, callback),
            "zone4": Zone(3, callback)
        }


    def start(self):
        print "Starting environment"
        self.env.start()
        print "Discover stuff"
        self.env.discover(5)
        print "Wait for stuff"
        Process(target=self.env.wait).start()

    def state(self, sender=None, state=None, **kwargs):
        motion = bool(state)
        print "Got state change {} {}".format(sender.name, motion)
        zone = self.mappings.get(sender.name)

        if zone == None:
            return

        if motion:
            zone.cancel()

        if zone.motion and not motion:
            zone.schedule()

        if not zone.motion and motion:
            zone.trigger(motion)
예제 #33
0
파일: wemo.py 프로젝트: ramrom/haus
def get_switch_state(switch_name):
  env = Environment(on_switch, on_motion)
  env.start()
  env.discover(seconds=1)
  #time.sleep(2)
  switch = env.get_switch(switch_name)
  return switch.basicevent.GetBinaryState()['BinaryState']
예제 #34
0
파일: wemo.py 프로젝트: ramrom/haus
def toggle_switch(switch_name):
  env = Environment(on_switch, on_motion)
  env.start()
  env.discover(seconds=1)
  #time.sleep(2)
  switch = env.get_switch(switch_name)
  switch.blink()
예제 #35
0
파일: wemo.py 프로젝트: yrahul/kasa
def main():
    '''
    Server routine
    '''
    port = "9801"
    context = zmq.Context.instance()

    # Receive input from the outside world
    socket = context.socket(zmq.DEALER)
    # Specify unique identity
    socket.setsockopt(zmq.IDENTITY, b"WeMo")
    socket.connect("tcp://127.0.0.1:%s" % port)

    print "Ready to receive"

    # Where we will store references to the worker threads
    worker_sockets = {}

    # Start the ouimeaux environment for discovery
    env = Environment(with_subscribers=False,
                      with_discovery=True,
                      with_cache=False)
    env.start()
    discovered.connect(discovered_wemo)

    # Run the polling mechanism in the background
    BackgroundDiscovery(env).start()

    while True:
        # Get the outside message in several parts
        # Store the client_addr
        client_addr, _, msg = socket.recv_multipart()
        print "Received request {} from '{}'".format(msg, client_addr)
        msg = msg.split(' ')

        command = msg[0]

        # General commands
        if command == 'list':
            # Send the current set of devices (only switches supported)
            socket.send_multipart(
                [client_addr, b'', ",".join(env.list_switches())])
            continue

        # Commands on objects
        switch_name = msg[1]
        print switch_name
        s = env.get_switch(switch_name)

        if command == 'on':
            s.on()
            socket.send_multipart([client_addr, b'', 'OK'])
        elif command == 'off':
            s.off()
            socket.send_multipart([client_addr, b'', 'OK'])
        elif command == 'state':
            st = s.get_state()
            st = 'on' if st else 'off'
            socket.send_multipart([client_addr, b'', st])
예제 #36
0
class WemoController:
    _env = None

    def _on_switch(self, switch):
        print "Light Switch found: ", switch.name

    def _on_motion(self, motion):
        print "Motion Sensor found: ", motion.name

    def connect(self):
        self._env = Environment(self._on_switch, self._on_motion)
        try:
            self._env.start()
        except TypeError:
            print "Start error"
        try:
            self._env.discover(seconds=3)
        except TypeError:
            print "Discovery error"

    def find_switches(self):
        result = []
        switches = self._env.list_switches()
        print "Found " + str(len(switches))
        print switches
        for s in switches:
            print "Found " + s
            result.append({
                "name": s,
                "state": self._env.get_switch(s).get_state()
            })
        return result

    def switch_on(self, switch_name):
        switch = self._env.get_switch(switch_name)
        switch.on()

    def switch_off(self, switch_name):
        switch = self._env.get_switch(switch_name)
        switch.off()

    def switch_state(self, switch_name):
        switch = self._env.get_switch(switch_name)
        return switch.get_state()
예제 #37
0
def devices():
	try:
		env = Environment()
		env.start()
		env.discover(seconds=3)
		result = env.list_switches()
	
	except:
		raise
	
	return result
예제 #38
0
class Controller(object):
    def __init__(self, callback):
        self.callback = callback
        self.motion = False
        self.env = Environment(with_cache=False)
        self.event = None
        receiver(statechange)(self.state)
        self.mappings = {
            "zone1": Zone(0, callback),
            "zone2": Zone(1, callback),
            "zone3": Zone(2, callback),
            "zone4": Zone(3, callback)
        }

    def start(self):
        print "Starting environment"
        self.env.start()
        print "Discover stuff"
        self.env.discover(5)
        print "Wait for stuff"
        Process(target=self.env.wait).start()

    def state(self, sender=None, state=None, **kwargs):
        motion = bool(state)
        print "Got state change {} {}".format(sender.name, motion)
        zone = self.mappings.get(sender.name)

        if zone == None:
            return

        if motion:
            zone.cancel()

        if zone.motion and not motion:
            zone.schedule()

        if not zone.motion and motion:
            zone.trigger(motion)
예제 #39
0
    def __init__(self):
        IPlugin.__init__(self)
        self.command_priority = 1
        self.voice = None
        bind_port = 54321  # number
        host = get_ip_addresses()[
            0]  # we just grab the first one that isn't local
        while bind_port < 54329:
            bind = '{0}:{1}'.format(host, str(bind_port))
            try:
                self.env = Environment(bind=bind, with_subscribers=False)
                self.env.start()
                break
            except:
                bind_port += 1

        # retrieve or create device cache
        self.devices = mc.get('footman_wemo_cache')
        if not self.devices:
            self.env.discover(5)
            self.devices = self.env.list_switches()
            mc.set('footman_wemo_cache', self.devices)
        self.log = logging.getLogger(__name__)

        self.commands = {
            '.*turn (?P<command>on|off).*(?P<device>' + '|'.join([
                d.lower() for d in self.devices
            ]) + ').*': [{
                'command': self.command,
                'args': (
                    None,
                    None,
                ),
                'kwargs': {},
                'command_priority': 0,
            }]
        }
예제 #40
0
def get_status():
    env = Environment(on_switch)
    env.start()
    env.discover(seconds=1)
    desk = env.get_switch('Wemo Mini')
    state = desk.get_state()
    
    if state == 1:
        state = 'On'        
    elif state == 0:
        state = 'Off'

    return state
예제 #41
0
def init(devname):
	try:
		env = Environment()
		env.start()
		env.discover(seconds=3)
		switch = env.get_switch(devname)

	#except UnknownDevice:
	#	return None, None
	except:
		raise

	return env, switch
예제 #42
0
    def __init__(self, machine_id, machine_desc, plug_id, plug_desc, plug_type,
                 plug_name, machine_power_threshold):
        super(MachinePlug_WemoInsight,
              self).__init__(machine_id, machine_desc, plug_id, plug_desc,
                             plug_type, plug_name, machine_power_threshold)

        ## create the static/global WEMO environment variable if it doesn't exist
        if (MachinePlug_WemoInsight.env == 0):
            MachinePlug_WemoInsight.env = Environment(with_cache=False,
                                                      bind=None)
            MachinePlug_WemoInsight.env.start()
            MachinePlug_WemoInsight.env.discover(3)

        self.wemo_switch = self.getSwitch(plug_name)
        logger.debug("switch = " + str(self.wemo_switch))
예제 #43
0
파일: wemo.py 프로젝트: pierreca/Tyler
class WemoController:
    _env = None

    def _on_switch(self, switch):
	print "Light Switch found: ", switch.name

    def _on_motion(self, motion):
	print "Motion Sensor found: ", motion.name

    def connect(self):
	self._env = Environment(self._on_switch, self._on_motion)
	try:
	    self._env.start()
	except TypeError:
	    print "Start error"
	try:
	    self._env.discover(seconds=3)
	except TypeError:
	    print "Discovery error"

    def find_switches(self):
	result = []
	switches = self._env.list_switches()
	print "Found " + str(len(switches))
	print switches
	for s in switches:
	    print "Found " + s
	    result.append({ "name" : s, "state" : self._env.get_switch(s).get_state() }) 
	return result

    def switch_on(self, switch_name):
	switch = self._env.get_switch(switch_name)
	switch.on()

    def switch_off(self, switch_name):
	switch = self._env.get_switch(switch_name)
	switch.off()

    def switch_state(self, switch_name):
	switch = self._env.get_switch(switch_name)
	return switch.get_state()
예제 #44
0
class WemoService:
    def __init__(self, discover_time=1):
        self.env = Environment()
        self.env.start()
        self.env.discover(discover_time)
        device_list = self.env.list_switches()
        self.devices = []
        for name in device_list:
            self.devices.append(name)

    def get_devices(self):
        return self.devices

    def device(self, name, attempts=0):
        try:
            return WemoDevice(self.env, name)
        except:
            if attempts < 3:
                print(name + ' was not found, trying in 3 seconds')
                sleep(3)
                attempts += 1
                self.device(name, attempts)
            else:
                raise Exception(name + ' could not be found')
예제 #45
0
class SwitchWemoPlugin(SwitchPlugin):
    def __init__(self, discovery_seconds=3):
        super().__init__()

        self.discovery_seconds = discovery_seconds
        self.env = Environment()
        self.env.start()
        self.refresh_devices()

    def refresh_devices(self):
        logging.info('Starting WeMo discovery')
        self.env.discover(seconds=self.discovery_seconds)
        self.devices = self.env.devices

    def _exec(self, method, device, *args, **kwargs):
        if device not in self.devices:
            self.refresh_devices()

        if device not in self.devices:
            raise RuntimeError('Device {} not found'.format(device))

        logging.info('{} -> {}'.format(device, method))
        dev = self.devices[device]
        getattr(dev, method)(*args, **kwargs)

        resp = {'device': device, 'state': dev.get_state()}
        return Response(output=json.dumps(resp))

    def on(self, device):
        return self._exec('on', device)

    def off(self, device):
        return self._exec('off', device)

    def toggle(self, device):
        return self._exec('toggle', device)
예제 #46
0
class Wemo(object):
    state_map = {'on': 1, 'off': 0}
    state_map_wemo = {'1': 'on', '0': 'off'}

    def __init__(self):
        self.env = Environment(with_cache=False)
        self.env.start()
        self.env.discover()
        self.list_switches = self.env.list_switches()
        print self.list_switches

    def get(self, name, use_cache=False):
        '''
        get - returns the state of the given device
        '''

        status = 0
        state = None
        s = self.env.get_switch(name)
        try:
            state = s.basicevent.GetBinaryState()
            if 'BinaryState' in state:
                print 'get info: {}'.format(state)
                state = Wemo.state_map_wemo[state['BinaryState']]
                return status, state

        except Exception as e:
            print 'exception {}'.format(e)
            status = 2

        return status, state

    def set(self, name, val_on_off, use_cache=False):
        '''
        set - turns the wemo switch either on or off. Will
        execute for all the switches in the list
        '''

        status = 0
        s = self.env.get_switch(name)

        print 'state: {}'.format(val_on_off)
        state = Wemo.state_map[val_on_off.lower()]
        try:
            s.basicevent.SetBinaryState(BinaryState=state)
        except:
            status = 2
        return status
예제 #47
0
class Wemo(Command):
    def __init__(self):
        self.env = Environment(with_discovery=False, with_subscribers=False)
        self.env.start()

    def on(self, device):
        switch = self.env.get_switch(closest_match(device, self.env.list_switches()))
        switch.basicevent.SetBinaryState(BinaryState=1)

    def off(self, device):
        switch = self.env.get_switch(closest_match(device, self.env.list_switches())) 
        switch.basicevent.SetBinaryState(BinaryState=0)
예제 #48
0
def toggleLight():
    env = Environment()
    try:
        env.start()
    except:
        print "server may have been started already"
    for i in range(1, 5):
        try:
            env.discover(i)
            switch = env.get_switch("WeMo Switch")
            switch.toggle()
        except:
            continue
        break
예제 #49
0
def get_switch():
    env = Environment()

    try:
        env.start()
    except:
        pass

    env.discover(5)
    found = None
    for switch in env.list_switches():
        if matches(switch):
            found = env.get_switch(switch)
            break
    else:
        raise Exception('Switch not found!')

    return found
예제 #50
0
def mainloop(name):
    matches = matcher(name)

    @receiver(devicefound)
    def found(sender, **kwargs):
        if matches(sender.name):
            print "Found device:", sender.name

            while 1:
                print_some_times(sender)



   
    env = Environment(with_cache=False)
    try:
        env.start()
        env.discover(10)
        env.wait()
    except (KeyboardInterrupt, SystemExit):
        print "Goodbye!"
        sys.exit(0)
예제 #51
0
파일: watch.py 프로젝트: Critter/ouimeaux
def mainloop(name):
    matches = matcher(name)

    @receiver(devicefound)
    def found(sender, **kwargs):
        if matches(sender.name):
            print "Found device:", sender.name

    @receiver(statechange)
    def motion(sender, **kwargs):
        if matches(sender.name):
            print "{} state is {state}".format(
                sender.name, state="on" if kwargs.get('state') else "off")

    env = Environment(with_cache=False)
    try:
        env.start()
        env.discover(10)
        env.wait()
    except (KeyboardInterrupt, SystemExit):
        print "Goodbye!"
        sys.exit(0)
예제 #52
0
def mainloop(name):
    matches = matcher(name)

    def is_standby(name):
        print "Waiting for standby or powerof"
        switch = env.get_switch(name)
        time.sleep(10)
        normal_power = switch.current_power
        time.sleep(10)

        while switch.get_state():
            if switch.current_power < (normal_power * 0.2):
                print "Device in standby mode!"
                break
            time.sleep(10)

    @receiver(devicefound)
    def found(sender, **kwargs):
        if matches(sender.name):
            print "Found device:", sender.name

    @receiver(statechange)
    def on_off(sender, **kwargs):
        if matches(sender.name):
            print "{} state is {state}".format(
                sender.name, state="on" if kwargs.get('state') else "off")
            if kwargs.get('state'):
                is_standby(sender.name)

    env = Environment(with_cache=False)
    try:
        env.start()
        env.discover(10)
        env.wait()
    except (KeyboardInterrupt, SystemExit):
        print "Goodbye!"
        sys.exit(0)
예제 #53
0
파일: wemo.py 프로젝트: tmackall/bin-home
def main():
    # define input parameters
    parser = OptionParser()
    parser.add_option("-a", help="all of the wemo devices", default=False, action="store_true")
    parser.add_option("-g", help="get switch state", default=False, action="store_true")
    parser.add_option("-l", help="list all the switches", default=False, action="store_true")
    parser.add_option("--off", help="off flag - default is on", default=False, action="store_true")
    parser.add_option("-s", help="switch name", default=None)

    # read input values
    (options, args) = parser.parse_args()
    flag_on_off = ON
    if options.off:
        flag_on_off = OFF
    flag_list = options.l
    flag_get = options.g
    switch_name = options.s

    #
    # environment - wemo
    env = Environment()
    env.start()
    env.discover()
    switches = env.list_switches()

    if switch_name is not None:
        if switch_name not in switches:
            print "%s is not available" % switch_name
            return {"status": 1}
        else:
            switches = [switch_name]

    if flag_list:
        return {"status": 0, "msg": switches}

    if flag_get:
        return {"status": 0, "msg": switch_get(env, switches)}

    #
    # switch - on/off
    switch_set(env, switches, flag_on_off)
    return {"status": 0, "msg": "switch(es):%s val:%s" % (switches, flag_on_off)}
예제 #54
0
파일: wemo.py 프로젝트: mmaduabum/Foodie
def go_pi():
	try:
		sys.stderr = open("otherlog.txt", "wa+")
		sys.stdout = open("log.txt", "wa+")
		print "Powering up server..."
		switches = []
		env = Environment(on_switch, on_motion)
		env.start()
		#search until a switch is found
		tries = 0
		print "Searching for switches..."
		while True:
			tries += 1
			names = env.list_switches()
			if len(names) > 0: break
			if tries == 100: 
				print "FAILED to find a switch after 100 tries"
				sys.exit()
		#create a dictionary object wrapper for each found switch
		for switch_name in names:
			s = {NAME : switch_name, SWITCH : None, STATE : OFF, ID : None, THRESH : None, MIN : 0}
			if switch_name == "ymcmb":
				ymcmb = env.get_switch('ymcmb')
				s[SWITCH] = ymcmb
				s[ID] = YMCMB_ID
				s[THRESH] = YMCMB_THRESH
				s[MIN] = YMCMB_MIN
			elif switch_name == "patty":
				paddy = env.get_switch('patty')
				s[SWITCH] = paddy
				s[ID] = PADDY_ID
				s[THRESH] = PADDY_THRESH
			#create a list of all found switches
			switches.append(s)

		run_local_server(switches)
	except:
		pass
예제 #55
0
#!/usr/bin/env python

import os, re, time, sys
from ouimeaux.environment import Environment
os.system('clear')

def on_switch(switch):
    print "Switch found!", switch.name
    #pass

env = Environment(on_switch)

env.start()

env.discover(seconds=15)

env.list_switches()

예제 #56
0
import random
import datetime
import time
import ouimeaux
from ouimeaux.environment import Environment

# http://pydoc.net/Python/ouimeaux/0.7.3/ouimeaux.examples.watch/
if __name__ == "__main__":
    print ""
    print "WeMo Randomizer"
    print "---------------"
    env = Environment()
    # TODO: run from 10am to 10pm
    try:
        env.start()
        env.discover(100)
        print env.list_switches()
        print env.list_motions()
        print "---------------"
        while True:
            # http://stackoverflow.com/questions/306400/how-do-i-randomly-select-an-item-from-a-list-using-python
            switchRND = env.get_switch( random.choice( env.list_switches() ) )
            print switchRND
            switchRND.toggle()
            env.wait(90)
        
    except (KeyboardInterrupt, SystemExit):
        print "---------------"
        print "Goodbye!"
        print "---------------"
예제 #57
0
#!/Python27/

import speech_recognition as sr
from ouimeaux.environment import Environment

def on_switch(sw):
	print  "Switch found!", sw.name

env = Environment(); env.start()
env.discover(5)

barLights = env.get_switch("Bar Lights")
bedroomLight = env.get_switch("Bedroom Light")

#obrain audio from the microphone
r = sr.Recognizer()
with sr.Microphone() as source:
	print("Say something!")
	audio = r.listen(source)

# recognize speech using Wit.ai
WIT_AI_KEY = "S6GRTNGQSDYWIBFSCYBGS6DZMYRGHS52"
try:
	print("Wit.ai thinks you said " + r.recognize_wit(audio, key=WIT_AI_KEY))
except sr.UnknownValueError:
	print("Wit.ai could not understand audio")
except sr.RequestError as e:
	print("Could not request results from Wit.ai service; {0}".format(e))

if r.recognize_wit(audio, key=WIT_AI_KEY) == "turn on the bar lights":
	barLights.on();
예제 #58
0
from config import CONFIG
import pychromecast
from ouimeaux.environment import Environment
from ouimeaux.signals import receiver, statechange

cast = None


def reset_chromecast():
    """Reset the chromecast connection."""
    global cast
    cast = pychromecast.get_chromecast(friendly_name=CONFIG['cast_name'])
    print("Connected to chromecast {}".format(cast))
    time.sleep(3)

env = Environment()
env.start()
env.discover(5)
switch = env.get_switch(CONFIG['wemo_name'])
print("Connected to switch {}".format(switch))

reset_chromecast()


def safe_volume_toggle(direction, notches):
    try:
        if direction == 1:
            for _ in notches:
                print("TURN DOWN FOR WHAT!")
                cast.volume_up()
        elif direction == 8: