def parse_torrent(): """DESC: Asks user for location of .torrent file. Parses and saves metadata results""" t_content = '' meta_dict = {} # TODO: allow nest pickling and reloading into memory nest = None # torrent_file = input("Torrent File Location: ") torrent_file = '../test/tst.torrent' print(torrent_file) if nest is None: # TODO: check if nest saved to disk else create a new nest nest = ns.Nest() try: # Attempt to open the torrent file and bdecode the metadata with open(torrent_file, 'rb') as content_file: t_content = content_file.read() meta_dict = bdecode(t_content) except IOError: print('ERROR: Could not open file: ' + torrent_file) except: print ('ERROR: An unknown error occurred in opening or decoding file.') else: nest.hatch(meta_dict)
def get_device(product_id, product_secret, access_token_cache_file): napi = nest.Nest(client_id=product_id, client_secret=product_secret, access_token_cache_file=access_token_cache_file) # try: return_value = [] for structure in napi.structures: return_value.append({ 'type': 'nest.home', 'where': str(structure.name), 'serial': str(structure.name), 'device_name': str(structure.name) }) for ProtectDevice in structure.smoke_co_alarms: return_value.append({ 'type': 'nest.protect', 'where': str(ProtectDevice.where), 'serial': str(ProtectDevice.serial) }) for thermostat in structure.thermostats: return_value.append({ 'type': 'nest.thermostat', 'where': str(thermostat.where), 'serial': str(thermostat.serial) }) for camera in structure.cameras: return_value.append({ 'type': 'nest.camera', 'where': str(camera.where), 'serial': str(camera.serial) }) return return_value
def __init__(self, parent, primary, address, temperature, structurename, location, manifest=None): self.parent = parent self.LOGGER = self.parent.poly.LOGGER self.structurename = structurename self.location = location try: self.LOGGER.info('Initializing New Thermostat') self.napi = nest.Nest(USERNAME, PASSWORD, local_time=True) except requests.exceptions.HTTPError as e: self.LOGGER.error('NestThermostat __init__ Caught exception: %s', e) self.away = False self.online = False self.insidetemp = nest_utils.c_to_f(temperature) try: self.name = 'Nest ' + self.structurename + " " + self.location except TypeError as e: self.LOGGER.error( 'Caught TypeError on structurename or location, which means they don\'t exist. Using Generic name.' ) self.name = 'Nest Thermostat' self.address = address self.LOGGER.info("Adding new Nest Device: %s Current Temp: %i F", self.name, self.insidetemp) super(NestThermostat, self).__init__(parent, address, self.name, primary, manifest) self.update_info()
def getThermostat(self, thermostatName): napi = nest.Nest(client_id=client_id, client_secret=client_secret, access_token_cache_file=access_token_cache_file) thermostat = next( (x for x in napi.thermostats if x.name == thermostatName), None) return thermostat
def gather_nest(): napi = nest.Nest(client_id=CLIENT_ID, client_secret=CLIENT_SECRET, access_token_cache_file=ACCESS_TOKEN_CACHE_FILE) if napi.authorization_required: print('Go to ' + napi.authorize_url + ' to authorize, then enter PIN below') if sys.version_info[0] < 3: pin = raw_input("PIN: ") else: pin = input("PIN: ") napi.request_token(pin) data = [] for structure in napi.structures: struct_name = structure.name for device in structure.thermostats: for m in metrics: print(m + ": " + str(getattr(device, m))) data.append({ 'measurement': m, 'tags': { 'structure': struct_name, 'device': device.name }, 'fields': { 'value': getattr(device, m) } }) return data
def onStart(self): # Set debug level according to user setting self.debug = _DEBUG_ON if Parameters["Mode6"] == "Debug" else _DEBUG_OFF Domoticz.Debugging(self.debug) # Show plugin configuration in log if self.debug == _DEBUG_ON: DumpConfigToLog() # Create images if necessary if _IMAGE_NEST_AWAY not in Images: Domoticz.Image("Nest Away.zip").Create() if _IMAGE_NEST_ECO not in Images: Domoticz.Image("Nest Eco.zip").Create() if _IMAGE_NEST_HEATING not in Images: Domoticz.Image("Nest Heating.zip").Create() if _IMAGE_NEST_HEATING_OFF not in Images: Domoticz.Image("Nest Heating Off.zip").Create() if _IMAGE_NEST_PROTECT not in Images: Domoticz.Image("Nest Protect.zip").Create() Domoticz.Debug("> Images created") # Set all devices as timed out TimeoutDevice(All=True) # Create Nest instance self.myNest = nest.Nest(Parameters["Mode1"], Parameters["Mode2"]) Domoticz.Debug("> Plugin started")
def setup_platform(hass, config, add_devices, discovery_info=None): """ Sets up the nest thermostat. """ logger = logging.getLogger(__name__) username = config.get(CONF_USERNAME) password = config.get(CONF_PASSWORD) if username is None or password is None: logger.error("Missing required configuration items %s or %s", CONF_USERNAME, CONF_PASSWORD) return try: import nest except ImportError: logger.exception( "Error while importing dependency nest. " "Did you maybe not install the python-nest dependency?") return napi = nest.Nest(username, password) try: add_devices([ NestThermostat(structure, device) for structure in napi.structures for device in structure.devices ]) except socket.error: logger.error("Connection error logging into the nest web service.")
def connect(self): # Get credentials for login self.credentials_file = os.path.join(os.path.dirname(sys.argv[0]), "credentials/nest.txt") if os.path.isfile(self.credentials_file): self.logger.debug( "Credential file found, reading attributes from file") self.username = linecache.getline(self.credentials_file, 1) self.password = linecache.getline(self.credentials_file, 2) else: self.logger.warning( "Credential file NOT found, continuing with default values") self.username = "******" self.password = "******" # clean up extracted data self.username = str(self.username).lstrip() self.username = str(self.username).rstrip() self.password = str(self.password).lstrip() self.password = str(self.password).rstrip() # Login to Nest account self.logger.debug("Attempting to connect to NEST account") try: self.nest = nest.Nest(self.username, self.password) self.logger.debug("Connection successful") return True except: self.nest = None self.logger.error("Could not connect to NEST account") return False
def get_token_link(product_id, product_secret, access_token_cache_file): napi = nest.Nest(client_id=product_id, client_secret=product_secret, access_token_cache_file=access_token_cache_file) login_url = napi.authorize_url login_url = unicode(login_url, 'utf-8') return login_url
def get_devices(hass, config): """ Gets Nest thermostats. """ logger = logging.getLogger(__name__) username = config.get(CONF_USERNAME) password = config.get(CONF_PASSWORD) if username is None or password is None: logger.error("Missing required configuration items %s or %s", CONF_USERNAME, CONF_PASSWORD) return [] try: import nest except ImportError: logger.exception( "Error while importing dependency nest. " "Did you maybe not install the python-nest dependency?") return [] napi = nest.Nest(username, password) return [ NestThermostat(structure, device) for structure in napi.structures for device in structure.devices ]
def _list(): _get_auth() with nest.Nest( client_id=config.client_id, client_secret=config.client_secret, access_token_cache_file=config.access_token_cache_file) as napi: for therm in napi.thermostats: print(therm.name)
def gather_nest(u=USER, p=PASS): napi = nest.Nest(u, p) data = [] # Jason loves mad precision, yo. Lets turn that shiz down a notch. nu.decimal.getcontext().prec = 4 for structure in napi.structures: struct_name = structure.name for device in structure.devices: for m in metrics: data.append({ 'measurement': m, 'tags': { 'structure': struct_name, 'device': device.name }, 'fields': { 'value': getattr(device, m) } }) for m in metrics_convert: data.append({ 'measurement': m, 'tags': { 'structure': struct_name, 'device': device.name }, 'fields': { 'value': nu.c_to_f(getattr(device, m)) } }) t = nu.c_to_f(structure.weather.current.temperature) data.append({ 'measurement': 'temperature', 'tags': { 'structure': struct_name, 'device': 'Outside' }, 'fields': { 'value': t } }) data.append({ 'measurement': 'humidity', 'tags': { 'structure': struct_name, 'device': 'Outside' }, 'fields': { 'value': structure.weather.current.humidity } }) return data
class MyStreamListener(tweepy.StreamListener): _napi = nest.Nest("<NEST ACCOUNT USERNAME>", "<NEST ACCOUNT PASSWORD>") def on_status(self, status): print(status.text) def on_direct_message(self, status): new_temp = status.direct_message['text'] print("Nest is changing the temp to {temp}".format(temp=new_temp)) self._napi.devices[0].temperature = nest_utils.f_to_c(new_temp)
def _checkconnect(self): try: connected = self.napi.devices[0].online self.logger.info('Connected: %s', connected) if not connected: self.napi = nest.Nest(USERNAME, PASSWORD, local_time=True) return True except (requests.exceptions.HTTPError, requests.exceptions.ConnectionError, TypeError) as e: self.logger.error('CheckConnect: %s', e) return False
def setup(hass, config): """Setup the Nest thermostat component.""" global NEST username = config[DOMAIN].get(CONF_USERNAME) password = config[DOMAIN].get(CONF_PASSWORD) import nest NEST = nest.Nest(username, password) return True
def setup(hass, config): """Setup the Nest thermostat component.""" import nest conf = config[DOMAIN] username = conf[CONF_USERNAME] password = conf[CONF_PASSWORD] nest = nest.Nest(username, password) hass.data[DATA_NEST] = NestDevice(hass, conf, nest) return True
def main(): args = parse_args() logging.basicConfig(level='INFO') LOG.info('authenticating to nest api') napi = nest.Nest(client_id=args.client_id, client_secret=args.client_secret, access_token_cache_file=args.token_cache, access_token=args.token) if napi.authorization_required: if args.pin: LOG.info('requesting access token') napi.request_token(args.pin) else: LOG.error('api requires authorization') sys.exit(1) LOG.info('connecting to mqtt broker') mq = mqtt.Client() mq.loop_start() mq.connect(args.mqtt_server) while True: for therm in napi.thermostats: if therm.structure._serial != args.location: continue if therm.temperature_scale == 'F': temp = nest.utils.f_to_c(therm.temperature) target = nest.utils.f_to_c(therm.target) else: temp = therm.temperature target = therm.target hvac_state = ['off', 'heating', 'cooling'].index(therm.hvac_state) topic = '{}/nest/{}'.format(args.topic, therm.device_id) sample = { 'sensor_id': therm.device_id, 'sensor_type': 'nest', 'location': therm.name.lower(), 'temperature': temp, 'temperature_target': target, 'humidity': therm.humidity, 'hvac_state': hvac_state, } LOG.info('sending on %s sample %s', topic, sample) msg = json.dumps(sample) mq.publish(topic, msg) time.sleep(args.interval)
def _getDevice(login, password, serial): # Instantiate the nest object and login. napi = nest.Nest(login, password) # Find the device we want to control. device = None for d in napi.devices: if d._serial == serial: device = d break else: raise 'Could not find device with requested serial ID.' return device
def init_nest(client_id, client_secret, access_token_file): napi = nest.Nest(client_id=client_id, client_secret=client_secret, access_token_cache_file=access_token_file) if napi.authorization_required: print('Go to ' + napi.authorize_url + ' to authorize, then enter PIN below') if sys.version_info[0] < 3: pin = raw_input("PIN: ") else: pin = input("PIN: ") napi.request_token(pin) return napi
def lambda_handler(event, context): nest_api = nest.Nest(client_id=client_id, client_secret=client_secret, access_token_cache_file=access_token_cache_file) if nest_api.authorization_required: print('Go to ' + nest_api.authorize_url + ' to authorize, then enter PIN below') pin = input("PIN: ") nest_api.request_token(pin) data = parse_nest_data(nest_api.thermostats) put_cloudwatch_metrics(data)
def __init__(self, config): self.config = config self.napi = nest.Nest(client_id=self.config['id'], client_secret=self.config['secret'], access_token_cache_file='nest.cache') if self.napi.authorization_required: print('Go to ' + self.napi.authorize_url + ' to authorize, then enter PIN below') if sys.version_info[0] < 3: pin = raw_input("PIN: ") else: pin = input("PIN: ") self.napi.request_token(pin)
def __init__(self, thermostatName): logger.info("Initializing thermostat {}".format(thermostatName)) client_id = settings['nest_id'] client_secret = settings['nest_key'] access_token_cache_file = 'nest.json' self.thermostatName = thermostatName self.napi = nest.Nest(client_id=client_id, client_secret=client_secret, access_token_cache_file=access_token_cache_file) if self.napi.authorization_required: self.printAuthMsg() self.thermostat = self.getThermostatByName(self.thermostatName) self.reporter = Reporter()
def _checkconnect(self): try: connected = self.device.online if not connected: self.parent.napi = nest.Nest(client_id=PRODUCTID, client_secret=PRODUCTSECRET, access_token_cache_file=CACHEFILE) return True except (requests.exceptions.HTTPError, requests.exceptions.ConnectionError, TypeError, requests.exceptions.ReadTimeout) as e: LOGGER.error('CheckConnect: %s', e) self.online = False self.setDriver('GV4', 0)
def onStart(self): # Set debug level according to user setting self.debug = DEBUG_ON if Parameters['Mode6'] == 'Debug' else DEBUG_OFF Domoticz.Debugging(self.debug) if self.debug == DEBUG_ON: DumpConfigToLog(Parameters, Devices) # Read technical parameters try: config = None with open('./plugins/GoogleNest/GoogleNest.json') as json_file: config = json.load(json_file) self.round_temperature = config['RoundTemperature'] except: pass # Create images if necessary if _IMAGE_NEST_AWAY not in Images: Domoticz.Image('Nest Away.zip').Create() if _IMAGE_NEST_ECO not in Images: Domoticz.Image('Nest Eco.zip').Create() if _IMAGE_NEST_HEATING not in Images: Domoticz.Image('Nest Heating.zip').Create() if _IMAGE_NEST_HEATING_OFF not in Images: Domoticz.Image('Nest Heating Off.zip').Create() if _IMAGE_NEST_PROTECT not in Images: Domoticz.Image('Nest Protect.zip').Create() Domoticz.Debug('> Images created') # Set all devices as timed out TimeoutDevice(Devices, All=True) # Create Nest instance if not Parameters['Mode1'].startswith('https://accounts.google.com'): Domoticz.Error( 'Hardware setting issue_token must start with https://accounts.google.com.' ) elif not Parameters['Mode1'].endswith('nest.com'): Domoticz.Error( 'Hardware setting issue_token must end with nest.com.') else: self.myNest = nest.Nest( Parameters['Mode1'], Parameters['Mode2'], float(Parameters['Mode5'].replace(',', '.'))) self.tasksThread.start() self.tasksQueue.put({'Action': 'StatusUpdate'}) self.tasksQueue.put({'Action': 'OutsideWeather'}) Domoticz.Debug('> Plugin started')
def bump_down(): _get_auth() with nest.Nest( client_id=config.client_id, client_secret=config.client_secret, access_token_cache_file=config.access_token_cache_file) as napi: if config.affect_all: for device in napi.thermostats: _bump_down(device) else: device = [ therm for therm in napi.thermostats if therm.name == config.device_name ][0] _bump_down(device)
def _get_auth(): if _get_auth._auth: return file_path = config.access_token_cache_file \ if os.path.isabs(config.access_token_cache_file) \ else os.path.join(_base_dir, config.access_token_cache_file) with nest.Nest(client_id=config.client_id, client_secret=config.client_secret, access_token_cache_file=file_path) as napi: if napi.authorization_required: print('Go to ' + napi.authorize_url + ' to authorize, then enter PIN below') pin = input("PIN: ") napi.request_token(pin) _get_auth._auth = True
def generate_token_file(authorization_code, product_id, product_secret, access_token_cache_file): napi = nest.Nest(client_id=product_id, client_secret=product_secret, access_token_cache_file=access_token_cache_file) napi.request_token(authorization_code) if napi.invalid_access_token is True: flash( gettext( u"Error while getting token from Nest code, check you products id/secret Pin code" ), "error") else: flash( gettext( u"Successfully generate token. Please restart the plugin."), "success")
def init(self): try: n = nest.Nest(nest_login, nest_passwd) n.login() return n except: print( strftime("[%H:%M:%S]: EXCEPTION ", localtime()) + traceback.format_exc()) if self.logger: self.logger.error( (strftime("[%H:%M:%S]: EXCEPTION ", localtime()) + traceback.format_exc()), exc_info=True) return False
def set_fan(time=15): _get_auth() with nest.Nest( client_id=config.client_id, client_secret=config.client_secret, access_token_cache_file=config.access_token_cache_file) as napi: if config.affect_all: for device in napi.thermostats: device.fan_timer = time device.fan = True else: device = [ therm for therm in napi.thermostats if therm.name == config.device_name ][0] device.fan_timer = time device.fan = True
def __init__(self): if not client_secret or not client_id: logger.error( "Nest Developer Account required: see https://console.developers.nest.com/developer/new" ) logger.error( "Update this file with client_id and client_secret to connect to Nest" ) raise Exception("No Nest Developer Credentials") self.api = nest.Nest(client_id=client_id, client_secret=client_secret, access_token_cache_file='.nestauthorization') if self.api.authorization_required: logger.info("Nest is not authorized...") self.authenticate() else: logger.info("Connected to Nest!")