Beispiel #1
0
	def readNest(cls):
		line = input().split()
		nest = Nest()
		while line[0] != 'END':
			cmd = line[0]
			args = line[1:]
			if cmd == 'STOCK':
				qtt = args[0]
				qtt = int(qtt)
				nest.setFood(qtt)

			elif cmd == 'MEMORY':
				tab_mem = [int(v) for v in args]
				nest.setMemory(tab_mem)

			elif cmd == 'ANT_COUNT':
				typ, qtt = [int(v) for v in args]
				nest.setAntCount(typ, qtt)

			elif cmd == 'ANT_IN':
				typ, m1, m2 = [int(v) for v in args]
				nest.setAntIn(typ, m1, m2)

			line = input().split()

		return nest
Beispiel #2
0
 def set_the_temp(self, message, temp):
     temp = int(temp)
     nest = Nest(
         username=settings.NEST_USERNAME,
         password=settings.NEST_PASSWORD,
         serial=settings.NEST_SERIAL,
         units="F",
     )
     nest.login()
     nest.set_temperature(temp)
     self.reply(message, "Done. I set the temp to %sF." % temp)
Beispiel #3
0
class AppServer(object):
    def __init__(self, app):
        self.app = app
        self.thread = None

    def run(self):
        self.nest = Nest(app=self.app, port=12345)
        self.thread = Thread(target=self.nest.run)
        self.thread.start()
        time.sleep(0.5)

    def stop(self):
        self.nest.shutdown()
        self.thread.join()
Beispiel #4
0
def nest():
    #Nest
    try:
        un = settings.NEST_USERNAME
        pw = settings.NEST_PASSWORD
        n = Nest(un, pw)
        n.login()
        n.get_status()
        logging.info("Current Temperature: {}".format(n.show_curtemp()))
        it = TimeSeriesMetric('indoor-temperature', n.show_curtemp()).save()
        logging.info("Current Humidity: {}".format(n.show_curhumidity()))
        ih = TimeSeriesMetric('indoor-humidity', n.show_curhumidity()).save()
    except Exception as e:
        logging.exception(e)
Beispiel #5
0
def main():
    log.info('Start process the gallery...')
    horcrux = Album(conf.PHOTOS_PATH, 'Horcrux', 0)
    config = horcrux.format()
    log.info('Now writing the config file to ' + str(conf.HORCRUX_PATH))
    conf.write_json(conf.HORCRUX_PATH, config)
    Nest().main()
    log.ok('Success! Enjoy~')
Beispiel #6
0
def nest():
    #Nest
    try:
        un = settings.NEST_USERNAME
        pw = settings.NEST_PASSWORD
        n = Nest(un, pw)
        n.login()
        n.get_status()
        logging.info("Current Temperature: {}".format(n.show_curtemp()))
        it = TimeSeriesMetric('indoor-temperature', n.show_curtemp()).save()
        logging.info("Current Humidity: {}".format(n.show_curhumidity()))
        ih = TimeSeriesMetric('indoor-humidity', n.show_curhumidity()).save()
    except Exception as e:
        logging.exception(e)
Beispiel #7
0
 def __init__(self):
     global logger
     logger = logging.getLogger(__name__)
     # connect to nest
     try:
         from nest import Nest
         self.nest = Nest(username=settings.NEST_LOGIN,
                          password=settings.NEST_PASS)
         self.nest.login()
         self.nest.get_status()
     except:
         logger.error("Unable to connect to NEST.")
     # connect to phillips hue
     self.bridge = Bridge(settings.HUE_BRIDGE)
     try:
         self.bridge.connect()
         self.bridge.get_api()
     except:
         logger.error("Unable to connect to Hue.")
Beispiel #8
0
def main():
    try:
        c = configparser.ConfigParser()
        c.read(
            os.path.join(os.path.abspath(os.path.dirname(__file__)),
                         '../frontend/conf', 'settings.ini'))

        # Setup Nest account
        n = Nest(c['nest']['nest_username'],
                 c['nest']['nest_password'],
                 c['nest']['nest_sn'],
                 c['nest']['nest_index'],
                 units=c['common']['units'])
        n.login()
        n.get_status()
        # Setup OpenWeatherMap account
        owm = pyowm.OWM(c['owm']['owm_id'])
        observation = owm.weather_at_place(c['owm']['owm_city'])
        w = observation.get_weather()
        # Connect to DB
        cnx = mysql.connector.connect(user=c['mysql']['mysql_username'],
                                      password=c['mysql']['mysql_password'],
                                      host=c['mysql']['mysql_hostname'],
                                      database=c['mysql']['mysql_database'])
        d = cnx.cursor()
        polling(c, n, w, d)
        cnx.commit()
        d.close()
    except Exception:
        print(sys.exc_info()[1])
Beispiel #9
0
def main():
    try:
        c = configparser.ConfigParser()
        c.read(
            os.path.join(os.path.abspath(os.path.dirname(__file__)),
                         '../frontend/conf', 'settings.ini'))

        # Setup Nest account
        n = Nest(c['nest']['nest_username'],
                 c['nest']['nest_password'],
                 c['nest']['nest_sn'],
                 c['nest']['nest_index'],
                 units=c['common']['units'])
        n.login()
        n.get_status()

        ds = forecast(c['darksky']['api_key'], c.getfloat('darksky', 'lat'),
                      c.getfloat('darksky', 'long'))

        observation = ds['currently']

        w = observation

        # Connect to DB
        cnx = mysql.connector.connect(user=c['mysql']['mysql_username'],
                                      password=c['mysql']['mysql_password'],
                                      host=c['mysql']['mysql_hostname'],
                                      database=c['mysql']['mysql_database'])
        d = cnx.cursor()
        polling(c, n, w, d)
        cnx.commit()
        d.close()
    except Exception:
        print(sys.exc_info()[1])
