Coder Social home page Coder Social logo

python-nest's Introduction

Python API and command line tool for the Nest™ Thermostat

https://travis-ci.org/jkoelker/python-nest.svg?branch=master

Installation

[sudo] pip install python-nest

NOTE The 4.x version uses the streaming endpoint. To use the older polling/caching behavior pin your requirements to python-nest<4.0.

NOTE The 3.x version uses the Nest official api. As such, some functionality was removed as it is not available. To keep the old version and functionality, make sure to set your requirements to python-nest<3.0.

Nest Developer Account

You will need a Nest developer account, and a Product on the Nest developer portal to use this module:

  1. Visit Nest Developers, and sign in. Create an account if you don't have one already.
  2. Fill in the account details:
  • The "Company Information" can be anything.
  1. Submit changes.
  2. Click "Products" at top of page.
  3. Click "Create New Product"
  4. Fill in details:
  • Product name must be unique.
  • The description, users, urls can all be anything you want.
  1. For permissions, check every box and if it's an option select the read/write option.
  • The description requires a specific format to be accepted.
  1. Click "Create Product".
  2. Once the new product page opens the "Product ID" and "Product Secret" are located on the right side. These will be used as client_id and client_secret below.

Usage

Migrate to 4.x

The version 4.x uses Nest Stream API, so that you can get nearly real time status update of your Nest devices.

If you use python-nest as a command line tool:
You don't need to change, but there is a new command line option --keep-alive you can give a try.
If you use python-nest in a poll loop, to query Nest device's property in certain period, there are several noticeable changes:
  • The internal cache removed, the Structure and Device objects will always return their current state presented in Nest API.
  • A persistence HTTP connection will keep open for each Nest object. Therefore, please avoid to create more than one Nest object in your program.
  • Your poll query would not hit the API rate limit, you can increase your poll frequency.
If you want to change to Push mode:
You need to listen Nest.update_event. Please note, any data change in all of your structures an devices will set the update_event. You don't know which field got update.
import nest

napi = nest.Nest(client_id=client_id, client_secret=client_secret, access_token_cache_file=access_token_cache_file)
while napi.update_event.wait():
    napi.update_event.clear()
    # assume you have one Nest Camera
    print (napi.structures[0].cameras[0].motion_detected)
If you use asyncio:
You have to wrap update_event.wait() in an ThreadPoolExecutor, for example:
import asyncio
import nest

napi = nest.Nest(client_id=client_id, client_secret=client_secret, access_token_cache_file=access_token_cache_file)
event_loop = asyncio.get_event_loop()
try:
    event_loop.run_until_complete(nest_update(event_loop, napi))
finally:
    event_loop.close()

async def nest_update(loop, napi):
    with ThreadPoolExecutor(max_workers=1) as executor:
        while True:
            await loop.run_in_executor(executor, nest.update_event.wait)
            nest.update_event.clear()
            # assume you have one Nest Camera
            print (napi.structures[0].cameras[0].motion_detected)

Module

You can import the module as nest.

import nest
import sys

client_id = 'XXXXXXXXXXXXXXX'
client_secret = 'XXXXXXXXXXXXXXX'
access_token_cache_file = 'nest.json'

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)

for structure in napi.structures:
    print ('Structure %s' % structure.name)
    print ('    Away: %s' % structure.away)
    print ('    Security State: %s' % structure.security_state)
    print ('    Devices:')
    for device in structure.thermostats:
        print ('        Device: %s' % device.name)
        print ('            Temp: %0.1f' % device.temperature)

# Access advanced structure properties:
for structure in napi.structures:
    print ('Structure   : %s' % structure.name)
    print (' Postal Code                    : %s' % structure.postal_code)
    print (' Country                        : %s' % structure.country_code)
    print (' num_thermostats                : %s' % structure.num_thermostats)

