def __init__(self, num_devices=1, debug=True): self.debug = debug print "initalizing the wemos for %s devices" % (num_devices) self.NUM_DEVICES = num_devices self.switches = {} self.devices = range(0, self.NUM_DEVICES) self.q = Queue() try: self.env = Environment() self.env.start() except: print """ Failed to access internet information. Are you connected to the router wifi?""" sys.exit(1) self.load_switches() if len(self.switches) == 0: print "could not connect any devices. are you on the router wifi?" sys.exit(1) print """ Done connecting devices. Starting asynchronous wemo reloader now!""" self.thread = Thread(target=self.reload_switch_spinner) self.thread.start()
def __init__(self, discovery_seconds=3): super().__init__() self.discovery_seconds = discovery_seconds self.env = Environment() self.env.start() self.refresh_devices()
def __init__(self, config=None, name_set=set(), data_queue=queue.Queue()): threading.Thread.__init__(self) self._name_set = METERS_NAME_SET self._config = config['switch_set_maintainer'] self._config_querier = config['switch_querier'] self._data_queue = data_queue self._env = Environment()
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 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 __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_device(name): env = Environment() # TODO: run from 10am to 10pm env.start() print "Discovering Device" env.discover(5) h = env.get(name) return h
def wemo_off(): env = Environment(on_switch) env.start() env.discover(seconds=1) desk = env.get_switch('Wemo Mini') power_off = desk.off() return power_off
def get_device(name): env = Environment() # TODO: run from 10am to 10pm env.start() print "Discovering Device %s" %name env.discover(8) this_switch = env.get(name) return this_switch
def wemo_main(): print "Start WEMO Daemon." print "Set Environment." #キャッシュを参照しようとすると動作が激重orストップするので参照しない wemo = Environment(with_cache=False) print "Finished init Environment." print "Starting WEMO module." wemo.start() print "Finished." print "Discovering..." wemo.discover(5) print "Finished discovering." print "Get Switch Instances." east = wemo.get_switch("Lab East") west = wemo.get_switch("Lab West") heater = wemo.get_switch("Lab Heater") print "Finished." print "Set GPIO pins." open("/sys/class/gpio/export", "w").write(str(44)) open("/sys/class/gpio/export", "w").write(str(19)) open("/sys/class/gpio/export", "w").write(str(110)) print "All init is finished." print "Start Loop." while True: if int(open("/sys/class/gpio/gpio44/value", "r").read().split("\n")[0]) == 0: #左ボタンが押された時の処理 print "east toggle" east.toggle() print "waiting..." #チャタリングと長押し対策 time.sleep(0.5) continue if int(open("/sys/class/gpio/gpio19/value", "r").read().split("\n")[0]) == 0: #中央ボタンが押された時の処理 print "west toggle" west.toggle() print "waiting..." #チャタリングと長押し対策 time.sleep(0.5) continue if int(open("/sys/class/gpio/gpio110/value", "r").read().split("\n")[0]) == 0: #右ボタンが押された時の処理 print "heater toggle" heater.toggle() print "waiting..." #チャタリングと長押し対策 time.sleep(0.5) continue print "nothing loop" time.sleep(0.2)
def 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.")
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 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 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 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()
def __init__(self): print "Setting up devices for control" #do the config stuff here self.taskConfig = parse("/var/www/html/tasks.xml") self.allTasks = self.taskConfig.getElementsByTagName('task') self.switches = [] self.motions = [] self.env = Environment(self.on_switch, self.on_motion) self.env.start() self.env.discover()
def devices(): try: env = Environment() env.start() env.discover(seconds=3) result = env.list_switches() except: raise return result
def refresh_wemo_devices(): global WEMO_DEVICES WEMO_DEVICES = {} try: env = Environment(found_device, with_subscribers=False, config_filename='./wemo-config.yaml') env.start() env.discover(seconds=5) except Exception as e: logger.error(traceback.format_exc())
def command_switchInfo(m): if m.chat.id in allowedChatIDs: def on_switch(switch): if wemoDevice == switch.name: bot.send_message(m.chat.id, "Switch found! state: %s" % 'ON' if switch.get_state() == 1 else 'OFF') bot.send_message(m.chat.id, "Looking for switch ...") env = Environment(on_switch) env.start() env.discover(seconds=3) else: bot.send_message(m.chat.id, "Sorry. I'm a private bot. I don't want to speak with you")
def __init__(self, callback): self.callback = callback self.motion = False self.env = Environment(with_cache=False) self.event = None receiver(statechange)(self.state) self.mappings = { "zone1": Zone(0, callback), "zone2": Zone(1, callback), "zone3": Zone(2, callback), "zone4": Zone(3, callback) }
def 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 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 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
def command_switchOFF(m): if m.chat.id in allowedChatIDs: def on_switch(switch): if wemoDevice == switch.name: if switch.get_state() == 0: bot.send_message(m.chat.id, "Switch already OFF") else: switch.basicevent.SetBinaryState(BinaryState=0) bot.send_message(m.chat.id, "Switch OFF") bot.send_message(m.chat.id, "Looking for switch ...") env = Environment(on_switch) env.start() env.discover(seconds=3) else: bot.send_message(m.chat.id, "Sorry. I'm a private bot. I don't want to speak with you")
def initialize(bind=None, auth=None): global ENV if ENV is None: ENV = Environment(bind=bind) ENV.start() gevent.spawn(ENV.discover, 10) if auth is not None: elems = auth.split(':', 1) username = elems[0] password = elems[1] print("Protected server with basic auth username/password: ", username, password) app.config['BASIC_AUTH_USERNAME'] = username app.config['BASIC_AUTH_PASSWORD'] = password app.config['BASIC_AUTH_FORCE'] = True basic_auth = BasicAuth(app)
def __init__(self, machine_id, machine_desc, plug_id, plug_desc, plug_type, plug_name, machine_power_threshold): super(MachinePlug_WemoInsight, self).__init__(machine_id, machine_desc, plug_id, plug_desc, plug_type, plug_name, machine_power_threshold) ## create the static/global WEMO environment variable if it doesn't exist if (MachinePlug_WemoInsight.env == 0): MachinePlug_WemoInsight.env = Environment(with_cache=False, bind=None) MachinePlug_WemoInsight.env.start() MachinePlug_WemoInsight.env.discover(3) self.wemo_switch = self.getSwitch(plug_name) logger.debug("switch = " + str(self.wemo_switch))
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 function_one(flag): # Initialization env = Environment() env.start() env.discover(3) b = Bridge('192.168.0.100') b.connect() lights = b.lights groups = b.groups client = MongoClient( 'mongodb://*****:*****@tmega-shard-00-00-kcfpq.mongodb.net:27017,tmega-shard-00-01-kcfpq.mongodb.net:27017,tmega-shard-00-02-kcfpq.mongodb.net:27017/user_info?ssl=true&replicaSet=tmega-shard-0&authSource=admin' ) db_website = client.website # Post button press to API temp_dict = db_website.usrname.find_one({'username': '******'}, {'button_one': ()}) new_value = int(temp_dict['button_one']) + 1 db_website.usrname.update({'username': '******'}, {'$set': { 'button_one': new_value }}, upsert=False) # Bedroom Lights (ON) if flag == 1: b.set_light('lamp 3', 'on', True) b.set_light('lamp 3', {'bri': int(200), 'transitiontime': 1}) b.set_light('lamp 3', 'ct', 197) # Kitchen Lights (ON) if flag == 2: b.set_group('Kitchen', 'on', True) b.set_group('Kitchen', {'bri': int(100), 'transitiontime': 1}) # TV (NONE) if flag == 3: print("TV 1") # Fan (ON) if flag == 4: env.get_switch('office').on() sleep(0.3)
def 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')