Beispiel #10
0
def main():
    options = _parse()

    if options.debug:
        import logging
        fmt = (
            '\033[36m%(asctime)-24s \033[34m%(name)-16s '
            '\033[32m%(levelname)-8s \033[97m%(message)s\033[39m'
        )
        logging.basicConfig(format=fmt, level=logging.INFO)

    module, app = options.app.split(':')
    module = importlib.import_module(module)
    app = getattr(module, app)

    kwargs = dict(
        app=app,
        host=options.host,
        port=options.port,
        auto_reload=options.auto_reload
    )
    nest = Nest(**kwargs)
    try:
        nest.run()
    except KeyboardInterrupt:
        print('Exiting...')
        nest.shutdown()
Beispiel #11
0
 def set_the_temp(self, message, temp):
     temp = int(temp)
     nest = Nest(
         username=settings.NEST_USERNAME,
         password=settings.NEST_PASSWORD,
         serial=settings.NEST_SERIAL,
         units="F",
     )
     nest.login()
     nest.set_temperature(temp)
     self.reply(message, "Done. I set the temp to %sF." % temp)
Beispiel #12
0
def run():
    from nest import Nest
    from drongo_app.app import app

    os.environ['DRONGO_SETTINGS_FILE'] = os.path.realpath(sys.argv[1])

    server = Nest(app=app)
    try:
        server.run()
    except KeyboardInterrupt:
        print('Terminating...')
        server.shutdown()
Beispiel #13
0
def main():

    nest_username = settings['nest_username']
    nest_password = settings['nest_password']
    db_username = settings['db_username']
    db_password = settings['db_password']
    db_name = settings['db_name']
    db_host = settings['db_host']
    db_port = settings['db_port']
    db_table = settings['db_table']

    n = Nest(nest_username, nest_password)
    n.login()
    n.get_status()

    d = Database(db_username, db_password, db_name, db_host, db_port, db_table)
    d.persist(n.show_status())
Beispiel #14
0
 def get_the_temp(self, message):
     nest = Nest(
         username=settings.NEST_USERNAME,
         password=settings.NEST_PASSWORD,
         serial=settings.NEST_SERIAL,
         units="F",
     )
     nest.login()
     nest.get_status()
     context = {
         "current_temp": nest.temp_out(nest.status['shared'][nest.serial]['current_temperature']),
         "target_temp": nest.temp_out(nest.status['shared'][nest.serial]['target_temperature']),
         "current_humidity": nest.status['device'][nest.serial]['current_humidity'],
         "is_on": nest.status['shared'][nest.serial]['hvac_heater_state'],
     }
     status_text = rendered_template("house_status.html", context)
     self.reply(message, status_text, html=True)
Beispiel #15
0
def run_dev():
    LOGGING_FORMAT = ('\033[36m%(asctime)-24s \033[34m%(name)-16s '
                      '\033[32m%(levelname)-8s \033[97m%(message)s\033[39m')
    logging.basicConfig(format=LOGGING_FORMAT, level=logging.INFO)

    os.environ['DRONGO_SETTINGS_FILE'] = os.path.realpath(sys.argv[1])
    from nest import Nest
    from drongo_app.app import app

    server = Nest(app=app, auto_reload=True)
    try:
        server.run()
    except KeyboardInterrupt:
        print('Terminating...')
        server.shutdown()
Beispiel #16
0
async def async_setup(hass, config):
    """Set up Nest components."""
    from nest import Nest

    if 'nest' in _CONFIGURING:
        return

    conf = config[DOMAIN]
    client_id = conf[CONF_CLIENT_ID]
    client_secret = conf[CONF_CLIENT_SECRET]
    filename = config.get(CONF_FILENAME, NEST_CONFIG_FILE)

    access_token_cache_file = hass.config.path(filename)

    nest = Nest(access_token_cache_file=access_token_cache_file,
                client_id=client_id,
                client_secret=client_secret)

    await async_setup_nest(hass, nest, config)

    return True
Beispiel #17
0
 def get_the_temp(self, message):
     nest = Nest(
         username=settings.NEST_USERNAME,
         password=settings.NEST_PASSWORD,
         serial=settings.NEST_SERIAL,
         units="F",
     )
     nest.login()
     nest.get_status()
     context = {
         "current_temp":
         nest.temp_out(
             nest.status['shared'][nest.serial]['current_temperature']),
         "target_temp":
         nest.temp_out(
             nest.status['shared'][nest.serial]['target_temperature']),
         "current_humidity":
         nest.status['device'][nest.serial]['current_humidity'],
         "is_on":
         nest.status['shared'][nest.serial]['hvac_heater_state'],
     }
     status_text = rendered_template("house_status.html", context)
     self.reply(message, status_text, html=True)
Beispiel #18
0
 def __init__(self):
     global logger
     logger = logging.getLogger(__name__)
     # connect to nest
     self.nest = Nest(
         username=settings.NEST_LOGIN,
         password=settings.NEST_PASS
     )
     try:
         self.nest.login()
         self.nest.get_status()
     except:
         logger.error("Unable to connect to NEST.")
     # connect to phillips hue
     self.bridge = Bridge(
         settings.HUE_BRIDGE
     )
     try:
         self.bridge.connect()
         self.bridge.get_api()
     except:
         logger.error("Unable to connect to Hue.")