# Access advanced device properties:
    for device in structure.thermostats:
        print ('        Device: %s' % device.name)
        print ('        Where: %s' % device.where)
        print ('            Mode       : %s' % device.mode)
        print ('            HVAC State : %s' % device.hvac_state)
        print ('            Fan        : %s' % device.fan)
        print ('            Fan Timer  : %i' % device.fan_timer)
        print ('            Temp       : %0.1fC' % device.temperature)
        print ('            Humidity   : %0.1f%%' % device.humidity)
        print ('            Target     : %0.1fC' % device.target)
        print ('            Eco High   : %0.1fC' % device.eco_temperature.high)
        print ('            Eco Low    : %0.1fC' % device.eco_temperature.low)
        print ('            hvac_emer_heat_state  : %s' % device.is_using_emergency_heat)
        print ('            online                : %s' % device.online)

# The Nest object can also be used as a context manager
# It is only for demo purpose, please do not create more than one Nest object in your program especially after 4.0 release
with nest.Nest(client_id=client_id, client_secret=client_secret, access_token_cache_file=access_token_cache_file) as napi:
    for device in napi.thermostats:
        device.temperature = 23

# Nest products can be updated to include other permissions. Before you
# can access them with the API, a user has to authorize again. To handle this
# and detect when re-authorization is required, pass in a product_version
client_id = 'XXXXXXXXXXXXXXX'
client_secret = 'XXXXXXXXXXXXXXX'
access_token_cache_file = 'nest.json'
product_version = 1337

# It is only for demo purpose, please do not create more than one Nest object in your program especially after 4.0 release
napi = nest.Nest(client_id=client_id, client_secret=client_secret, access_token_cache_file=access_token_cache_file, product_version=product_version)

print("Never Authorized: %s" % napi.never_authorized)
print("Invalid Token: %s" % napi.invalid_access_token)
print("Client Version out of date: %s" % napi.client_version_out_of_date)
if napi.authorization_required is None:
    print('Go to ' + napi.authorize_url + ' to authorize, then enter PIN below')
    pin = input("PIN: ")
    napi.request_token(pin)


# NOTE: By default all datetime objects are timezone unaware (UTC)
#       By passing ``local_time=True`` to the ``Nest`` object datetime objects
#       will be converted to the timezone reported by nest. If the ``pytz``
#       module is installed those timezone objects are used, else one is
#       synthesized from the nest data
napi = nest.Nest(username, password, local_time=True)
print napi.structures[0].weather.current.datetime.tzinfo

In the API, all temperature values are reported and set in the temperature scale the device is set to (as determined by the device.temperature_scale property).

Helper functions for conversion are in the utils module:

from nest import utils as nest_utils
temp = 23.5
fahrenheit = nest_utils.c_to_f(temp)
temp == nest_utils.f_to_c(fahrenheit)

The utils function use decimal.Decimal to ensure precision.

Command line

usage: nest [-h] [--conf FILE] [--token-cache TOKEN_CACHE_FILE] [-t TOKEN]
            [--client-id ID] [--client-secret SECRET] [-k] [-c] [-s SERIAL]
            [-S STRUCTURE] [-i INDEX] [-v]
            {temp,fan,mode,away,target,humid,target_hum,show,camera-show,camera-streaming,protect-show}
            ...

Command line interface to Nest™ Thermostats

positional arguments:
  {temp,fan,mode,away,target,humid,target_hum,show,camera-show,camera-streaming,protect-show}
                        command help
    temp                show/set temperature
    fan                 set fan "on" or "auto"
    mode                show/set current mode
    away                show/set current away status
    target              show current temp target
    humid               show current humidity
    target_hum          show/set target humidty
    show                show everything
    camera-show         show everything (for cameras)
    camera-streaming    show/set camera streaming
    protect-show        show everything (for Nest Protect)

optional arguments:
  -h, --help            show this help message and exit
  --conf FILE           config file (default ~/.config/nest/config)
  --token-cache TOKEN_CACHE_FILE
                        auth access token cache file
  -t TOKEN, --token TOKEN
                        auth access token
  --client-id ID        product id on developer.nest.com
  --client-secret SECRET
                        product secret for nest.com
  -k, --keep-alive      keep showing update received from stream API in show
                        and camera-show commands
  -c, --celsius         use celsius instead of farenheit
  -s SERIAL, --serial SERIAL
                        optional, specify serial number of nest thermostat to
                        talk to
  -S STRUCTURE, --structure STRUCTURE
                        optional, specify structure name toscope device
                        actions
  -i INDEX, --index INDEX
                        optional, specify index number of nest to talk to
  -v, --verbose         showing verbose logging

