跳转到主要内容

与Nest™恒温器通信的Python API和命令行工具

项目描述

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

安装

[sudo] pip install python-nest

注意 4.x 版本使用流式接口。要使用旧的轮询/缓存行为,请将您的需求限制为 python-nest<4.0

注意 3.x 版本使用Nest官方API。因此,一些功能已被删除,因为它们不可用。为了保留旧版本和功能,请确保将您的需求设置为 python-nest<3.0

巢开发者账户

您需要一个巢开发者账户和一个在巢开发者门户上的产品才能使用此模块。

  1. 访问巢开发者,并登录。如果您还没有账户,请创建一个。

  2. 填写账户详细信息。

  • “公司信息”可以是任何内容。

  1. 提交更改。

  2. 点击页面顶部的“产品”。

  3. 点击“创建新产品”。

  4. 填写详细信息。

  • 产品名称必须唯一。

  • 描述、用户、url都可以是您想要的任何内容。

  1. 对于权限,勾选所有复选框,如果有的话,选择读写选项。

  • 描述需要特定的格式才能被接受。

  1. 点击“创建产品”。

  2. 新产品页面打开后,“产品 ID”和“产品密钥”位于右侧。这些将用作下面的 client_id 和 client_secret。

用法

迁移到 4.x

版本 4.x 使用巢流式 API,这样您就可以获得您巢设备的几乎实时的状态更新。

如果您将 python-nest 作为命令行工具使用

您不需要更改,但有一个新的命令行选项 --keep-alive 您可以尝试一下。

如果您在轮询循环中使用 python-nest,以一定的时间间隔查询巢设备的属性,有几个显著的变化
  • 移除了内部缓存,StructureDevice对象将始终返回在巢 API 中呈现的当前状态。

  • 将为每个Nest对象保持持久的 HTTP 连接。因此,请避免在您的程序中创建多个 Nest 对象。

  • 您的轮询查询不会触达 API 速率限制,您可以增加轮询频率。

如果您想改为推送模式

您需要监听Nest.update_event。请注意,您所有结构和设备中的任何数据更改都将触发update_event。您不知道哪个字段被更新。

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)
如果您使用 asyncio

您必须将update_event.wait()包装在ThreadPoolExecutor中,例如

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)

模块

您可以导入该模块为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

在 API 中,所有温度值都是以设备设置的温度尺度(由device.temperature_scale属性确定)报告和设置的。

转换辅助函数位于utils模块中

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

utils 函数使用 decimal.Decimal 来确保精度。

命令行

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

必须指定一个配置文件,并使用它来与 NEST 智能恒温器进行通信的凭据。一旦完成并生成令牌,如果您使用默认的令牌位置,命令行选项将自动从其中读取。

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

为了方便,[NEST]部分也可以命名为[nest]。不要使用[DEFAULT],因为它无法读取

历史

此模块最初是nest_thermostat的一个分支,而pynest是它的分支。

项目详情


下载文件

下载适用于您平台的文件。如果您不确定选择哪个,请了解更多关于安装包的信息。

源分发

python-nest-4.2.0.tar.gz (24.5 kB 查看散列值)

上传时间

由以下支持

AWS AWS 云计算和安全赞助商 Datadog Datadog 监控 Fastly Fastly CDN Google Google 下载分析 Microsoft Microsoft PSF 赞助商 Pingdom Pingdom 监控 Sentry Sentry 错误日志 StatusPage StatusPage 状态页面