Beispiel #19
0
def nest_usage():
    #Nest Usage
    print "woot"
    try:
        un = settings.NEST_USERNAME
        pw = settings.NEST_PASSWORD
        n = Nest(un, pw)
        n.login()
        n.get_status()
        usage = n.get_usage()
        for day in usage:
            for k, cycles in usage[day].iteritems():
                for use in cycles:
                    logging.info("{} ran at: {} for {}".format(
                        k, use['timestamp'], use['duration']))
                    it = TimeSeriesMetric('{}-usage'.format(k),
                                          use['duration'],
                                          use['timestamp']).save()
    except Exception as e:
        logging.exception(e)
Beispiel #20
0
def main():

    nest_username = settings['nest_username']
    nest_password = settings['nest_password']
    db_username = settings['db_username']
    db_password = settings['db_password']
    db_name = settings['db_name']
    db_host = settings['db_host']
    db_port = settings['db_port']
    db_table = settings['db_table']

    n = Nest(nest_username, nest_password)
    n.login()
    n.get_status()

    d = Database(db_username, db_password, db_name, db_host, db_port, db_table)
    d.persist(n.show_status())
Beispiel #21
0
def nest_usage():
    #Nest Usage
    print "woot"
    try:
        un = settings.NEST_USERNAME
        pw = settings.NEST_PASSWORD
        n = Nest(un, pw)
        n.login()
        n.get_status()
        usage = n.get_usage()
        for day in usage:          
            for k, cycles in usage[day].iteritems():
                for use in cycles:
                    logging.info("{} ran at: {} for {}".format(k, use['timestamp'], use['duration']))
                    it = TimeSeriesMetric('{}-usage'.format(k), use['duration'], use['timestamp']).save()
    except Exception as e:
        logging.exception(e)
Beispiel #22
0
def main():
    #Setup Nest account
    n = Nest(NEST_ID, NEST_PWD, NEST_SN, 0, "C")
    n.login()
    n.get_status()
    # Setup OpenWeatherMap account
    owm = pyowm.OWM(OWM)
    observation = owm.weather_at_place(OWM_CITY)
    w = observation.get_weather()
    # Connect to DB
    cnx = mysql.connector.connect(user=DB_USER,
                                  password=DB_PWD,
                                  host=DB_HOST,
                                  database=DB_NAME)
    d = cnx.cursor()
    polling(n, w, d)
    cnx.commit()
    d.close()
Beispiel #23
0
def main():
    options = _parse()
    module, app = options.app.split(':')
    module = importlib.import_module(module)
    app = getattr(module, app)

    kwargs = dict(
        app=app,
        host=options.host,
        port=options.port,
        auto_reload=options.auto_reload
    )
    nest = Nest(**kwargs)
    try:
        nest.run()
    except KeyboardInterrupt:
        print('Exiting...')
        nest.shutdown()
Beispiel #24
0
def main():
    parser = create_parser()
    (opts, args) = parser.parse_args()

    if (len(args)==0) or (args[0]=="help"):
        help()
        sys.exit(-1)

    if (not opts.user) or (not opts.password):
        print "how about specifying a --user and --password option next time?"
        sys.exit(-1)

    if opts.celsius:
        units = "C"
    else:
        units = "F"

    n = Nest(opts.user, opts.password, opts.serial, opts.index, units=units)
    n.login()
    n.get_status()

    cmd = args[0]

    if (cmd == "temp"):
        if len(args)<2:
            print "please specify a temperature"
            sys.exit(-1)
        n.set_temperature(int(args[1]))
    elif (cmd == "fan"):
        if len(args)<2:
            print "please specify a fan state of 'on' or 'auto'"
            sys.exit(-1)
        n.set_fan(args[1])
    elif (cmd == "show"):
        n.show_status()
    elif (cmd == "curtemp"):
        n.show_curtemp()
    elif (cmd == "curhumid"):
        print n.status["device"][n.serial]["current_humidity"]
    else:
        print "misunderstood command:", cmd
        print "do 'nest.py help' for help"
Beispiel #25
0
def main():
    parser = create_parser()
    (opts, args) = parser.parse_args()

    if (len(args) == 0) or (args[0] == "help"):
        help()
        sys.exit(-1)

    if (not opts.user) or (not opts.password):
        print "how about specifying a --user and --password option next time?"
        sys.exit(-1)

    if opts.celsius:
        units = "C"
    else:
        units = "F"

    n = Nest(opts.user, opts.password, opts.serial, opts.index, units=units)
    n.login()
    n.get_status()

    cmd = args[0]

    if (cmd == "temp"):
        if len(args) < 2:
            print "please specify a temperature"
            sys.exit(-1)
        n.set_temperature(int(args[1]))
    elif (cmd == "fan"):
        if len(args) < 2:
            print "please specify a fan state of 'on' or 'auto'"
            sys.exit(-1)
        n.set_fan(args[1])
    elif (cmd == "show"):
        n.show_status()
    elif (cmd == "curtemp"):
        n.show_curtemp()
    elif (cmd == "curhumid"):
        print n.status["device"][n.serial]["current_humidity"]
    else:
        print "misunderstood command:", cmd
        print "do 'nest.py help' for help"