examples:
    # If your nest is not in range mode
    nest --conf myconfig --client-id CLIENTID --client-secret SECRET temp 73
    # If your nest is in range mode
    nest --conf myconfig --client-id CLIENTID --client-secret SECRET temp 66 73

    nest --conf myconfig --client-id CLIENTID --client-secret SECRET fan --auto
    nest --conf myconfig --client-id CLIENTID --client-secret SECRET target_hum 35

    # nestcam examples
    nest --conf myconfig --client-id CLIENTID --client-secret SECRET camera-show
    nest --conf myconfig --client-id CLIENTID --client-secret SECRET camera-streaming --enable-camera-streaming

    # Stream API example
    nest --conf myconfig --client-id CLIENTID --client-secret SECRET --keep-alive show
    nest --conf myconfig --client-id CLIENTID --client-secret SECRET --keep-alive camera-show

    # Set ETA 5 minutes from now
    nest --conf myconfig --client-id CLIENTID --client-secret SECRET away --away --eta 5

A configuration file must be specified and used for the credentials to communicate with the NEST Thermostat initially. Once completed and a token is generated, if you're using the default location for the token, the command line option will read from it automatically.

[NEST]
client_id = your_client_id
client_secret = your_client_secret
token_cache = ~/.config/nest/token_cache

The [NEST] section may also be named [nest] for convenience. Do not use [DEFAULT] as it cannot be read

History

This module was originally a fork of nest_thermostat which was a fork of pynest

python-nest's People

Contributors

abemassry avatar anna-hope avatar arnoutd avatar awarecan avatar balloob avatar enigma62333 avatar filosottile avatar fxstein avatar gwiskur avatar jawilson avatar jkoelker avatar kd7lxl avatar les69 avatar logjames avatar mattsch avatar milhousevh avatar ngordon-scty avatar notnami avatar nudge avatar peterot avatar rbpasker avatar schmittx avatar simone-zabberoni avatar slemiere avatar smbaker avatar technicalpickles avatar theaquarium avatar troyfontaine avatar vladonemo avatar zyell avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

python-nest's Issues

Unable to specify client-id and client-secret in config file

When added to a config file and called via --conf, the CLI spits out Missing client and secret. Either call with --client-id and --client-secret or add to config as client_id and client_secret.

It appears the functionality to read those variables from the configuration file isn't functional.

Issue with documentation on home page

if napi.authorization_required:
print('Go to ' + nest.authorize_url + ' to authorize, then enter PIN below')

Should use napi.authorize_url, not nest.authorize_url

nest protect

Is it possible to add nest protect information?

Use REST Streaming API

