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)
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)
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
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()
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']
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))
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
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])
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 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)
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 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])
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 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 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 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 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
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 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 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
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_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
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')
} #EDIT THIS COMMAND TO CONTAIN THE MAC ADDRESS OF THE DEVICE YOU WANT TO USE TO GAUGE DISTANCE command = 'hcitool rssi DEVICE_MAC_ADDRESS' #WEMO SECTION #Find and connect to WeMo Devices. print('Finding WeMo devices') def on_switch(switch): print "Switch found!", switch.name #USE INFO RETURNED FROM ENV TO PROPERLY NAME YOUR DEVICES (EX. 'Air Conditioner') env = Environment(on_switch) env.start() aircon = env.get_switch('Air Conditioner') fan = env.get_switch('Fan') #Set global locks bedroom_locked = None livingroom_locked = None harmony_lock = None wemo_lock = None idle_loop_check = None #Start up Myo print('Starting Fullmetal') print('Keep your arm in REST position. Wait to sync until connect is complete') fullmetal = Myo()
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: for _ in notches: print("OKAY MOM!") cast.volume_down()
wemo = {} short = aliases() print wemo URL = '/?oh=on&lamp=off/' #URL = '/?oh=off' parse = linereader() print parse.params for key in parse.params: name = wemo.get(key, None) if name: print name, parse.params[key] if parse.params[key] == "on": state = 1 print state if parse.params[key] == "off": state = 0 print state try: switch = env.get_switch(name) switch.basicevent.SetBinaryState(BinaryState=state) except: print ("Doesn't exist.") pass #print short.string #string = " oh: Office Heater"
print("System Initiated, Looking for devices") print("---------------") env = Environment() machines = dict() try: env.start() env.discover(10) switches = env.list_switches() # creating dict for switches for switch in switches: machines[switch] = 0 print "Found devices in the network", machines while True: #start detecting current power" env.wait(5) for key in machines: selectedMachine = env.get_switch(key) #mySwitch.toggle() machines[key] = selectedMachine.current_power # apiURL = "/add_schedule_anonymous?machine_id=%s&curr_power=%d" % (key,selectedMachine.current_power) # Test network connection : response = urllib.urlopen("https://www.google.com") PARAMS = { 'machine_id': key, 'curr_power': selectedMachine.current_power } response = requests.post(serverurl, data=PARAMS) print response.json() except (KeyboardInterrupt, SystemExit): print("---------------") print("Goodbye!") print("---------------")
# Echo client program import socket from ouimeaux.environment import Environment env = Environment() env.start() switches = list() env.discover(seconds=3) switchesList = env.list_switches() #switches = list() for s in switchesList: switches.append(env.get_switch(s)) str_switches = ', '.join(switchesList) # to be sent to server HOST = 'localhost' # The remote host PORT = 50010 # Arbitrary non-privileged port s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #s.connect((HOST, PORT)) s.bind((HOST, PORT)) print('Ready for Connections') while 1: s.listen(1)
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 os, sys, requests, json, time, argparse from datetime import datetime from ouimeaux.environment import Environment from ouimeaux.signals import statechange, receiver parser = argparse.ArgumentParser() parser.add_argument("-set", action="store_true") parser.add_argument("-isSub", action="store_true") parser.add_argument("-port", type=int, default=10085) options = parser.parse_args() env = Environment(bind="0.0.0.0:{}".format(options.port), with_subscribers=options.isSub) env.start() env.discover(5) switch = env.get_switch('WeMo Switch1') @receiver(statechange, sender=switch) def switch_toggle(device, **kwargs): print device, kwargs['state'] if options.set: switch.on() print(time.strftime("%H%M%S")) sys.exit(0) else: switch.off() while switch.get_state(force_update=True) == 0: time.sleep(1) print(switch.get_state(force_update=True)) print(time.strftime("%H%M%S"))
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]) def updated(): t = time.localtime() n = datetime.now() start_time = n.replace(hour=19, minute=5, second=0, microsecond=0) end_time = n.replace(hour=0, minute=55, second=0, microsecond=0)
configParser.read(configFilePath) print env.list_switches() switchList = env.list_switches() start=time.time() ''' In this loop we will go throuh list of devices and for each one will store the following information switch name, switch mac address, and current power consumption. we also search for new devices based on the rediscovery time for example if it's 20 we will refresh list of devices every 20 seconds. this is for times when we unplug one device and plug it again for example. ''' while True: for i in range(0,len(switchList)): switch = env.get_switch(switchList[i]) try: power= switch.insight.GetPower()["InstantPower"] print power macAd = switch.basicevent.GetMacAddr()["MacAddr"] print macAd schoolName = configParser.get(macAd, 'school_name') room = configParser.get(macAd, 'room') mydata={'room_name':room,'sensor_name':macAd,'school_name':schoolName ,'value1':power} path='http://www.learningenergy.eca.ed.ac.uk/sense.php' #the url you want to POST to print requests.post(path, mydata) except Exception as e: print 'Exception error is: %s' % e time.sleep(10);
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 for switch in ( env.list_switches() ): print "Turning Off: " + switch env.get_switch( switch ).off()
#!/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();
# 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()
r = requests.get(channels_api_url) for ch in r.json()['channels']: print ch print 40 * "########" if r.status_code != 200: print "Couldn't get a valid response from Slack api, maybe check API token" exit(1) # get string channel name from encoded response and compare try: for channel in r.json()['channels']: if 'fire-' in str(channel['name']) and str(channel['is_archived']) != 'True': print "Fire channel found: %s" % channel['name'] print "Channel archived status: %s " % channel['is_archived'] firestatus = True # Turn on all switches in this lan for switch in (env.list_switches()): print("Turning On : " + switch) env.get_switch(switch).on() except KeyError: print "Couldnt get slack channels; is API token env variable correct?" if not firestatus: # Turn off all switches print 'No fires found in slack' for switch in (env.list_switches()): print("Turning Off: " + switch) env.get_switch(switch).off()
$ 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")
TRoof = W1ThermSensor(16,TRoofID) # an old DS1820 sensor # check temperature sensors print "Find Temp Sensors" for s in W1ThermSensor.get_available_sensors(): print ">Found:",s.id, s.get_temperature(),"'C" # setup WeMo switch print "\nFind Wemo Switches" wemo = Environment() print ">start" wemo.start() print ">discover" wemo.discover(5) print ">Found: ", wemo.list_switches() print ">get RoofFan" RoofFan01 = wemo.get_switch(RoofFanID) # humidty sensor print "Check Humidity Sensors" print "Roof ", hrf,trf2 = readHumidity(HS1_Pin) print "Room ", hrm,trm2 = readHumidity(HS2_Pin) # setup GPIO for buzzer and LED gpio.setup(PWM_Pin,gpio.OUT) #alarm buzzer gpio.setup(LED_Pin,gpio.OUT) #LED ####### MAIN LOOP #######
class actuators(): def __init__ (self): self._env = Environment(self._setup_switch) self._sensors = Sensors() def _setup_switch(self,switch): print "Switch found!", switch.name def start(self): self._env.start() def _getName(self): sensorName=self._env.list_switches() return sensorName[0] def _getNameList(self): sensorNameList=self._env.list_switches() return sensorNameList def _getIdFromName(self, name): if name=='Lamp01': idSensor='91' elif name=='LivingRoomLamp': idSensor='92' elif name=='KitchenCoffeMachine': idSensor='93' elif name=='LivingRoomTV': idSensor='94' else: idSensor=null return idSensor def _getValue(self, name): if name=='Lamp01': idSensor='91' elif name=='LivingRoomLamp': idSensor='92' elif name=='KitchenCoffeMachine': idSensor='93' elif name=='LivingRoomTV': idSensor='94' else: idSensor=null return self._sensors.getSensor(idSensor) def _get_switch(self, name): return self._env.get_switch(name) def _on_switch(self, switch): switch.basicevent.SetBinaryState(BinaryState=1) def _off_switch(self, switch): switch.basicevent.SetBinaryState(BinaryState=0) def setOn(self, name): self._sensors.updateSensor(self._getIdFromName(name), 1.0, 'On') print " %s has been switched On" % name def setOff(self, name): self._sensors.updateSensor(self._getIdFromName(name), 0.0, 'Off') print " %s has been switched Off" % name
from ouimeaux.environment import Environment from ouimeaux.signals import statechange, receiver from ouimeaux.device.switch import Switch from ouimeaux.device.lightswitch import LightSwitch env = Environment() env.start() #chiron isn't detecting the switches, so do it manually env._process_device(LightSwitch('http://192.168.0.110:49153/setup.xml')) env._process_device(Switch('http://192.168.0.111:49153/setup.xml')) #print 'discovering' #env.discover(5) switchLight = env.get_switch("Living Room Light") switchWall = env.get_switch("Living Room Wall") @receiver(statechange, sender=switchLight) def switch_toggle(sender, **kwargs): print 'triggered!' switchWall.basicevent.SetBinaryState(BinaryState=kwargs['state']) print 'waiting' env.wait()
import serial, urllib,os,datetime from ouimeaux.environment import Environment from time import gmtime,strftime import httplib, urllib import pyowm import time fh=open("log.txt","a") temp_boost=0.1 env=Environment() env.start() boiler=env.get_switch('Boiler') boiler_state=[] port = serial.Serial("/dev/ttyACM0", baudrate=9600, timeout = 120) boiler_off_temp=0 boiler_on_temp=99 porch=[] landing=[] garden=[] battery='x.xx' print 'starting' while True: error = '' # try: try: rcv = port.read(12) except:
return _urllib.urlopen('http://' + self._ip_address + '/set.cmd?cmd=setpower+p6' + str(self.port) + '=0') def reset(self): self.off() time.sleep(5) self.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")
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()
print nicknames # Switch Acquisition 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() switches=env.list_switches() # switchpair matches names to switch obj switchpair={} for s in switches: if s in devicemap.keys(): switchpair[s]=env.get_switch(s) print switchpair # get ips to look for ips=[] for d in db5.find(): ips.append(d["ip"]) #interval interval = int(sys.argv[1]) #import applications: f=os.listdir("apps") f=[t for t in f if ".py" in t] apps=[] for app in f:
turn_on(sw) elif 'set_state_off' in path: turn_off(sw) elif 'get_state' in path: self.wfile.write(device_state) def log_request(self, code=None, size=None): print('Request') def log_message(self, format, *args): print('Message') if __name__ == "__main__": env = Environment(on_switch) try: env.start() except TypeError: pass sw = env.get_switch('WeMo Switch') try: server = HTTPServer(('', 8091), MyHandler) print('Started http server') server.serve_forever() except KeyboardInterrupt: print('^C received, shutting down server') server.socket.close()
signal.signal(signal.SIGINT, handler) signal.signal(signal.SIGTERM, handler) print 'Discovering WeMo devices...', env = Environment() sys.stdout.flush() env.start() env.discover(5) print 'Done.' switches = env.list_switches() if config['devices']['switches'][0] not in switches: print "Couldn't find switch named '{}'. Discovered switches: {}".format(config['devices']['switches'][0], ', '.join(switches)) sys.exit(1) switch = env.get_switch(config['devices']['switches'][0]) print 'Fetching geolocation...', sys.stdout.flush() geodata = requests.get('http://freegeoip.net/json/').json() location = Location(( geodata['city'], geodata['region_name'], geodata['latitude'], geodata['longitude'], geodata['time_zone'], 0)) print location.name print 'Starting...' last_state, state = UNCONNECTED, UNCONNECTED last_on_time = 0
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: for _ in notches: print("OKAY MOM!") cast.volume_down()
from ouimeaux.environment import Environment def on_switch(switch): print switch.name env = Environment(on_switch, on_switch) env.start() print env.discover() print env.list_switches() switch = env.get_switch('Aeroponics plug') print "State->", switch.get_state() switch.on() print "Turning on:", switch.get_state() env.wait(5) switch.off() print "Turning off:", switch.get_state()
import urllib2 import time from ouimeaux.environment import Environment env = Environment() env.start() env.discover(10) while True: InsightParams=env.get_switch('WeMo Insight').insight.GetInsightParams() InsightParams=str(InsightParams) InsightParamsSplit=InsightParams.split("|") CurrentPower=InsightParamsSplit[7] CurrentPower=float(CurrentPower) CurrentPower=CurrentPower/1000 CurrentPower=str(CurrentPower) print CurrentPower emoncmsURLhosted="http://emoncms.org/input/post.json?node=2&apikey=APIKEY&csv=" PostURL=emoncmsURL + CurrentPower urllib2.urlopen(PostURL).read() time.sleep(1)
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
from ouimeaux.environment import Environment import os import time # Setup GPIO using BCM Numbering GPIO.setmode(GPIO.BCM) buttonPin = 24 currentState = False # Unlocked GPIO.setup(buttonPin, GPIO.IN, pull_up_down=GPIO.PUD_UP) # Setup the WeMo Environment env = Environment() env.start() switch = env.get_switch('eolamp') def lock_unlock(state): if not state: os.system("./lock.py") else: os.system("./unlock.py") return while True: GPIO.wait_for_edge(buttonPin, GPIO.FALLING) timeStarted = time.time() print("Big Red Button pressed") # GPIO.wait_for_edge(buttonPin, GPIO.RISING) while GPIO.input(buttonPin) == 0 and time.time() - timeStarted < 0.5: # Wait some small amount of time.
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() except websockets.ConnectionClosed: print(f"Terminated")
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
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
except: try: self.h = re.search('hour', text).group() #print(self.h) #Debug self.type = ('hour') except: self.type = None env = Environment(on_switch) env.start() '''Show all the WeMo searching stuff''' # env.discover(seconds=3) switch = env.get_switch('Office Heater') switch_name = 'Office Heater' total = len(sys.argv) #print(total) flip = None if total == 2: if str(sys.argv[1]) == ('on'): answer = ('on') flip = True if str(sys.argv[1]) == ('off'): answer = ('off') flip = True elif not total == 4: if switch.get_state() == 0:
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
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()