Beispiel #26
0
class Control:
    nest = None
    bridge = None

    def __init__(self):
        global logger
        logger = logging.getLogger(__name__)
        # connect to nest
        try:
            from nest import Nest
            self.nest = Nest(
                username=settings.NEST_LOGIN,
                password=settings.NEST_PASS
            )
            self.nest.login()
            self.nest.get_status()
        except:
            logger.error("Unable to connect to NEST.")
        # connect to phillips hue
        self.bridge = Bridge(
            settings.HUE_BRIDGE
        )
        try:
            self.bridge.connect()
            self.bridge.get_api()
        except:
            logger.error("Unable to connect to Hue.")

    def execute_command(self, command):
        if command.action == 'power':
            light_state = (command.value == 'on')
            for light_index in settings.LIGHT_GROUPS[command.room]:
                logger.debug('Setting light %s: %s' % (
                    str(light_index),
                    str(light_state)
                ))
                self.bridge.set_light(light_index, 'on', light_state)
                if light_state:
                    # reset color
                    self.bridge.set_light(light_index, 'hue', 15331)
                    self.bridge.set_light(light_index, 'sat', 121)
            return True
        elif command.action == 'dim':
            for light_index in settings.LIGHT_GROUPS[command.room]:
                brightness = int(255 * (command.value*0.1))
                logger.debug('Setting bright %s: %s' % (
                    str(light_index),
                    str(brightness)
                ))
                self.bridge.set_light(light_index, 'bri', brightness)
            return True
        elif command.action == 'hue':
            curr_group = settings.LIGHT_GROUPS[command.room]
            for index, light_index in enumerate(curr_group):
                # iterates over each color for fades, gradients,etc
                value = command.value[index % len(command.value)]
                logger.debug('Setting hue %s: %s' % (
                    str(light_index), value
                ))
                self.bridge.set_light(light_index, 'on', True)
                self.bridge.set_light(light_index, 'hue', value)
                self.bridge.set_light(light_index, 'sat', 255)
            return True
        elif command.action == 'temperature':
            if not self.nest:
                logger.error('Nest thermostat not initialized.')
                return False
            if command.value:
                self.nest.set_temperature(command.value)
                return True
            else:
                logger.error('Could not determine a temperature.')
        return False
Beispiel #27
0
 def run(self):
     self.nest = Nest(app=self.app, port=12345)
     self.thread = Thread(target=self.nest.run)
     self.thread.start()
     time.sleep(0.5)
Beispiel #28
0
 def initialize(self):
     self.nest = Nest(NEST_USER, NEST_PASSWD)
Beispiel #29
0
        return os.path.exists(self.filename)


if __name__ == '__main__':
    if len(sys.argv) < 2:
        print('Missing argument: get / set')
        sys.exit(1)

    cfg_file = ConfigFile()
    config = None
    if cfg_file.exists():
        config = cfg_file.read()

    nest = None
    if config and 'access_token' in config:
        nest = Nest(access_token=config['access_token'])
    else:
        authorize()
        code = input("Enter code: ")
        nest = Nest(code=code)
        config = {'access_token': nest.access_token}
        cfg_file.write(config)

    thermostat = None
    if 'thermostat_id' in config:
        thermostat = nest.get_thermostat(config['thermostat_id'])
    else:
        thermostat = nest.get_thermostat()
        config['thermostat_id'] = thermostat.device_id
        cfg_file.write(config)
Beispiel #30
0
            'smoke_sequence_number': protect.smoke_sequence_number,
            'wired_or_battery': protect.wired_or_battery
            }
    }]

    return event


with shApp('nest', config_defaults=defaults) as app:
    app.run()

    handler = shEventHandler(app)

    nest = Nest(app.config.get('nest', 'nest_user'),
                app.config.get('nest', 'nest_pass'),
                access_token_cache_file=os.path.expanduser(
                    app.config.get('nest', 'nest_cache')),
                cache_ttl=9)

    while True:
        retries = 0

        # app.log.info(json.dumps(nest._status, sort_keys=True))
        # exit(1)

        # Retry loop for Nest communications
        while True:
            try:
                # Loop through Nest structures aka homes
                for structure in nest.structures:
                    event = mapStructure(structure)
Beispiel #31
0
 def initialize(self):
     self.nest = Nest(NEST_USER, NEST_PASSWD)
Beispiel #32
0
class NestPlugin(IPlugin):
    """
    This plugin interfaces with the unofficial Nest api using the
    python Nest-API package.
    """
    def __init__(self):
        IPlugin.__init__(self)
        self.command_priority = 2
        self.nest = None
        self.voice = None

        self.commands = {
            'what.*(?P<nest_temp>indoor temp).*': [{
                'command': self.get_temp,
                'args': (None, ),
                'kwargs': {},
                'command_priority': 0,
            }],
            'what.*(?P<nest_hum>indoor humid).*': [{
                'command': self.get_humidity,
                'args': (None, ),
                'kwargs': {},
                'command_priority': 0,
            }],
            'what.*(?P<nest_cond>indoor condition).*': [{
                'command': self.get_conditions,
                'args': (None, ),
                'kwargs': {},
                'command_priority': 0,
            }],
            'set.*indoor temp.*to (?P<set_nest_temp>\d*).*': [{
                'command':
                self.set_temp,
                'args': (None, ),
                'kwargs': {},
                'command_priority':
                0,
            }],
        }

    def initialize(self):
        self.nest = Nest(NEST_USER, NEST_PASSWD)

    def get_temp(self, command_dict, text):
        """
        Get the Nest's indoor temperature
        """
        if text:
            command_text = text
        else:
            command_text = command_dict['nest_temp']

        if not self.nest:
            self.initialize()

        if not self.voice:
            self.instantiate_voice()

        response_text = 'the temperature in the house is ' + str(
            self.nest.temperature) + ' degrees Fahrenheit'

        self.voice.say({}, response_text)
        return None

    def get_humidity(self, command_dict, text):
        """
        Get the Nest's indoor humidity
        """
        if text:
            command_text = text
        else:
            command_text = command_dict['nest_hum']

        if not self.nest:
            self.initialize()

        if not self.voice:
            self.instantiate_voice()

        response_text = 'the humidity in the house is ' + str(
            self.nest.humidity) + ''

        self.voice.say({}, response_text)
        return None

    def get_conditions(self, command_dict, text):
        """
        Get the Nest's indoor temperature and humidity
        """
        if text:
            command_text = text
        else:
            command_text = command_dict['nest_cond']

        if not self.nest:
            self.initialize()

        if not self.voice:
            self.instantiate_voice()

        response_text = 'the temperature in the house is ' + str(self.nest.temperature) + ' degrees Fahrenheit, ' + \
            'and the humidity is ' + str(self.nest.humidity) + ''

        self.voice.say({}, response_text)
        return None

    def set_temp(self, command_dict, text):
        """
        Set the Nest's indoor temperature target
        """
        if text:
            command_text = text
        else:
            command_text = command_dict['set_nest_temp']

        if not self.nest:
            self.initialize()

        if not self.voice:
            self.instantiate_voice()

        response_text = 'setting the house temperature to ' + command_text + ' degrees Fahrenheit'

        self.nest.set_target_temperature(int(command_text))

        self.voice.say({}, response_text)
        return None

    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