Now that this project uses the official Nest API (#49), has anyone looked into using the REST Streaming API ?
It would avoid polling the API, which is good for both not triggering rate limits, and receiving fast updates (push vs. poll).

This would potentially solve issues such as #106 and #58.

Invalid content sent when setting fan

I am attempting to turn the fan on and have been running into an error which seems to be coming from incompatibility between python-nest and the nest api.

When running "nest fan --on" from the command line I get the following:

Traceback (most recent call last):
File "/usr/local/bin/nest", line 11, in
sys.exit(main())
File "/usr/local/lib/python3.5/dist-packages/nest/command_line.py", line 210, in main
device.fan = True
File "/usr/local/lib/python3.5/dist-packages/nest/nest.py", line 298, in fan
self._set('device', {'fan_timer_active': mapped_value})
File "/usr/local/lib/python3.5/dist-packages/nest/nest.py", line 168, in _set
response = self._nest_api._put(path=path, data=data)
File "/usr/local/lib/python3.5/dist-packages/nest/nest.py", line 1576, in _put
return self._request('PUT', path, data=data)
File "/usr/local/lib/python3.5/dist-packages/nest/nest.py", line 1568, in _request
raise APIError(response)
nest.nest.APIError: Invalid content sent

Any pointers or suggestions would be great.

Add automatic deploy to PyPi

I'd be happy to add support for automatic deploy to PyPi-Test and PyPi.

Have recently figured that out for a little tool I wrote.

It would basically add two branches:

deploy
deploy-test

Any push into them would automatically package and upload python-nest. Only the version number would need to be incremented in a central location in preparation for new releases.
Both branches would need to be setup as protected so none of the forks or pull requests could push into them - only admins of the project.

It would require a few variables to be setup on Travis/CI to hold the PyPi-Test and PyPi user information (secure and encrypted, not visible to anybody).

It would completely automate the deployment step to PyPi and leverage the PyPi Test site to try out deployments before making them available on the live site.

You can an example on this type cli helper of mine:
https://github.com/fxstein/pubkey

Let me know if there is interest in automating that. Its a 20 min job to get this done.

AttributeError: 'Thermostat' object has no attribute 'hvac_mode'

Running this against a freshly setup Nest Thermostat, I get some useful info (address, temp, etc.) and then this:

Country : GB
num_thermostats : 1
Device: Hallway
Where: Hallway
Mode : heat
Traceback (most recent call last):
File "nesttest.py", line 39, in
print (' HVAC Mode: %s' % device.hvac_mode)
AttributeError: 'Thermostat' object has no attribute 'hvac_mode'

NestCam Support?

Would it be possible to add NestCam support please? Just being able to turn on/off would be a great start.

I'm using Home Assistant, which uses python-nest, and would love to be able to control the cams from inside HASS.

Incorrect implementation of event detection for Nest cameras

Event detection for Nestcams (as currently implemented) doesn't seem to work, at least in conjunction with homeassistant. Is this because the requirements for "is_ongoing" are too stringent? (Maybe the Nest API is very precise about events, and an event is only "ongoing" for a few milliseconds.) If that's the case, should this be fixed so that "ongoing" is more lenient? (E.g., cache the old last_event, check whether it differs from the new last_event. If so, and the time between the two is small enough, is_ongoing returns true.)

Simple Example

Hi,
can anyone send here an simple example that use the newest nest api?

thanks

400 Client Error: Bad Request (variation)

This may be a variation of #25, but with different-looking error messages. After a nest show:

Traceback (most recent call last):
  File "/usr/bin/nest", line 11, in <module>
    load_entry_point('python-nest==2.11.0', 'console_scripts', 'nest')()
  File "/usr/lib/python2.7/site-packages/nest/command_line.py", line 181, in main
    device = napi.devices[args.index]
  File "/usr/lib/python2.7/site-packages/nest/nest.py", line 1053, in devices
    for devid in self._status['device']]
  File "/usr/lib/python2.7/site-packages/nest/nest.py", line 1039, in _status
    url = self.urls['transport_url'] + '/v2/mobile/' + self.user
  File "/usr/lib/python2.7/site-packages/nest/nest.py", line 1067, in urls
    return self._session.auth.urls
  File "/usr/lib/python2.7/site-packages/nest/nest.py", line 167, in urls
    self._login()
  File "/usr/lib/python2.7/site-packages/nest/nest.py", line 133, in _login
    response.raise_for_status()
  File "/usr/lib/python2.7/site-packages/requests/models.py", line 884, in raise_for_status
    raise HTTPError(http_error_msg, response=self)
requests.exceptions.HTTPError: 400 Client Error: Bad Request for url: https://home.nest.com/user/login

Here is whay the config file looks like at the moment. (Un)Commenting the credential cache line does not change the error.

[DEFAULT]
user = [myusername]
password = [mypasswordwithlotsofnumbersandsymbols]
#token_cache = ~/.config/nest/cache

TypeError: float argument required, not NoneType

nest --token-cache nest.json --client-id xxxxxxxxxxx --client-secret xxxxxxxxxxx show
Device: Living Room (Salon)
Where: Living Room
Away                  : home
Mode                  : heat-cool
State                 : cooling
Can Heat              : True
Can Cool              : True
Has Humidifier        : None
Has Dehumidifier      : None
Has Fan               : False
Has Hot Water Control : None
Temp                  : 23.5C
Humidity              : 75.0%
Target                 : 19.5-23.0C
Traceback (most recent call last):
  File "/usr/local/bin/nest", line 9, in <module>
    load_entry_point('python-nest==3.4.0', 'console_scripts', 'nest')()
  File "build/bdist.linux-armv7l/egg/nest/command_line.py", line 300, in main
TypeError: float argument required, not NoneType

