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 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'])
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 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 devices(): try: env = Environment() env.start() env.discover(seconds=3) result = env.list_switches() except: raise return result
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 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 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 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 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
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')
def list_switches(): env = Environment(on_switch, on_motion) env.start() env.discover(seconds=1) return env.list_switches()
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(): for entry in config: if light_name == entry.get('wemo light'): light = Light('Garage North', bridge) # FIXME: log print("Found Wemo: {}".format(switch_name))
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
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 requests from ouimeaux.environment import Environment serverurl = "http://128.237.215.125:3000/api/add_schedule_anonymous?" if __name__ == "__main__": print("") 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
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()
from ouimeaux.environment import Environment if __name__ == "__main__": print("") print("WeMo Randomizer") print("---------------") env = Environment() try: env.start() env.discover(3) print(env.list_switches()) print("---------------") wemo = env.get_switch('WeMo Insight Wasp') while True: print("insight.today_kwh: {var}".format(var=wemo.today_kwh)) print("today_on_time: {var}".format(var=wemo.today_on_time)) print("insight.on_for: {var}".format(var=wemo.on_for)) print( "insight.current_power: {var}".format(var=wemo.current_power)) print("insight.today_standby_time: {var}".format( var=wemo.today_standby_time)) print("---------------") env.wait(1) except (KeyboardInterrupt, SystemExit): print("---------------") print("Goodbye!") print("---------------")
#!/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 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 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
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')
TRoom = W1ThermSensor(W1ThermSensor.THERM_SENSOR_DS18B20, TRoomID) # a new DS18B20 sensor 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 ", end=' ') hrf, trf2 = readHumidity(HS1_Pin) print("Room ", end=' ') 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 #######
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()
class WemoSkill(MycroftSkill): # The constructor of the skill, which calls MycroftSkill's constructor def __init__(self): super(WemoSkill, self).__init__(name="WemoSkill") def on_switch(self, switch): LOGGER.debug("Switch detected: %s" % switch.name) self.speak('Discovered a switch named ' + switch.name) def on_motion(self, motion): LOGGER.debug("Motion detected on ", motion.name) # This method loads the files needed for the skill's functioning, and # creates and registers each intent that the skill uses 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) def __register_prefixed_regex(self, prefixes, suffix_regex): for prefix in prefixes: self.register_regex(prefix + ' ' + suffix_regex) def handle_wemo_switch_intent(self, message): togglewords = message.data.get("ToggleWords") try: device = self.env.get_switch(togglewords) device.toggle() except: LOGGER.debug("Unknown WeMo device: ", togglewords) self.speak("I don't know a device called ", togglewords) def handle_wemo_list_intent(self, message): # listwords are the type of thing you want to list # like "mycroft list switches" listwords = message.data.get("ListWords") LOGGER.debug("Wemo list") LOGGER.debug(listwords) try: self.env.start() switches = self.env.list_switches() LOGGER.debug("Wemo switches:") LOGGER.debug(switches) num_switches = len(switches) if num_switches > 0: self.speak("I found " + str(num_switches) + " wemo switches.") else: self.speak("I didn't find any wemo switches") for switch in switches: self.speak(switch) except Exception as e: LOGGER.debug("Error occurred listing Wemo switches: " + e.message) LOGGER.debug(e) self.speak("uh. ah.") 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.") # 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, the method just contains the keyword "pass", which # does nothing. def stop(self): pass
$ 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")
# 2_7_Client.py # 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')
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
# wemo setup via ouimeax package env = Environment() env.start() env.discover() # Names of current CT switches for reference # dev_switch = env.get_switch('wemo-dev') # cs_switch = env.get_switch('wemo-cs') # get Slack API token slack_api_token = os.environ['SLACK_API_TOKEN'] firestatus = False print "Starting Slack API check for fire channel! Switches:" lan_switches = env.list_switches() for sw in lan_switches: print sw channels_api_url = 'https://slack.com/api/channels.list?token=%s&pretty=1' % slack_api_token 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
# TS = W1ThermSensor(W1ThermSensor.THERM_SENSOR_DS18B20,'0008006b3137') TRoom = W1ThermSensor(W1ThermSensor.THERM_SENSOR_DS18B20,TRoomID) # a new DS18B20 sensor 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
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()
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
for d in db4.find(): devicemap[d['name']] = [int(d['level']),d['nick']] print devicemap nicknames={} for d in db4.find(): nicknames[d['nick']] = d['name'] 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 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()
running = True def handler(signum, frame): global running running = False 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 "WeMo Randomizer" print "---------------" env = Environment() # TODO: run from 10am to 10pm env.start() env.discover(seconds=3) time.sleep(3) #reading Config files setting configParser = ConfigParser.RawConfigParser() configFilePath = r'config.ini' 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
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()
class LocalNetworkWemoFetcher: def __init__(self,config_params): # We will use an in-memory database & table to store and aggregate our data we've pulled from our WeMo devices self.dbfile = str(uuid.uuid4()) + ".db" self.db = sqlite3.connect(self.dbfile) self.cur = self.db.cursor() # This function will create the database to store our WeMo device data; # since this is a simple example, it`s just one table: self.cur.execute('''CREATE TABLE switchDataPoints ( MACAddress TEXT, IPAddress TEXT, SignalStrength INTEGER, SerialNbr TEXT, ModelNbr TEXT, FirmwareVersion TEXT, DeviceName TEXT, Status INTEGER, EnergyUse INTEGER, DateDataFetched DATE )''' ) self.cur.execute('''CREATE TABLE averagedDataPoints ( MACAddress TEXT, IPAddress TEXT, SignalStrength INTEGER, SerialNbr TEXT, ModelNbr TEXT, FirmwareVersion TEXT, DeviceName TEXT, Status INTEGER, AvgEnergyUse INTEGER, CountDataPoints INTEGER, DateDataFetched DATE )''' ) self.config = config_params self.wemoenvironment = None # we will construct and destruct this elsewhere 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)) def getDeviceHardwareIDs(self, environment): current_switches = self.wemoenvironment.list_switches() if current_switches.__len__() == 0: logging.exception("No devices exist in ouimeaux environment; cannot fetch hardware data") raise NameError("No ouimeaux environment data exists!") devicehardwaredata = [] for switchStr in (self.wemoenvironment.list_switches()): currentswitch = self.wemoenvironment.get_switch(switchStr) dict_switchinfo = currentswitch.basicevent.GetMacAddr() switchmac = dict_switchinfo.get("MacAddr") switchudnlowercase = dict_switchinfo.get("PluginUDN").lower() dict_switchfirmwareversion = currentswitch.firmwareupdate.GetFirmwareVersion() switchfirmwareversion = dict_switchfirmwareversion.get("FirmwareVersion") switchipaddress = currentswitch.host switchserialnumber = currentswitch.serialnumber switchmodelnbr = currentswitch.model dict_currentswitchattributes = { "Device Name": switchStr, "MAC Address": switchmac, "Universal Unique Identifier": switchudnlowercase, "Firmware Version": switchfirmwareversion, "IP Address": switchipaddress, "Serial Number": switchserialnumber, "Model Number": switchmodelnbr } devicehardwaredata.append( dict_currentswitchattributes ) return devicehardwaredata def closeconnection(self): #Call this after ensuring data has been captured so that the temp db file is destroyed self.db.close() os.remove(self.dbfile) def fetchdevicedata(self): # print(Environment.list_switches()) #DEBUG: See what devices we grabbed during discovery switchPowerDataArray = [] # We will store a list of power measurements in this list and then average them before sending them to a flat file or database (we don`t need 300 measurements per minute stored in the database; it should be flattened out) # Fetch the current date/time into a variable, then find the date/time one minute from now; we'll use that currentDateTime = datetime.datetime.now() minuteFromNow = currentDateTime - datetime.timedelta(minutes=(-1 * self.config.get("Minutes to Gather Data"))) currentLoopIteration = 0 # We will only gather the switch hardware / firmware details at the first iteration of fetching power data; no need to get it multiple times during execution deviceHardwareData = self.getDeviceHardwareIDs(self.wemoenvironment) while datetime.datetime.now() <= minuteFromNow: for wemoDevice in (deviceHardwareData): currentSwitch = self.wemoenvironment.get_switch(wemoDevice.get("Device Name")) print(currentSwitch) switchsignalstrength = currentSwitch.basicevent.GetSignalStrength() switchcurrentbinarystate = currentSwitch.basicevent.GetBinaryState() switchhwinfo = currentSwitch.metainfo.GetMetaInfo() switchmanufacture= currentSwitch.manufacture.GetManufactureData() if currentSwitch.model.find('Insight') > 0: if currentSwitch.insight_params.get("state") == 0: #API sometimes show power usage when turned off; force usage to zero when off switchpowerconsumption = 0 else: switchpowerconsumption = currentSwitch.current_power switchcurrentstate = currentSwitch.insight_params.get("state") datatoinsert = ( wemoDevice.get("MAC Address"), wemoDevice.get("IP Address"), float(switchsignalstrength.get("SignalStrength")), wemoDevice.get("Serial Number"), wemoDevice.get("Model Number"), wemoDevice.get("Firmware Version"), wemoDevice.get("Device Name"), int(switchcurrentbinarystate.get("BinaryState")), switchpowerconsumption ) logging.info(datatoinsert) self.cur.execute( '''INSERT INTO switchDataPoints( MACAddress , IPAddress , SignalStrength , SerialNbr , ModelNbr , FirmwareVersion , DeviceName , Status , EnergyUse , DateDataFetched ) VALUES (?,?,?,?,?,?,?,?,?, datetime('now'))''', datatoinsert) # This method must iterate through the list and replace the variables (?'s) in the INSERT statement from left to right self.db.commit() self.wemoenvironment.wait(self.config.get("Delay in Seconds When Fetching Data")) derp = 2 def aggregateusagedata(self): self.cur.execute( '''INSERT INTO averagedDataPoints SELECT MACAddress , MAX(IPAddress) AS IPAddress , MIN(SignalStrength) AS SignalStrength , SerialNbr , MAX(ModelNbr) AS ModelNbr , MAX(FirmwareVersion) AS FirmwareVersion , DeviceName AS DeviceName , MAX(Status) AS Status , AVG(EnergyUse) AS EnergyUse , COUNT(0) AS DataPointsCollected , datetime('now') AS DataPulledDate FROM switchDataPoints GROUP BY MACAddress, SerialNbr, DeviceName ''' ) self.db.commit() self.cur.execute( # Clear the ongoing log as we've already summarized and stored the averaged usage data '''DELETE FROM switchDataPoints''' ) tablequery = '''SELECT ROWID ,MACAddress ,IPAddress ,SignalStrength ,SerialNbr ,ModelNbr ,FirmwareVersion ,DeviceName ,Status ,AvgEnergyUse ,CountDataPoints ,DateDataFetched FROM averagedDataPoints''' returnusagedata = [] for dataRow in self.cur.execute(tablequery): rowdict = { "SQLite3 - averagedDataPoints Row ID": dataRow[0] ,"MAC Address": dataRow[1] ,"IP Address": dataRow[2] ,"Signal Strength": dataRow[3] , "Serial Number": dataRow[4] , "Model Number": dataRow[5] , "Firmware Version": dataRow[6] , "Device Name": dataRow[7] , "Device Status": dataRow[8] , "Average Energy Usage": dataRow[9] , "Data Points Collected": dataRow[10] , "Date Stamp for Data": dataRow[11] } returnusagedata.append(rowdict) return returnusagedata def InsertOrUpdateDatabase(self,currentDataSet): try: #Connect to the MS SQL Server instance the database application is stored: mssqldb = pymssql.connect( self.config.get("server_ip") , self.config.get("serviceaccount") , self.config.get("db_password") , self.config.get("databasename") ) mssqlcursor = mssqldb.cursor() for currentDataRow in currentDataSet: print("Beginning work in MS SQL Server for ", currentDataRow.get("Device Name")) #First, we need to fill the lookup tables before we can start filling the tables with FK's to the lookups: mssqlcursor.execute(""" MERGE INTO dbo.deviceFirmware AS target USING (SELECT %s AS firmwareName ) AS source (firmwareName) ON (target.firmwareName = source.firmwareName) WHEN MATCHED THEN UPDATE SET target.firmwareName = source.firmwareName WHEN NOT MATCHED THEN INSERT (firmwareName) VALUES(source.firmwareName) OUTPUT inserted.[deviceFirmwareSK] --This will return the new or fetched SK back to the calling client (Yay!!) ; """,currentDataRow.get("Firmware Version")) #http://stackoverflow.com/questions/3410455/how-do-i-use-sql-parameters-with-python currentFirmwareSK = mssqlcursor.fetchone() mssqlcursor.execute(""" MERGE INTO dbo.networkMetadata AS target USING (SELECT %s AS ipAddress ,%s AS tcpIPversion ) AS source (ipAddress, tcpIPversion) ON (target.ipAddress = source.ipAddress) WHEN MATCHED THEN UPDATE SET target.ipAddress = source.ipAddress, target.tcpIPversion = source.tcpIPversion WHEN NOT MATCHED THEN INSERT (ipAddress, tcpIPversion) VALUES(source.ipAddress, source.tcpIPversion) OUTPUT inserted.[networkMetadataSK] ; """,(currentDataRow.get("IP Address"),'IPv4')) currentNetworkMetadataSK = mssqlcursor.fetchone() mssqlcursor.execute(""" MERGE INTO dbo.deviceTypes AS target USING (SELECT %s AS deviceTypeLabel ) AS source (deviceTypeLabel) ON (target.deviceTypeLabel = source.deviceTypeLabel) WHEN MATCHED THEN UPDATE SET target.deviceTypeLabel= source.deviceTypeLabel WHEN NOT MATCHED THEN INSERT (deviceTypeLabel) VALUES(source.deviceTypeLabel) OUTPUT inserted.[deviceTypeSK] ; """,(currentDataRow.get("Model Number"))) currentDeviceTypeSK = mssqlcursor.fetchone() #Now that we have the SK's for our lookups, upsert into the IoTDevice table: mssqlcursor.execute(""" MERGE INTO dbo.IoTDevice AS target USING (SELECT %s AS macAddress ,%s AS serialNumber ,%s AS friendlyName ,%s AS deviceTypeFK ,%s AS deviceFirmwareFK ,%s AS deviceIPAddressFK ,0 AS retiredDevice --If this merge statment is being called from the python app, then obviously the device is active ) AS source ( macAddress ,serialNumber ,friendlyName ,deviceTypeFK ,deviceFirmwareFK ,deviceIPAddressFK ,retiredDevice ) ON ( target.macAddress = source.macAddress AND target.serialNumber = source.serialNumber ) --Honestly, this is bad code; you should likely return a SELECT to the application to see if an UPDATE is necessary. This will UPDATE a device record every time the application has data from a device. Lots and lots of unnecessary writes. WHEN MATCHED THEN UPDATE SET target.macAddress = source.macAddress , target.serialNumber = source.serialNumber , target.friendlyName = source.friendlyName , target.deviceTypeFK = source.deviceTypeFK , target.deviceFirmwareFK = source.deviceFirmwareFK , target.deviceIPAddressFK = source.deviceIPAddressFK , target.retiredDevice = source.retiredDevice , target.deviceChangedDate = getdate() WHEN NOT MATCHED THEN INSERT ( macAddress ,serialNumber ,friendlyName ,deviceTypeFK ,deviceFirmwareFK ,deviceIPAddressFK ,retiredDevice ,deviceChangedDate ) VALUES( source.macAddress , source.serialNumber , source.friendlyName , source.deviceTypeFK , source.deviceFirmwareFK , source.deviceIPAddressFK , source.retiredDevice , getDate() ) OUTPUT inserted.[deviceSK] ; """,(currentDataRow.get("MAC Address"),currentDataRow.get("Serial Number"),currentDataRow.get("Device Name"),currentDeviceTypeSK,currentFirmwareSK,currentNetworkMetadataSK)) currentDeviceSK = mssqlcursor.fetchone() mssqlcursor.execute(""" MERGE INTO dbo.powerScales AS target USING (SELECT %s AS unitOfPower ) AS source (unitOfPower) ON (target.unitOfPower = source.unitOfPower) WHEN MATCHED THEN UPDATE SET target.unitOfPower = source.unitOfPower ,target.scaleChangedDate = getdate() WHEN NOT MATCHED THEN INSERT (unitOfPower, scaleAddedDate) VALUES(source.unitOfPower, getdate()) OUTPUT inserted.powerScaleSK ; """,('Milliwatt')) currentPowerScaleSK = mssqlcursor.fetchone() mssqlcursor.execute(""" MERGE INTO dbo.statusList AS target USING (SELECT %s AS statusNumberRepresentation ,%s AS sourceSystem ) AS source (statusNumberRepresentation, sourceSystem) ON ( target.statusNumberRepresentation = source.statusNumberRepresentation AND target.sourceSystem = source.sourceSystem ) WHEN MATCHED THEN UPDATE SET target.statusNumberRepresentation = source.statusNumberRepresentation ,target.sourceSystem = source.sourceSystem ,target.statusChangedDate = getdate() WHEN NOT MATCHED THEN INSERT (statusNumberRepresentation, sourceSystem, statusAddedDate) VALUES(source.statusNumberRepresentation, source.sourceSystem, getdate()) OUTPUT inserted.statusSK ; """,(currentDataRow.get("Device Status"),'OuimeauxPython')) currentstatusSK = mssqlcursor.fetchone() #Now that we've filled all the lookup tables for the device itself, we can store the usage data for that device (after ensuring that mssqlcursor.execute(""" INSERT INTO dbo.deviceUsageData ( deviceFK ,deviceSignalStrength ,deviceStateFK ,devicePowerUsage ,devicePowerScaleFK ,dataPointSampleSize ,dataPointAddedDate ) VALUES( %s ,%s ,%s ,%s ,%s ,%s ,getdate() ) ; """,(currentDeviceSK, currentDataRow.get("Signal Strength"), currentstatusSK, currentDataRow.get("Average Energy Usage"), currentPowerScaleSK, currentDataRow.get("Data Points Collected"))) mssqlcursor.execute(""" COMMIT; """ ) mssqldb.commit() self.cur.execute("DELETE FROM averagedDataPoints WHERE ROWID = ?", (int(currentDataRow.get("SQLite3 - averagedDataPoints Row ID")),)) mssqldb.close() #end of for loop per device except Exception as e: logging.warning("ERROR IN LOADING DATABASE WITH CACHED DATA: " + str(e.message)) raise #Ideally, error handling should fill an in-memory python buffer that is flushed into the DB when the exception state clears, but this is a home project for data that has little value (unlike, say, money changing hands), so meh. print("Finished with MS SQL Server work!")
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() except websockets.ConnectionClosed:
os.system("rm ~/.wemo/cache") print "" print "WeMo Randomizer" print "---------------" env = Environment() # TODO: run from 10am to 10pm env.start() env.discover(seconds=3) time.sleep(3) #reading Config files setting configParser = ConfigParser.RawConfigParser() configFilePath = r'config.ini' 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
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 for switch in ( env.list_switches() ):
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 for switch in (env.list_switches()):
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 # http://pydoc.net/Python/ouimeaux/0.7.3/ouimeaux.examples.watch/ if __name__ == "__main__": print "" print "---------------" env = Environment() # TODO: run from 10am to 10pm try: print "calling env.start()" env.start() print "calling env.discover()" env.discover(15) print "listing switches" 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 "calling get_switch()" switchRND = env.get_switch("WEMO CNC ROOM") print switchRND power = switchRND.current_power print "turning off" switchRND.basicevent.SetBinaryState(BinaryState=0) print "turning on" switchRND.basicevent.SetBinaryState(BinaryState=1) #switchRND.explain() print switchRND.deviceinfo.GetDeviceInformation()