Beispiel #33
0
        if nest.mode == "init" or not nest.mode == "heat":
            nest.set_mode("heat")
        else:
            logging.info("Already in heat mode. ignoring request")
    else:
        if nest.mode == "init" or not nest.mode == "off":
            nest.set_mode("off")
        else:
            logging.info("Already in off mode. ignoring request")

if __name__ == "__main__":

    logger.info("HUEBOT says hello!")

    scheduler              = Scheduler()
    nest                   = Nest(_c.NEST_USERNAME, _c.NEST_PASSWORD, _c.NEST_SERIAL)
    bridge                 = phue.Bridge(ip=_c.HUE_BRIDGE_IP, config_file_path=_c.HUE_BRIDGE_CONFIG)
    last_number_of_devices = 0

    nest.login()
    nest.get_status()

    def schedule_next_sunset():
        if _c.SUNSET_AUTO:
            date = sunset_date(_c.SUNSET_CITY).replace(tzinfo=None) - timedelta(minutes=_c.SUNSET_OFFSET)
        else:
            date = datetime.now().replace(hour=_c.SUNSET_HOUR, minute=_c.SUNSET_MINUTES, second=0, tzinfo=None)

        rightnow = datetime.now()

        if date < rightnow:
Beispiel #34
0
        logging.basicConfig(level=log_level, format=log_format)
    else:
        logging.basicConfig(level=log_level, format=log_format,
                            filename=log_fname, filemode='a')
    log = logging.getLogger('default')

    try:
        cfg = read_config(cfg_fname)
    except Exception, ex:
        log.error("Error reading config file %s" % ex)
        sys.exit(1)
        
    fields = cfg["fields"]

    try:
        n = Nest(cfg["nest_user"],cfg["nest_password"],units=cfg["units"])
        n.login()
        n.get_status()
        shared = n.status["shared"][n.serial]
        device = n.status["device"][n.serial]
        allvars = shared
        allvars.update(device)
    except Exception, ex:
        log.error("Error connecting to NEST: %s" % ex )
        sys.exit(100)

    data = ""
    for fname,fds in fields.items():
        if allvars.has_key(fname):
            ds = str(fds["datastream"])
            if fds.has_key("mapping"):
Beispiel #35
0
def nest():
    n = Nest("*****@*****.**", "reaganomics")
    n.login()
    n.get_status()
    return json.dumps(n.status)
Beispiel #36
0
from nest import Nest
from oversee.app import app

nest = Nest(app=app)
try:
    nest.run()
except KeyboardInterrupt as e:
    print('Shutting down...')
finally:
    nest.shutdown()
Beispiel #37
0
        logging.basicConfig(level=log_level,
                            format=log_format,
                            filename=log_fname,
                            filemode='a')
    log = logging.getLogger('default')

    try:
        cfg = read_config(cfg_fname)
    except Exception, ex:
        log.error("Error reading config file %s" % ex)
        sys.exit(1)

    fields = cfg["fields"]

    try:
        n = Nest(cfg["nest_user"], cfg["nest_password"], units=cfg["units"])
        n.login()
        n.get_status()
        shared = n.status["shared"][n.serial]
        device = n.status["device"][n.serial]
        allvars = shared
        allvars.update(device)
    except Exception, ex:
        log.error("Error connecting to NEST: %s" % ex)
        sys.exit(100)

    data = ""
    for fname, fds in fields.items():
        if allvars.has_key(fname):
            ds = str(fds["datastream"])
            if fds.has_key("mapping"):