Add "Away" status to show

Is there any way to include the current Away (home, away, auto-away) status when running nest show?

I've added the following patch, which works:

diff --git a/nest/command_line.py b/nest/command_line.py
index 3dad7e0..4f0b3b7 100644
--- a/nest/command_line.py
+++ b/nest/command_line.py
@@ -248,6 +248,7 @@ def main():
             # TODO should pad key? old code put : out 35
             print('Device: %s' % device.name)
             print('Where: %s' % device.where)
+            print('Away     : %s' % napi.structures[0].away)
             print('Mode     : %s' % device.mode)
             print('State    : %s' % device.hvac_state)
             print('Fan      : %s' % device.fan)

but is obviously just a quick hack and doesn't take into account different devices/serials/structures as per the existing away command (I only have a single Nest thermostat, so this hack works for me).

The purpose of adding the "Away" status to the show command would be to eliminate one extra API call and potential rate limiting.

No support for eco mode

Looks like nest is changing their API to support a new mode called eco, currently the incorrect state is being returned for Nest Thermostats when the mode is set to eco.

New API status for external plugin

Hi all don't find how to contact you! This is not a real tickets.

What the status off all the new API and nest cam support ?

I'm certainly going to rewrite the @domogik nest plugin to have cam support. And was thinking about all those new function and API. Is it all available on pipy with last version?

Getting an error when trying to set temperature

>>> with nest.Nest(username, password) as napi:
...     for device in napi.devices:
...         device.temperature = 23
...
Traceback (most recent call last):
  File "<stdin>", line 3, in <module>
  File "C:\Python27\lib\site-packages\nest\nest.py", line 477, in temperature
    self.target = value
  File "C:\Python27\lib\site-packages\nest\nest.py", line 493, in target
    data['target_temperature_low'] = value[0]
TypeError: 'int' object has no attribute '__getitem__'

PIN Entry Fails on CLI

% nest --client-id=XXXXX --client-secret=XXXXX show
Go to https://home.nest.com/login/oauth2?client_id=... to authorize, then enter PIN below
PIN: MYPIN
Traceback (most recent call last):
  File "/usr/local/bin/nest", line 9, in <module>
    load_entry_point('python-nest==3.1.0', 'console_scripts', 'nest')()
  File "/usr/local/lib/python2.7/dist-packages/nest/command_line.py", line 140, in main
    pin = input("PIN: ")
  File "<string>", line 1, in <module>
NameError: name 'MYPIN' is not defined

Fix token caching

Token caching was never really tested and appears to be very broken (all requests with an old token result in a 400 being raised).

Set fan from libs

Hi trying to implement command in my @domogik plugin, i got this issue:

Traceback (most recent call last):
  File "nestautre.py", line 117, in <module>
    device.fan = "on"
  File "/usr/local/lib/python2.7/dist-packages/nest/nest.py", line 298, in fan
    self._set('device', {'fan_timer_active': mapped_value})
  File "/usr/local/lib/python2.7/dist-packages/nest/nest.py", line 168, in _set
    response = self._nest_api._put(path=path, data=data)
  File "/usr/local/lib/python2.7/dist-packages/nest/nest.py", line 1590, in _put
    return self._request('PUT', path, data=data)
  File "/usr/local/lib/python2.7/dist-packages/nest/nest.py", line 1582, in _request
    raise APIError(response)
nest.nest.APIError: Invalid content sent

I've tried device.fan = "on", device.fan = 'on', device.fan = on true/false True/False ....

Expired token

Is they're a way to implement an exception like token expired and add a method for Refresh files?

In fact what appens if the token as expired ?
How to handle this in external apps?

Nest Cmd Line Error After Install

Hello, after install I receive an error whenever I try to run nest.exe. This occurs for all parameters (even when only using the -h parameter).

File "C:\Python27\Scripts\nest-script.py", line 9, in
load_entry_point('python-nest==2.1', 'console_scripts', 'nest')()
File "C:\Python27\lib\site-packages\pkg_resources.py", line 339, in load_entry
_point
return get_distribution(dist).load_entry_point(group, name)
File "C:\Python27\lib\site-packages\pkg_resources.py", line 2470, in load_entr
y_point
return ep.load()
File "C:\Python27\lib\site-packages\pkg_resources.py", line 2184, in load
['name'])
ImportError: No module named nest_thermostat.command_line

