コード例 #1
0
ファイル: poller.py プロジェクト: tadthies/nest-datagraph
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])
コード例 #2
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])
コード例 #3
0
ファイル: nest_control.py プロジェクト: skymeson/my-will
 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)
コード例 #4
0
ファイル: nest_control.py プロジェクト: skoczen/my-will
 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)
コード例 #5
0
ファイル: run.py プロジェクト: entone/Clubhouse
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)
コード例 #6
0
ファイル: run.py プロジェクト: entone/Clubhouse
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)
コード例 #7
0
ファイル: nest_control.py プロジェクト: skoczen/my-will
 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)
コード例 #8
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())
コード例 #9
0
ファイル: run.py プロジェクト: kgorman/pynest
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())
コード例 #10
0
ファイル: run.py プロジェクト: entone/Clubhouse
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)
コード例 #11
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()
コード例 #12
0
ファイル: nesttool.py プロジェクト: frasermac/pynest
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"
コード例 #13
0
ファイル: nesttool.py プロジェクト: frasermac/pynest
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"
コード例 #14
0
ファイル: run.py プロジェクト: entone/Clubhouse
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)
コード例 #15
0
ファイル: nest_control.py プロジェクト: skymeson/my-will
 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)
コード例 #16
0
ファイル: nest_cosm.py プロジェクト: frasermac/pynest
                            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"):
                rv = str(allvars[fname])
コード例 #17
0
ファイル: control.py プロジェクト: AnanthaRajuC/homecontrol
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
コード例 #18
0
ファイル: huebot.py プロジェクト: primalmotion/huebot
    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:

            logger.info("current sunset already past. scheduling for tomorow.")

            if rightnow.time().hour < _c.SLEEP_TIME_HOUR or (rightnow.time().hour == _c.SLEEP_TIME_HOUR and rightnow.time().minute < _c.SLEEP_TIME_MINUTES):
コード例 #19
0
ファイル: nest_cosm.py プロジェクト: frasermac/pynest
    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"):
                rv = str(allvars[fname])
コード例 #20
0
ファイル: app.py プロジェクト: dpaola2/jarvis
def nest():
    n = Nest("*****@*****.**", "reaganomics")
    n.login()
    n.get_status()
    return json.dumps(n.status)
コード例 #21
0
ファイル: control.py プロジェクト: srodge1/homecontrol
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