Beispiel #38
0
class NestPlugin(IPlugin):
    """
    This plugin interfaces with the unofficial Nest api using the
    python Nest-API package.
    """
    def __init__(self):
        IPlugin.__init__(self)
        self.command_priority = 2
        self.nest = None
        self.voice = None

        self.commands = {
            'what.*(?P<nest_temp>indoor temp).*': [
                {
                    'command': self.get_temp,
                    'args': (None,),
                    'kwargs': {},
                    'command_priority': 0,
                }
            ],
            'what.*(?P<nest_hum>indoor humid).*': [
                {
                    'command': self.get_humidity,
                    'args': (None,),
                    'kwargs': {},
                    'command_priority': 0,
                }
            ],
            'what.*(?P<nest_cond>indoor condition).*': [
                {
                    'command': self.get_conditions,
                    'args': (None,),
                    'kwargs': {},
                    'command_priority': 0,
                }
            ],
            'set.*indoor temp.*to (?P<set_nest_temp>\d*).*': [
                {
                    'command': self.set_temp,
                    'args': (None,),
                    'kwargs': {},
                    'command_priority': 0,
                }
            ],
        }

    def initialize(self):
        self.nest = Nest(NEST_USER, NEST_PASSWD)

    def get_temp(self, command_dict, text):
        """
        Get the Nest's indoor temperature
        """
        if text:
            command_text = text
        else:
            command_text = command_dict['nest_temp']

        if not self.nest:
            self.initialize()

        if not self.voice:
            self.instantiate_voice()

        response_text = 'the temperature in the house is ' + str(self.nest.temperature) + ' degrees Fahrenheit'

        self.voice.say({}, response_text)
        return None

    def get_humidity(self, command_dict, text):
        """
        Get the Nest's indoor humidity
        """
        if text:
            command_text = text
        else:
            command_text = command_dict['nest_hum']

        if not self.nest:
            self.initialize()

        if not self.voice:
            self.instantiate_voice()

        response_text = 'the humidity in the house is ' + str(self.nest.humidity) + ''

        self.voice.say({}, response_text)
        return None

    def get_conditions(self, command_dict, text):
        """
        Get the Nest's indoor temperature and humidity
        """
        if text:
            command_text = text
        else:
            command_text = command_dict['nest_cond']

        if not self.nest:
            self.initialize()

        if not self.voice:
            self.instantiate_voice()

        response_text = 'the temperature in the house is ' + str(self.nest.temperature) + ' degrees Fahrenheit, ' + \
            'and the humidity is ' + str(self.nest.humidity) + ''

        self.voice.say({}, response_text)
        return None

    def set_temp(self, command_dict, text):
        """
        Set the Nest's indoor temperature target
        """
        if text:
            command_text = text
        else:
            command_text = command_dict['set_nest_temp']

        if not self.nest:
            self.initialize()

        if not self.voice:
            self.instantiate_voice()

        response_text = 'setting the house temperature to ' + command_text + ' degrees Fahrenheit'

        self.nest.set_target_temperature(int(command_text))

        self.voice.say({}, response_text)
        return None

    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
Beispiel #39
0
class Control:
    nest = None
    bridge = None

    def __init__(self):
        global logger
        logger = logging.getLogger(__name__)
        # connect to nest
        try:
            from nest import Nest
            self.nest = Nest(username=settings.NEST_LOGIN,
                             password=settings.NEST_PASS)
            self.nest.login()
            self.nest.get_status()
        except:
            logger.error("Unable to connect to NEST.")
        # connect to phillips hue
        self.bridge = Bridge(settings.HUE_BRIDGE)
        try:
            self.bridge.connect()
            self.bridge.get_api()
        except:
            logger.error("Unable to connect to Hue.")

    def execute_command(self, command):
        if command.action == 'power':
            light_state = (command.value == 'on')
            for light_index in settings.LIGHT_GROUPS[command.room]:
                logger.debug('Setting light %s: %s' %
                             (str(light_index), str(light_state)))
                self.bridge.set_light(light_index, 'on', light_state)
                if light_state:
                    # reset color
                    self.bridge.set_light(light_index, 'hue', 15331)
                    self.bridge.set_light(light_index, 'sat', 121)
            return True
        elif command.action == 'dim':
            for light_index in settings.LIGHT_GROUPS[command.room]:
                brightness = int(255 * (command.value * 0.1))
                logger.debug('Setting bright %s: %s' %
                             (str(light_index), str(brightness)))
                self.bridge.set_light(light_index, 'bri', brightness)
            return True
        elif command.action == 'hue':
            curr_group = settings.LIGHT_GROUPS[command.room]
            for index, light_index in enumerate(curr_group):
                # iterates over each color for fades, gradients,etc
                value = command.value[index % len(command.value)]
                logger.debug('Setting hue %s: %s' % (str(light_index), value))
                self.bridge.set_light(light_index, 'on', True)
                self.bridge.set_light(light_index, 'hue', value)
                self.bridge.set_light(light_index, 'sat', 255)
            return True
        elif command.action == 'temperature':
            if not self.nest:
                logger.error('Nest thermostat not initialized.')
                return False
            if command.value:
                self.nest.set_temperature(command.value)
                return True
            else:
                logger.error('Could not determine a temperature.')
        return False