I'm using Python 2.7. Thank you.

Setting Positional Argument Results in errors

example: attempt to set thermostat to away ("nest --user xxxxxx --password yyyyyy away away") results in "nest-script.py: error: unrecognized arguments: away"

example: attempt to set thermostat to home ("nest --user xxxxxx --password yyyyyy away home") results in "nest-script.py: error: unrecognized arguments: home"

example: attempt to set temperature to 73 ("nest --user xxxxxx --password yyyyyy temp 73") results in
Traceback (most recent call last):
File "C:\Python27\Scripts\nest-script.py", line 9, in
load_entry_point('python-nest==2.2', 'console_scripts', 'nest')()
File "C:\Python27\lib\site-packages\nest\command_line.py", line 164, in main
temp = convert_temp(args.temperature)
File "C:\Python27\lib\site-packages\nest\utils.py", line 12, in f_to_c
temp = decimal.Decimal(temp)
File "C:\Python27\lib\decimal.py", line 607, in new
raise ValueError('Invalid tuple size in creation of Decimal '
ValueError: Invalid tuple size in creation of Decimal from list or tuple. The l
ist or tuple should have exactly three elements.

However if the second parameter is not set ("away", "home" , "73"), the script correctly shows the current status of the positional argument.

I want to view the temperature change...

Hi Every one i want to show the temperature changes inside an while cicle...

napi = nest.Nest(username, password)
while(True):
structure = napi.structures[0]
device = structure.devices[0]
print(' Device %s Temp : %0.1fC' % (device.name,device.temperature))

But when i change temp inside nest simulator i dont view the changes...

Serial Number and Index Parameters Issue

The serial number option seems to work with many parameters (including the temp paramter) except the away parameter. I have two nest thermostats and usually supply the serial number in the command line to properly configure the appropriate thermostat. However, no matter what serial number I provide (or eliminate it completely) it only sets the away mode on one thermostat

All three of these commands sets the ABC thermostat:
nest --user xxxxxx --password yyyyyy --serial ABC away --away
nest --user xxxxxx --password yyyyyy --serial DEF away --away
nest --user xxxxxx --password yyyyyy away --away

The same occurs for the --home parameter. Unfortunately I wanted to set thermostat DEF.

Since the serial number parameter was not working, I tried the index parameter. Both of these resulted in ABC thermostat changing:
nest --user xxxxxx --password yyyyyy --index 1 away --away
nest --user xxxxxx --password yyyyyy --index 0 away --away

FYI - I encountered the same problem with the original smbaker script.

Thanks again!

Exception "unhandled KeyError" 'structure'

I'm getting this error when i run this code or the code provided:
I believe we are using the 3rd gen. nest

import nest
username = 'username'
password = 'password'
napi = nest.Nest(username,password)
for structure in napi.structures:
    print 'Structure %s' % structure.name

Error:

Exception "unhandled KeyError"
'structure'
File: C:\Python27\lib\site-packages\nest\nest.py, Line: 1064

Missing where names

Due to an upstream bug some devices will be assigned a where_id that is not
visible in the API. As a result we can't get a friendly name for the where and

As a result if we try and get the where property on the device we will the following trace:

Traceback (most recent call last):
  File "./python-nest-test.py", line 28, in <module>
    print('device.where: %s\n' % (repr(device.where)))
  File "/Users/cfb/scratch/nest/venv/lib/python2.7/site-packages/nest/nest.py", line 238, in where
    return self.structure.wheres[self.where_id]['name']

See https://nestdevelopers.io/t/missing-where-name-from-some-devices/1202 for details on the upstream issue.

Release Process

@jkoelker Is there a process for determining when a release should be triggered to PyPi?

Is it a unilateral call on your part currently or is there already decision making process with contributors providing input?

Thanks!

Unable to set temperature

I'm trying to set the temperature with the python API. When I try to say device.temp = 40, nothing happens. I've tried both in range mode and just AC mode, and nothing works.

Sett Temperature Throw device._set

How i can set temperature directly with python?

device._set(device.temperature,{'target_temperature':32})

Which is the correct command?

400 Client Error: Bad Request

Just downloaded and it doesn't seem to work. I get the following:

import nest
napi = nest.Nest("myusername", "mypassword")
for structure in napi.structures:
... print 'Structure %s' % structure.name
... print ' Away: %s' % structure.away
...
/usr/local/lib/python2.7/dist-packages/requests/packages/urllib3/util/ssl_.py:79: InsecurePlatformWarning: A true SSLContext object is not available. This prevents urllib3 from configuring SSL appropriately and may cause certain SSL connections to fail. For more information, see https://urllib3.readthedocs.org/en/latest/security.html#insecureplatformwarning.
InsecurePlatformWarning
Traceback (most recent call last):
File "", line 1, in
File "/usr/local/lib/python2.7/dist-packages/nest/nest.py", line 1033, in structures
for stid in self._status['structure']]
File "/usr/local/lib/python2.7/dist-packages/nest/nest.py", line 1009, in _status
url = self.urls['transport_url'] + '/v2/mobile/' + self.user
File "/usr/local/lib/python2.7/dist-packages/nest/nest.py", line 1037, in urls
return self._session.auth.urls
File "/usr/local/lib/python2.7/dist-packages/nest/nest.py", line 167, in urls
self._login()
File "/usr/local/lib/python2.7/dist-packages/nest/nest.py", line 133, in _login
response.raise_for_status()
File "/usr/local/lib/python2.7/dist-packages/requests/models.py", line 834, in raise_for_status
raise HTTPError(http_error_msg, response=self)
requests.exceptions.HTTPError: 400 Client Error: Bad Request

