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)
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']
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()
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
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))
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
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
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
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)
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()
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.")
def devices(): try: env = Environment() env.start() env.discover(seconds=3) result = env.list_switches() except: raise return result
def command_switchInfo(m): if m.chat.id in allowedChatIDs: def on_switch(switch): if wemoDevice == switch.name: bot.send_message(m.chat.id, "Switch found! state: %s" % 'ON' if switch.get_state() == 1 else 'OFF') bot.send_message(m.chat.id, "Looking for switch ...") env = Environment(on_switch) env.start() env.discover(seconds=3) else: bot.send_message(m.chat.id, "Sorry. I'm a private bot. I don't want to speak with you")
def refresh_wemo_devices(): global WEMO_DEVICES WEMO_DEVICES = {} try: env = Environment(found_device, with_subscribers=False, config_filename='./wemo-config.yaml') env.start() env.discover(seconds=5) except Exception as e: logger.error(traceback.format_exc())
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
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)
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
def wemo_start(): env = Environment(on_switch,on_motion) env.start() env.discover(seconds=3) #print("listing:") #env.list_switches() devices = {} for device_name in config["devices"]: switch = env.get_switch(device_name) #switch["node"] = config["devices"][device_name]["node"] # no support for assignment devices[device_name] = switch #print("explain()") #switch.explain() return devices
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
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()
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
def command_switchOFF(m): if m.chat.id in allowedChatIDs: def on_switch(switch): if wemoDevice == switch.name: if switch.get_state() == 0: bot.send_message(m.chat.id, "Switch already OFF") else: switch.basicevent.SetBinaryState(BinaryState=0) bot.send_message(m.chat.id, "Switch OFF") bot.send_message(m.chat.id, "Looking for switch ...") env = Environment(on_switch) env.start() env.discover(seconds=3) else: bot.send_message(m.chat.id, "Sorry. I'm a private bot. I don't want to speak with you")
class SwitchSetMaintainer(threading.Thread): 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() def find_energy_meter(self): self._env.discover(self._config['discover_wait_time']) logging.debug("List of local switches: " + str(self._env.list_switches())) name_set_current = set(self._env.list_switches()) switch_names_new = name_set_current - self._name_set for switch_name in switch_names_new: logging.info("Found new switch" + str(switch_name) + ". Getting the instance of the switch") switch_instance = None try: switch_instance = self._env.get_switch(switch_name) except Exception as e: logging.error("Error when trying to get meter instance") logging.error(e) if switch_instance is not None: logging.info("Creating the Querier thread for the switch " + str(switch_name)) try: querier = SwitchQuerier( config=self._config_querier, switch_name=switch_name, switch_instance=switch_instance, data_queue=self._data_queue, name_set=self._name_set ) querier.setDaemon(True) except Exception as e: logging.error("Error when trying to create Querier thread") logging.error(e) else: querier.start() self._name_set.add(switch_name) def run(self): self._env.start() while(True): self.find_energy_meter() time.sleep(self._config['update_interval'])
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
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()
def get_switch(): env = Environment() try: env.start() except Exception: 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
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
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()
def function_one(flag): # Initialization env = Environment() env.start() env.discover(3) b = Bridge('192.168.0.100') b.connect() lights = b.lights groups = b.groups client = MongoClient( 'mongodb://*****:*****@tmega-shard-00-00-kcfpq.mongodb.net:27017,tmega-shard-00-01-kcfpq.mongodb.net:27017,tmega-shard-00-02-kcfpq.mongodb.net:27017/user_info?ssl=true&replicaSet=tmega-shard-0&authSource=admin' ) db_website = client.website # Post button press to API temp_dict = db_website.usrname.find_one({'username': '******'}, {'button_one': ()}) new_value = int(temp_dict['button_one']) + 1 db_website.usrname.update({'username': '******'}, {'$set': { 'button_one': new_value }}, upsert=False) # Bedroom Lights (ON) if flag == 1: b.set_light('lamp 3', 'on', True) b.set_light('lamp 3', {'bri': int(200), 'transitiontime': 1}) b.set_light('lamp 3', 'ct', 197) # Kitchen Lights (ON) if flag == 2: b.set_group('Kitchen', 'on', True) b.set_group('Kitchen', {'bri': int(100), 'transitiontime': 1}) # TV (NONE) if flag == 3: print("TV 1") # Fan (ON) if flag == 4: env.get_switch('office').on() sleep(0.3)
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)}
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()
def wemo(bot, trigger): a = trigger.group(2) if not a: return env = Environment() env.start() env.discover(seconds=1) l = env.get_switch('Light') if a.lower() == 'on': l.on() return bot.say('Lights on') elif a.lower() == 'status': if l.get_state() == 1: bot.say('Light is on') elif l.get_state() == 0: bot.say('Light is off') else: bot.say('Unknown') elif a.lower() == 'off': l.off() return bot.say('Lights off')
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)
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)
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)
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)
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)
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)
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')
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 "---------------" # Turn off all switches
#!/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();
class WemoInsightSwitch(basemodule.SensorModule): def __init__(self): self.env = Environment(switch_callback=self.on_switch, motion_callback=self.on_motion, with_cache=False) self.env.start() self.devices = [] def trigger_device_discovery(self): self.env.discover(seconds=10) self.env.list_switches() devices_found = self.env.list_switches() timestamp = time.time() data = [] self.devices = [] for device_name in devices_found: data.append((device_name, timestamp)) self.devices.append(device_name) return data def trigger_device_check(self): devices = self.devices data = [] timestamp = time.time() for device_name in devices: try: insight = self.env.get_switch(device_name) tkwh = insight.today_kwh cp = insight.current_power tot = insight.today_on_time of = insight.on_for lc = insight.last_change tsbt = insight.today_standby_time ot = insight.ontotal tmw = insight.totalmw data.append((device_name, tkwh, cp, tot, of, lc, tsbt, ot, tmw, timestamp)) except: print 'Error connecting to WeMo' print '-' * 20 traceback.print_exc(file=sys.stdout) print '-' * 20 return data @staticmethod def discovery_timer(): return 900 @staticmethod def check_timer(): return 30 @staticmethod def data_format(): return [('device_name', 'text'), ('today_kwh', 'integer'), ('current_power', 'integer'), ('today_on_time', 'integer'), ('on_for', 'integer'), ('last_change', ' integer'), ('today_standby_time', 'integer'), ('ontotal', 'integer'), ('totalmw', 'integer'), ('date', 'integer')] @staticmethod def database_version(): return 1 def on_switch(self, switch): print "Switch found!", switch.name def on_motion(self, motion): print "Motion found!", motion.name
# this server sends and receives all signals from wemo switches. # It makes RESTful calls to other services in the apartment based on the switch states # Date: 3/23/2015 # Author: Brian Aggrey import requests from ouimeaux.environment import Environment from ouimeaux.signals import statechange, receiver # define globals bedroomURL = 'http://192.168.1.2:5000' env = Environment() if __name__ == "__main__": env.start() env.discover(5) switch = env.get_switch('bedroomSwitch') @receiver(statechange, sender=switch) def switch_toggle(sender, **kwargs): print sender.name, kwargs['state'] if kwargs.get('state'): # If switch turns on, send GET request to bedroomServer with "on" param requests.get(bedroomURL + '/state/', params={'command': 'on'}) else: # If switch turns on, send GET request to bedroomServer with "off" param requests.get(bedroomURL + '/state/', params={'command': 'off'}) env.wait()
name = "Device" # Name of the device port = 8765 # Port where the websocket will be served def on_switch(switch): print("Switch found!", switch.name) def on_motion(motion): print("Motion found!", motion.name) env = Environment(on_switch, on_motion) env.start() env.discover(seconds=3) print("Found the following wemo devices: ", env.list_switches()) switch = env.get_switch(name) # Get IP hostname = socket.gethostname() IPAddr = socket.gethostbyname(hostname) print("Your Computer Name is:" + hostname) print("Your Computer IP Address is:" + IPAddr) # Define websocket server async def hello(websocket, path): while True: try: cmd = await websocket.recv()
class HABelkinWemo(HomeAutomationQueueThread): webservice_definitions = [ WebServiceDefinition( '/HABelkinWemo/setState/([a-zA-Z0-9 ]+)/(\w+)', 'WebService_HABelkinWemoSetLightState', '/HABelkinWemo/setState/', 'wsHueSetState'), ] # region Method overrides 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() def pre_processqueue(self): logging.info('Belkin Wemo module initialized') self.env.start() self.env.discover(10) webservice_state_instances_add(self.__class__.__name__, self.get_json_status) webservice_class_instances_add(self.get_class_name(), self) self.update_light_instances() self.timecheck = time.time() self.update_light_cache() self.cachetime = time.time() logging.info('Belkin Wemo module ready') super(HABelkinWemo, self).pre_processqueue() def post_processqueue(self): if time.time() - self.timecheck > 3600: # every hour self.timecheck = time.time() logging.info('30s interval') self.update_light_instances() if time.time() - self.cachetime > 30: # every 30 seconds self.cachetime = time.time() self.update_light_cache() super(HABelkinWemo, self).post_processqueue() def get_class_name(self): return self.__class__.__name__ def get_json_status(self): return json.dumps({self.__class__.__name__: { 'lights': self.cache }}) # endregion def set_light_state(self, id, state): with self.lock: if id in self.lights.keys(): l = self.lights[id] l.set_state(state) #update cache value also for l in self.cache: if l['Name'] == id: l['State'] = state return True def update_light_cache(self): with self.lock: logging.info('++ updating light status cache') cache = [] for key, value in self.lights.iteritems(): #self.cache[key] = {} d = {} d['Name'] = key d['State'] = value.get_state() #for attr in self.relevant_light_attrs: # #self.cache[key][attr] = getattr(value, attr) # d[attr] = getattr(value, attr) cache.append(d) self.cache = cache logging.info('-- updating light status cache') def update_light_instances(self): with self.lock: logging.info('++ updating light instances') namesfound = [] added, removed = 0, 0 for switchname in self.env.list_switches(): logging.info('found switch with name: ' + switchname) if not switchname in namesfound: namesfound.append(switchname) if not switchname in self.lights.keys(): self.lights[switchname] = self.env.get_switch(switchname) added += 1 for name in self.lights.keys(): if not name in namesfound: self.lights.pop(name, None) removed+=1 if added != 0 or removed != 0: logging.info('Added ' + str(added) + ' lights and removed ' + str(removed)) logging.info('-- updating light instances')
import time from datetime import datetime from pyhue import Hue from ouimeaux.environment import Environment from ouimeaux.subscribe import SubscriptionRegistry registry = SubscriptionRegistry() env = Environment(with_cache=False) env.start() env.discover(3) ms = env.list_motions() ss = env.list_switches() m = ms[0] m = env.get_motion(ms[0]) ss = [env.get_switch(s) for s in ss] h = Hue() ls = h.lights print ls sunset = dict(sofa = [0.5543, 0.4098], room = [0.5452, 0.4164], bed = [0.5848, 0.3872], desk = [0.5413, 0.4193])
class WemoInsightSwitch(basemodule.SensorModule): def __init__(self): self.env = Environment(switch_callback=self.on_switch, motion_callback=self.on_motion, with_cache=False) self.env.start() self.devices = [] def trigger_device_discovery(self): self.env.discover(seconds=10) self.env.list_switches() devices_found = self.env.list_switches() timestamp = time.time() data = [] self.devices = [] for device_name in devices_found: data.append((device_name, timestamp)) self.devices.append(device_name) return data def trigger_device_check(self): devices = self.devices data = [] timestamp = time.time() for device_name in devices: try: insight = self.env.get_switch(device_name) tkwh = insight.today_kwh cp = insight.current_power tot = insight.today_on_time of = insight.on_for lc = insight.last_change tsbt = insight.today_standby_time ot = insight.ontotal tmw = insight.totalmw data.append((device_name, tkwh, cp, tot, of, lc, tsbt, ot, tmw, timestamp)) except: print 'Error connecting to WeMo' print '-'*20 traceback.print_exc(file=sys.stdout) print '-'*20 return data @staticmethod def discovery_timer(): return 900 @staticmethod def check_timer(): return 30 @staticmethod def data_format(): return [('device_name', 'text'), ('today_kwh', 'integer'), ('current_power', 'integer'), ('today_on_time', 'integer'), ('on_for', 'integer'), ('last_change', ' integer'), ('today_standby_time', 'integer'), ('ontotal', 'integer'), ('totalmw', 'integer'), ('date', 'integer')]; @staticmethod def database_version(): return 1 def on_switch(self, switch): print "Switch found!", switch.name def on_motion(self, motion): print "Motion found!", motion.name
wemo = button_switches[mac] wemo.toggle() if mac in email_switches: email = email_switches[mac] email.send() if len(sys.argv) < 2: print("Usage: {} <path to config file>".format(sys.argv[0])) sys.exit(1) with open(sys.argv[1]) as conf: config = json.loads(conf.read()) env = Environment(with_subscribers=False, with_cache=False) env.start() env.discover() #env.wait(3) found_wemos = False for switch_name in env.list_switches(): for entry in config: if switch_name == entry.get('wemo switch'): # FIXME: log print("Found Wemo: {}".format(switch_name)) button_switches[entry['button mac']] = env.get(switch_name) found_wemos = True for bridge_name in env.list_bridges(): bridge = env.get_bridge(bridge_name) for light_name in bridge.bridge_get_lights():
import ouimeaux from ouimeaux.environment import Environment from time import sleep print "env" wemo = Environment() print "start" wemo.start() print "discover" wemo.discover(5) print wemo.list_switches() wemoFan = wemo.get_switch("wemoFan02") print "on" wemoFan.on() sleep(5) print "off" wemoFan.off() sleep(5) print "toggle" wemoFan.toggle()
def main(): if args.list: env = Environment() env.start() env.discover(seconds=4) listSwitches(env) exit(0) elif args.mon: print("Monitoring current temperatures every %s seconds" % accuracy) print("Press Enter to quit") m = watchTemp() t1 = Thread(target=m.run) t1.setDaemon(True) t1.start() raw_input() exit(0) if args.fudge: lagValue = args.fudge else: lagValue = None if args.switch and args.temp and args.time: print("Finding WeMo switches") env = Environment() env.start() env.discover(seconds=4) switchName = args.switch origTarget = args.temp timer = (int(args.time) * 60) try: switch = env.get_switch(switchName) except: print("Couldn't find %s" % switchName) listSwitches(env) exit(1) try: targetScale = origTarget[-1] if targetScale == "F": targetF = float(origTarget[:-1]) # Convert to celsius because we're not American target = ((targetF - 32) / 1.8) elif targetScale == "C": target = float(origTarget[:-1]) else: print("Error: Please specify either [C]elsius or [F]ahrenheit") exit(1) except: parser.print_help() while getTemp() < target: if getSwitch(switch) == False: switchOn(switch) if targetScale == "F": print("Heating up. Current temp: %sF" % (getTemp() * 1.8 + 32)) else: print("Heating up. Current temp: %sC" % getTemp()) time.sleep(accuracy) print("Device on switch %s is at target temperature %s" % (switchName, origTarget)) switchOff(switch) # Start the temp maintainer thread # Catch exit exceptions when timer expires m = maintainTemp() t1 = Thread(target=m.run, args=(switch, target, targetScale, lagValue)) t1.setDaemon(True) t1.start() raw_input("Press Enter to start the %s minute timer\n" % (timer/60)) startTime = int(time.time()) currentTime = startTime readableStart = time.strftime("%I:%M %p", time.localtime(startTime)) readableFinish = time.strftime("%I:%M %p", time.localtime(startTime + timer)) temp = {} # Build a dict to keep track of temperature print("Timer started, start time: %s finish time: %s\n" % (readableStart, readableFinish)) while currentTime < (startTime + timer): time.sleep(accuracy) currentTime = time.time() temp[time.time()] = getTemp() timeLeft = (startTime + timer) - currentTime if timeLeft > 0 and timeLeft < 60: print("%s seconds left" % int(round(timeLeft))) elif int(round(timeLeft)/60) == 1: print("1 minute left") elif (round(timeLeft)/60) < 15: print("%s minutes left" % int(round(timeLeft/60,1))) m.terminate() # Kill the maintainTemp loop once timer finished t1.join() # Join the maintainTemp thread with main switchOff(switch) # We've finished. Turn the switch off, no matter the current state. average = sum(temp.values())/len(temp) if targetScale == "F": average = average * 1.8 + 32 print("Timer %s mins reached. Switch %s is now off" % ((timer/60), switch.name)) print("Average temperature was %s%s with a %s second accuracy" % (round(average,3), targetScale, accuracy)) # FIXME: # if args.out: # try: # outfile = args.out # except: # parser.print_help() # drawGraph(temp, outfile, targetScale) else: # If they haven't provided enough detail, print help print("\nYou must provide either --list, --mon, or all 3 of -s, -t and -T\n") parser.print_help()
$ python ./devices/power.py ''' def __init__(self, outlet): addr = 'http://' + outlet.replace("wemo://", "") + ":49153/setup.xml" self.switch = WemoSwitch(addr) def reset(self): self.switch.off() time.sleep(5) self.switch.on() if __name__ == "__main__": print("Gathering info about power outlets...") if WemoEnv is not None: env = WemoEnv() env.start() scan_time = 10 print("Scanning for WeMo switches for %s seconds..." % scan_time) env.discover(scan_time) if len(env.list_switches()) > 0: print("Found the following switches:"); for switch_name in env.list_switches(): switch = env.get_switch(switch_name) print("%s ip address is %s" % (switch_name, switch.host)) print("The switches above can be added by ip address" " for example use the") print("following to use %s" % switch_name) print("\twemo://%s" % switch.host) else: print("No WeMo switches found")
def mainloop(name): matches = matcher(name) queueName = 'HUECOMMANDS' channel = None def connect(): global channel global queue print "Connecting to RabbitMQ" connection = pika.BlockingConnection(pika.ConnectionParameters( '54.69.168.245')) channel = connection.channel() channel.queue_declare(queue=queueName) print "Connected to RabbitMQ" def postState(): global channel print "motion detected ", datetime.now().time() #TODO: this should be posting events, not commands, but this works for now... if channel is not None: channel.basic_publish(exchange='', routing_key=queueName, body=buildMessage("5").SerializeToString()) channel.basic_publish(exchange='', routing_key=queueName, body=buildMessage("6").SerializeToString()) channel.basic_publish(exchange='', routing_key=queueName, body=buildMessage("7").SerializeToString()) print "message posted" def buildMessage( id ): m = UpdateLightCommand.UpdateLightCommand() m.is_on = True m.msg_version = 1 m.light_id = id m.rgb_red = 255 m.rgb_green = 255 m.rgb_blue = 255 return m @receiver(devicefound) def found(sender, **kwargs): if matches(sender.name): print "Found device:", sender.name connect() @receiver(statechange) def motion(sender, **kwargs): if matches(sender.name) and kwargs.get('state'): postState() env = Environment(with_cache=False) try: env.start() env.discover(10) env.wait() except (KeyboardInterrupt, SystemExit): print "Goodbye!" sys.exit(0)
client = mqtt.Client("wemo_controller") client.on_connect = on_connect client.message_callback_add('lights/on', turn_lights_on) client.message_callback_add('lights/off', turn_lights_off) client.message_callback_add('devices/discover', reply_with_devices) client.connect('192.168.0.11', 1883, 60) print 'Running WEMO controller - listening for messages on localhost:1883' devices = { 'switches': [], 'motions': [] } print "start" env = Environment(on_switch, on_motion) print "got env" env.start() print "middle" env.discover(seconds=3) print env.list_switches() print env.list_motions() print "LISTED" @receiver(statechange) def motion(sender, **kwargs): print 'A THING HAPPENED' print "{} state is {state}".format(sender.name, state="on" if kwargs.get('state') else "off") client.loop_start() env.wait()
#!/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()
class AdvancedWemoSkill(MycroftSkill): def __init__(self): super(AdvancedWemoSkill, self).__init__(name="AdvancedWemoSkill") def initialize(self): self.wemo = Environment(self.on_switch, self.on_motion) self.wemo.start() self.wemo.discover(seconds=3) def on_switch(self, switch): self.register_vocabulary(switch.name, "WemoSwitch") def on_motion(self, motion): self.register_vocabulary(switch.name, "WemoMotion") def get_toggle_label(self, state): return { 0: "off", 1: "on", }[state] @intent_handler( IntentBuilder("").require('Schedule').require("Toggle").require( "WemoSwitch").require("Switch")) def handle_schedule_switch(self, message): utterence = message.data.get('utterance') eventTime = extract_datetime(utterence) self.schedule_event(self.handle_switch, eventTime[0], data=message.data) name = message.data.get('WemoSwitch') method = message.data.get('Toggle') device = self.wemo.get_switch(name) self.speak_dialog('schedule.switch.toggle', data={ "light": device.name, "toggle": method }) @intent_handler( IntentBuilder("").require("Toggle").require("WemoSwitch").require( "Switch")) def handle_switch(self, message): name = message.data.get('WemoSwitch') method = message.data.get('Toggle') device = self.wemo.get_switch(name) state = device.get_state() command = getattr(device, method) if self.get_toggle_label(state) == method: self.speak_dialog("switch.active", data={ "light": device.name, "toggle": method }) elif method == 'toggle': self.speak('Toggling ' + device.name) command() else: self.speak_dialog("switch.toggle", data={ "light": device.name, "toggle": method }) command() @intent_handler(IntentBuilder("").require("Find").require("WemoDevices")) def handle_discover(self, message): self.speak('Looking for wemo switches...') self.wemo.start() self.wemo.discover(seconds=5) switches = self.wemo.list_switches() self.speak_dialog('switch.found', data={"count": len(switches)}) @intent_handler(IntentBuilder("").require("List").require("WemoDevices")) def handle_list_switches(self, message): switches = self.wemo.list_switches() self.speak_dialog("switch.known", data={"count": len(switches)}) for index, switch in enumerate(switches, start=1): if (index == len(switches)): self.speak('and ' + switch) else: self.speak(switch) # The "stop" method defines what Mycroft does when told to stop during # the skill's execution. In this case, since the skill's functionality # is extremely simple, there is no need to override it. If you DO # need to implement stop, you should return True to indicate you handled # it. def stop(self): return False
class WemoPlugin(IPlugin): """ Abstraction of the Wemo plugin. """ 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, }] } def command(self, command_dict, comm_text, device_text): """ Give the robot a command """ if comm_text: command_text = comm_text else: command_text = command_dict['command'] device_id_text = None if device_text: for d in self.devices: if d.lower() == device_text: device_id_text = d else: for d in self.devices: if d.lower() == command_dict['device']: device_id_text = d if not device_id_text: raise Exception('Device unknown') self.env.discover(5) switch = self.env.get_switch(device_id_text) if not self.voice: self.instantiate_voice() self.voice.say({}, 'Turning ' + command_text + ' the ' + device_id_text + '.') if command_text == 'on': switch.on() elif command_text == 'off': switch.off() def instantiate_voice(self): """ We need to separately instatiate this so yapsy doesn't get confused. """ from footman.plugins.voice import VoicePlugin self.voice = VoicePlugin() return None
def list_switches(): env = Environment(on_switch, on_motion) env.start() env.discover(seconds=1) return env.list_switches()