Beispiel #40
0
async def async_setup_entry(hass, entry):
    """Set up Nest from a config entry."""
    from nest import Nest

    nest = Nest(access_token=entry.data['tokens']['access_token'])

    _LOGGER.debug("proceeding with setup")
    conf = hass.data.get(DATA_NEST_CONFIG, {})
    hass.data[DATA_NEST] = NestDevice(hass, conf, nest)
    if not await hass.async_add_job(hass.data[DATA_NEST].initialize):
        return False

    for component in 'climate', 'camera', 'sensor', 'binary_sensor':
        hass.async_create_task(hass.config_entries.async_forward_entry_setup(
            entry, component))

    def set_mode(service):
        """
        Set the home/away mode for a Nest structure.

        You can set optional eta information when set mode to away.
        """
        if ATTR_STRUCTURE in service.data:
            structures = service.data[ATTR_STRUCTURE]
        else:
            structures = hass.data[DATA_NEST].local_structure

        for structure in nest.structures:
            if structure.name in structures:
                _LOGGER.info("Setting mode for %s", structure.name)
                structure.away = service.data[ATTR_HOME_MODE]

                if service.data[ATTR_HOME_MODE] == HOME_MODE_AWAY \
                        and ATTR_ETA in service.data:
                    now = datetime.utcnow()
                    eta_begin = now + service.data[ATTR_ETA]
                    eta_window = service.data.get(ATTR_ETA_WINDOW,
                                                  timedelta(minutes=1))
                    eta_end = eta_begin + eta_window
                    trip_id = service.data.get(
                        ATTR_TRIP_ID, "trip_{}".format(int(now.timestamp())))
                    _LOGGER.info("Setting eta for %s, eta window starts at "
                                 "%s ends at %s", trip_id, eta_begin, eta_end)
                    structure.set_eta(trip_id, eta_begin, eta_end)
            else:
                _LOGGER.error("Invalid structure %s",
                              service.data[ATTR_STRUCTURE])

    hass.services.async_register(
        DOMAIN, 'set_mode', set_mode, schema=AWAY_SCHEMA)

    @callback
    def start_up(event):
        """Start Nest update event listener."""
        threading.Thread(
            name='Nest update listener',
            target=nest_update_event_broker,
            args=(hass, nest)
        ).start()

    hass.bus.async_listen_once(EVENT_HOMEASSISTANT_START, start_up)

    @callback
    def shut_down(event):
        """Stop Nest update event listener."""
        nest.update_event.set()

    hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, shut_down)

    _LOGGER.debug("async_setup_nest is done")

    return True
Beispiel #41
0
async def async_setup_legacy_entry(hass: HomeAssistant,
                                   entry: ConfigEntry) -> bool:
    """Set up Nest from legacy config entry."""

    nest = Nest(access_token=entry.data["tokens"]["access_token"])

    _LOGGER.debug("proceeding with setup")
    conf = hass.data.get(DATA_NEST_CONFIG, {})
    hass.data[DATA_NEST] = NestLegacyDevice(hass, conf, nest)
    if not await hass.async_add_executor_job(hass.data[DATA_NEST].initialize):
        return False

    hass.config_entries.async_setup_platforms(entry, PLATFORMS)

    def validate_structures(target_structures):
        all_structures = [structure.name for structure in nest.structures]
        for target in target_structures:
            if target not in all_structures:
                _LOGGER.info("Invalid structure: %s", target)

    def set_away_mode(service):
        """Set the away mode for a Nest structure."""
        if ATTR_STRUCTURE in service.data:
            target_structures = service.data[ATTR_STRUCTURE]
            validate_structures(target_structures)
        else:
            target_structures = hass.data[DATA_NEST].local_structure

        for structure in nest.structures:
            if structure.name in target_structures:
                _LOGGER.info(
                    "Setting away mode for: %s to: %s",
                    structure.name,
                    service.data[ATTR_AWAY_MODE],
                )
                structure.away = service.data[ATTR_AWAY_MODE]

    def set_eta(service):
        """Set away mode to away and include ETA for a Nest structure."""
        if ATTR_STRUCTURE in service.data:
            target_structures = service.data[ATTR_STRUCTURE]
            validate_structures(target_structures)
        else:
            target_structures = hass.data[DATA_NEST].local_structure

        for structure in nest.structures:
            if structure.name in target_structures:
                if structure.thermostats:
                    _LOGGER.info(
                        "Setting away mode for: %s to: %s",
                        structure.name,
                        AWAY_MODE_AWAY,
                    )
                    structure.away = AWAY_MODE_AWAY

                    now = datetime.utcnow()
                    trip_id = service.data.get(ATTR_TRIP_ID,
                                               f"trip_{int(now.timestamp())}")
                    eta_begin = now + service.data[ATTR_ETA]
                    eta_window = service.data.get(ATTR_ETA_WINDOW,
                                                  timedelta(minutes=1))
                    eta_end = eta_begin + eta_window
                    _LOGGER.info(
                        "Setting ETA for trip: %s, "
                        "ETA window starts at: %s and ends at: %s",
                        trip_id,
                        eta_begin,
                        eta_end,
                    )
                    structure.set_eta(trip_id, eta_begin, eta_end)
                else:
                    _LOGGER.info(
                        "No thermostats found in structure: %s, unable to set ETA",
                        structure.name,
                    )

    def cancel_eta(service):
        """Cancel ETA for a Nest structure."""
        if ATTR_STRUCTURE in service.data:
            target_structures = service.data[ATTR_STRUCTURE]
            validate_structures(target_structures)
        else:
            target_structures = hass.data[DATA_NEST].local_structure

        for structure in nest.structures:
            if structure.name in target_structures:
                if structure.thermostats:
                    trip_id = service.data[ATTR_TRIP_ID]
                    _LOGGER.info("Cancelling ETA for trip: %s", trip_id)
                    structure.cancel_eta(trip_id)
                else:
                    _LOGGER.info(
                        "No thermostats found in structure: %s, "
                        "unable to cancel ETA",
                        structure.name,
                    )

    hass.services.async_register(DOMAIN,
                                 SERVICE_SET_AWAY_MODE,
                                 set_away_mode,
                                 schema=SET_AWAY_MODE_SCHEMA)

    hass.services.async_register(DOMAIN,
                                 SERVICE_SET_ETA,
                                 set_eta,
                                 schema=SET_ETA_SCHEMA)

    hass.services.async_register(DOMAIN,
                                 SERVICE_CANCEL_ETA,
                                 cancel_eta,
                                 schema=CANCEL_ETA_SCHEMA)

    @callback
    def start_up(event):
        """Start Nest update event listener."""
        threading.Thread(
            name="Nest update listener",
            target=nest_update_event_broker,
            args=(hass, nest),
        ).start()

    hass.bus.async_listen_once(EVENT_HOMEASSISTANT_START, start_up)

    @callback
    def shut_down(event):
        """Stop Nest update event listener."""
        nest.update_event.set()

    entry.async_on_unload(
        hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, shut_down))

    _LOGGER.debug("async_setup_nest is done")

    return True