Current temp error

I used the sample code but can't get temp correctly.

Structure Kav_Office
    Away: False
    Devices:
        Device: 
Traceback (most recent call last):
  File "test.py", line 15, in <module>
    print '            Temp: %0.1f' % device.temperature
  File "/usr/local/lib/python2.7/dist-packages/nest/nest.py", line 473, in temperature
    return self._shared['current_temperature']
KeyError: 'current_temperature'

strftime() failing: TypeError: a float is required

Python-Nest version 2.7.0

API code from the example:

structure = napi.structures[0]
time_str = structure.weather.current.datetime.strftime('%Y-%m-%d %H:%M:%S')

fails with the error:

Traceback (most recent call last):
  File "NestTest.py", line 27, in <module>
    time_str = structure.weather.current.datetime.strftime('%Y-%m-%d %H:%M:%S')
  File "/Library/Python/2.7/site-packages/nest/nest.py", line 189, in datetime
    return datetime.datetime.fromtimestamp(self._time, self._tz)
TypeError: a float is required

I'm on Mac OS X Yosemite, python 2.7.10

Hardly any of the examples work

Whenever I try to use this script, I encounter problems and can't get hardly anything to work. Has something broken?

None of these examples work (when I use my own username and password, of course):

When I try:
nest --user [email protected] --password swordfish temp 73
I get:

Traceback (most recent call last):
  File "C:\Python27\Scripts\nest-script.py", line 9, in <module>
    load_entry_point('python-nest==2.3.1', 'console_scripts', 'nest')()
  File "C:\Python27\lib\site-packages\nest\command_line.py", line 200, in main
    device.temperature = temp
  File "C:\Python27\lib\site-packages\nest\nest.py", line 343, in temperature
    self.target = value
  File "C:\Python27\lib\site-packages\nest\nest.py", line 358, in target
    data['target_temperature_low'] = value[0]
TypeError: 'float' object has no attribute '__getitem__'

When I try:
nest --user [email protected] --password swordfish fan auto
I get:

usage: nest-script.py [-h] [--conf FILE] [--token-cache TOKEN_CACHE_FILE]
                      [-t TOKEN] [-u USER] [-p PASSWORD] [-c] [-s SERIAL]
                      [-S STRUCTURE] [-i INDEX]
                      {humid,target,temp,target_hum,away,show,fan,mode} ...
nest-script.py: error: unrecognized arguments: auto

When I try:
nest --user [email protected] --password swordfish target_hum 35
It seems to work, and I get:

35.0

When I try:
nest --user [email protected] --password swordfish show
It works, and returns a huge list of information about my nest account