Beispiel #42
0
class Nest(Command):
    def __init__(self):
        self.nest = NestAPI(settings.NEST_USER, settings.NEST_PASSWD)

    def set(self, temp):
        self.nest.set_target_temperature(int(temp))
Beispiel #43
0
async def async_setup_entry(hass, entry):
    """Set up Nest from a config entry."""
    from nest import Nest

    nest = Nest(access_token=entry.data['tokens']['access_token'])

    _LOGGER.debug("proceeding with setup")
    conf = hass.data.get(DATA_NEST_CONFIG, {})
    hass.data[DATA_NEST] = NestDevice(hass, conf, nest)
    if not await hass.async_add_job(hass.data[DATA_NEST].initialize):
        return False

    for component in 'climate', 'camera', 'sensor', 'binary_sensor':
        hass.async_create_task(
            hass.config_entries.async_forward_entry_setup(entry, component))

    def validate_structures(target_structures):
        all_structures = [structure.name for structure in nest.structures]
        for target in target_structures:
            if target not in all_structures:
                _LOGGER.info("Invalid structure: %s", target)

    def set_away_mode(service):
        """Set the away mode for a Nest structure."""
        if ATTR_STRUCTURE in service.data:
            target_structures = service.data[ATTR_STRUCTURE]
            validate_structures(target_structures)
        else:
            target_structures = hass.data[DATA_NEST].local_structure

        for structure in nest.structures:
            if structure.name in target_structures:
                _LOGGER.info("Setting away mode for: %s to: %s",
                             structure.name, service.data[ATTR_AWAY_MODE])
                structure.away = service.data[ATTR_AWAY_MODE]

    def set_eta(service):
        """Set away mode to away and include ETA for a Nest structure."""
        if ATTR_STRUCTURE in service.data:
            target_structures = service.data[ATTR_STRUCTURE]
            validate_structures(target_structures)
        else:
            target_structures = hass.data[DATA_NEST].local_structure

        for structure in nest.structures:
            if structure.name in target_structures:
                if structure.thermostats:
                    _LOGGER.info("Setting away mode for: %s to: %s",
                                 structure.name, AWAY_MODE_AWAY)
                    structure.away = AWAY_MODE_AWAY

                    now = datetime.utcnow()
                    trip_id = service.data.get(
                        ATTR_TRIP_ID, "trip_{}".format(int(now.timestamp())))
                    eta_begin = now + service.data[ATTR_ETA]
                    eta_window = service.data.get(ATTR_ETA_WINDOW,
                                                  timedelta(minutes=1))
                    eta_end = eta_begin + eta_window
                    _LOGGER.info(
                        "Setting ETA for trip: %s, "
                        "ETA window starts at: %s and ends at: %s", trip_id,
                        eta_begin, eta_end)
                    structure.set_eta(trip_id, eta_begin, eta_end)
                else:
                    _LOGGER.info(
                        "No thermostats found in structure: %s, "
                        "unable to set ETA", structure.name)

    def cancel_eta(service):
        """Cancel ETA for a Nest structure."""
        if ATTR_STRUCTURE in service.data:
            target_structures = service.data[ATTR_STRUCTURE]
            validate_structures(target_structures)
        else:
            target_structures = hass.data[DATA_NEST].local_structure

        for structure in nest.structures:
            if structure.name in target_structures:
                if structure.thermostats:
                    trip_id = service.data[ATTR_TRIP_ID]
                    _LOGGER.info("Cancelling ETA for trip: %s", trip_id)
                    structure.cancel_eta(trip_id)
                else:
                    _LOGGER.info(
                        "No thermostats found in structure: %s, "
                        "unable to cancel ETA", structure.name)

    hass.services.async_register(DOMAIN,
                                 SERVICE_SET_AWAY_MODE,
                                 set_away_mode,
                                 schema=SET_AWAY_MODE_SCHEMA)

    hass.services.async_register(DOMAIN,
                                 SERVICE_SET_ETA,
                                 set_eta,
                                 schema=SET_ETA_SCHEMA)

    hass.services.async_register(DOMAIN,
                                 SERVICE_CANCEL_ETA,
                                 cancel_eta,
                                 schema=CANCEL_ETA_SCHEMA)

    @callback
    def start_up(event):
        """Start Nest update event listener."""
        threading.Thread(name='Nest update listener',
                         target=nest_update_event_broker,
                         args=(hass, nest)).start()

    hass.bus.async_listen_once(EVENT_HOMEASSISTANT_START, start_up)

    @callback
    def shut_down(event):
        """Stop Nest update event listener."""
        nest.update_event.set()

    hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, shut_down)

    _LOGGER.debug("async_setup_nest is done")

    return True
Beispiel #44
0
 def __init__(self):
     self.nest = NestAPI(settings.NEST_USER, settings.NEST_PASSWD)