Humidity reading accuracy

Hi all,

Can you help confirm expectation around the accuracy of device.humidity? I only ever seem to get values in increments of 5. I.e. 45, 50, 55. Right now the python-nest is reading 45, when it's 47 in the NEST app in reality.

Just wondered if this is a limitation of the NEST API or python-nest?

Many thanks for all you do.

Errors on Python 2.7.13 on Raspberry Pi

pi@raspberrypi:~ $ uname -a
Linux raspberrypi 4.9.41+ #1023 Tue Aug 8 15:47:12 BST 2017 armv6l GNU/Linux
pi@raspberrypi:~ $ python -V
Python 2.7.13
pi@raspberrypi:~ $ nest show
Device: Entryway
Where: None
Away                  : home
Mode                  : cool
State                 : None
Can Heat              : True
Can Cool              : True
Has Humidifier        : None
Has Dehumidifier      : None
Has Fan               : True
Fan                   : False
Fan Timer             : None
Has Hot Water Control : None
Temp                  : 74.0F
Traceback (most recent call last):
  File "/usr/local/bin/nest", line 11, in <module>
    sys.exit(main())
  File "/usr/local/lib/python2.7/dist-packages/nest/command_line.py", line 291, in main
    print('Humidity              : %0.1f%%' % device.humidity)
TypeError: float argument required, not NoneType

I also get errors trying to set temperature:

Traceback (most recent call last):
  File "/usr/local/bin/nest", line 11, in <module>
    sys.exit(main())
  File "/usr/local/lib/python2.7/dist-packages/nest/command_line.py", line 227, in main
    device.temperature = args.temperature
  File "/usr/local/lib/python2.7/dist-packages/nest/nest.py", line 501, in temperature
    self.target = value
  File "/usr/local/lib/python2.7/dist-packages/nest/nest.py", line 523, in target
    rounded_temp = self._round_temp(value)
  File "/usr/local/lib/python2.7/dist-packages/nest/nest.py", line 459, in _round_temp
    return int(round(temp))
TypeError: a float is required

Document releasing to pypi

From @jkoelker on #49 (comment)

For pypi releasing we just have to push to the deploy-test branch to get it on https://testpypi.python.org/pypi then to deploy to get it on pypi proper. This way if I ever go mia for a while it can still be updated by whoever has access to the repo. If you have a pypi username I can also add you as an owner there too so we have more redundancy.

Not sure the best place to put that info, not to confuse it with usage of the library.

Eco Temperature Issue

For some reason my Nest returns None for the Away Heat and Away Cool which causes the code to fail to display (since it's looking for a float).

The issue appears to be here.

My Python is super rusty this is ugly but I fixed it by switching to:

if isinstance(device.eco_temperature, tuple) and device.eco_temperature[0] != None and device.eco_tempera$
     print('Away Heat: %0.1fC' % device.eco_temperature[0])
     print('Away Cool: %0.1fC' % device.eco_temperature[1])

Cheers and thanks for the good library.

Polling structure.away

I have a program that polls structure.away every 30 seconds (along with a number of other things). All of them work except structure.away is never changed from the initial state when I create the napi connection. The first call to structure.away pull the correct state on instantiation, then is never updated if the away state changes.

UPDATE: This is not a python-nest issue. It looks like Nest itself updates the nest api for structures every 300 seconds. Therefore there is up to a 5 minute delay on away reporting. Is there a way to pull away state in the device that is updated much more often?

Crashing on Forecast call

File "/usr/lib/python2.7/site-packages/nest/nest.py", line 205, in init
Nest: fget('observation_epoch')))))
Nest: TypeError: float() argument must be a string or a number

Support for turning camera on and off

The API supports turning the camera off and on.

Implementation would look something like:

  • in nest/nest.py, update class Camera
  • add a new method for turning on/off
    • use ._set from NestBase for setting the is_streaming from the API (search that file for other examples)

cc @GussyH who asked about it in #44 (comment)

python-nest reports temperature in °F

The python-nest docs on pypi say:

In the API, all temperature values are in degrees celsius.

But the temperature attribute of thermostat objects appears to report the temperature in °F. I don't know if this is a doc bug, or a change in the API, or something else, but figured I would mention it.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.