1
0
mirror of https://github.com/USA-RedDragon/badnest.git synced 2025-05-21 00:45:47 +01:00

Compare commits

...

35 Commits

Author SHA1 Message Date
Jacob McSwain
faa0c956db
Add retirement notice 2020-10-15 19:50:27 -05:00
Jacob McSwain
7ab48d968e Adapt @therealryanbonham's PR ()
This removes the formatting portion, which should have been a separate PR
2020-02-03 15:00:20 -06:00
Jacob McSwain
59bb5ae237 Update README 2020-02-03 14:47:43 -06:00
Jacob McSwain
d74dc3f2ea
Merge pull request from piit79/apparent-temp-offset
Update info.md with a note about seemingly off temperatures
2020-02-03 14:44:32 -06:00
Jacob McSwain
a5b57f0cf0
Merge pull request from piit79/nest-access-token
Switch from Nest username/password to user_id/access_token
2020-02-03 14:43:42 -06:00
Jacob McSwain
1069805ed8
Merge pull request from chrismarcellino/master
Add target humidity support to allow automation
2020-02-03 14:42:24 -06:00
Jacob McSwain
857463f3d4
Merge pull request from nonsleepr/thermostat-as-a-sensor
Expose thermostat as a sensor
2020-02-03 14:41:14 -06:00
Chris Marcellino
cbc8702ee0 Fix copy-past error in humidity setter code 2020-01-20 07:18:37 -06:00
Chris Marcellino
f1ebd8a2f7 Round humidity changes to nearest 5% instead of down 2020-01-19 15:09:22 -06:00
Petr Sedlacek
2e9378de06 Switch from Nest username/password to user_id/access_token
Username and password can no longer be used directly because of reCAPTCHA.
2020-01-14 15:25:48 +01:00
Petr Sedlacek
5b9cf52aff Update info.md with a note about seemingly off temperatures 2020-01-10 23:52:43 +01:00
Chris Marcellino
5b3c70e0ec Add target humidity support to allow automation 2019-12-13 16:42:47 -06:00
Alexander Bessonov
63da0e61b0 Expose thermostat as a sensor 2019-12-11 10:55:17 -05:00
Jacob McSwain
e55159b465
Merge pull request from USA-RedDragon/is_online-regression
Camera: Bugfix: online -> is_online
2019-11-04 09:16:04 -06:00
Jacob McSwain
933b7a017b
Camera: Bugfix: online -> is_online 2019-11-04 09:15:28 -06:00
Jacob McSwain
de8dfa1490
Merge pull request from USA-RedDragon/not-just-a-thermostat-pt-2
More changes to remove just a thermostat
2019-11-03 22:12:35 -06:00
Jacob McSwain
222f981692
More changes to remove just a thermostat 2019-11-03 22:12:12 -06:00
Jacob McSwain
cc7ec56d2a
Merge pull request from USA-RedDragon/not-just-a-thermostat
It's no longer just a thermostat
2019-11-03 22:09:50 -06:00
Jacob McSwain
385e97a62a
It's no longer just a thermostat 2019-11-03 22:09:20 -06:00
Jacob McSwain
fe6f04e645
Merge pull request from USA-RedDragon/readme-maintenance
Update README to reflect all the changes
2019-11-03 21:54:22 -06:00
Jacob McSwain
799d7a55dc
Update README to reflect all the changes 2019-11-03 21:53:31 -06:00
Jacob McSwain
0c87f7561a
Merge pull request from USA-RedDragon/nest_protect
Add preliminary Nest Protect support
2019-11-03 21:46:57 -06:00
Jacob McSwain
c9693df3a2
Merge pull request from USA-RedDragon/rewrite-api
Rewrite API to be a singleton
2019-11-03 21:45:22 -06:00
Jacob McSwain
2927881c33
Add preliminary Nest Protect support 2019-11-03 21:44:38 -06:00
Jacob McSwain
334ce8579f
Rewrite API to be a singleton
This should make error handling and extending this to more Nest platforms much easier
2019-11-03 21:43:45 -06:00
Jacob McSwain
98490b08f5
Merge pull request from USA-RedDragon/remove_api_key
Remove API Key from the config.
2019-11-03 17:29:12 -06:00
Jacob McSwain
7cef7c65a4
Remove API Key from the config.
Apparently this is public and shared, I was being overly protective.

Thanks to @gboudreau for this.

https://github.com/USA-RedDragon/badnest/issues/25
2019-11-03 17:28:27 -06:00
Jacob McSwain
c7ac77ca85
Merge pull request from USA-RedDragon/updates
Update readme and the gitignore
2019-11-03 17:14:00 -06:00
Jacob McSwain
dadf80f745
Update readme and the gitignore 2019-11-03 17:13:15 -06:00
Jacob McSwain
fa1a632d2b
Merge pull request from USA-RedDragon/multi-region-cameras
Add region config and use it to use correct camera URL
2019-11-03 17:08:23 -06:00
Vinod Mishra
b1447a4e6e
Add region config and use it to use correct camera URL 2019-11-03 17:05:05 -06:00
Jacob McSwain
3d49b85c50
Merge pull request from USA-RedDragon/cameras-multiple-api-instances
Attempt to make the camera's use different API instances
2019-10-23 21:48:30 -05:00
Jacob McSwain
4a6c88a6ef
Merge pull request from USA-RedDragon/api-fix-token-expiration
API: Handle KeyError to fix the expiration of tokens
2019-10-23 21:47:20 -05:00
Jacob McSwain
51efa759e8
Attempt to make the camera's use different API instances 2019-10-23 21:46:55 -05:00
Jacob McSwain
77bd36b4bd
API: Handle KeyError to fix the expiration of tokens 2019-10-23 21:29:24 -05:00
9 changed files with 691 additions and 445 deletions

8
.gitignore vendored

@ -91,3 +91,11 @@ ENV/
.vscode/ .vscode/
.DS_Store .DS_Store
__init__.py
api.py
camera.py
climate.py
const.py
manifest.json
sensor.py

@ -1,21 +1,22 @@
"""The example integration.""" """The example integration."""
import voluptuous as vol import voluptuous as vol
from homeassistant.helpers import config_validation as cv from homeassistant.helpers import config_validation as cv
from homeassistant.const import CONF_EMAIL, CONF_PASSWORD
from .const import DOMAIN, CONF_ISSUE_TOKEN, CONF_COOKIE, CONF_APIKEY from .api import NestAPI
from .const import DOMAIN, CONF_ISSUE_TOKEN, CONF_COOKIE, CONF_USER_ID, CONF_ACCESS_TOKEN, CONF_REGION
CONFIG_SCHEMA = vol.Schema( CONFIG_SCHEMA = vol.Schema(
{ {
DOMAIN: vol.All( DOMAIN: vol.All(
{ {
vol.Required(CONF_EMAIL, default=""): cv.string, vol.Required(CONF_USER_ID, default=""): cv.string,
vol.Required(CONF_PASSWORD, default=""): cv.string, vol.Required(CONF_ACCESS_TOKEN, default=""): cv.string,
vol.Optional(CONF_REGION, default="us"): cv.string,
}, },
{ {
vol.Required(CONF_ISSUE_TOKEN, default=""): cv.string, vol.Required(CONF_ISSUE_TOKEN, default=""): cv.string,
vol.Required(CONF_COOKIE, default=""): cv.string, vol.Required(CONF_COOKIE, default=""): cv.string,
vol.Required(CONF_APIKEY, default=""): cv.string vol.Optional(CONF_REGION, default="us"): cv.string,
} }
) )
}, },
@ -26,24 +27,26 @@ CONFIG_SCHEMA = vol.Schema(
def setup(hass, config): def setup(hass, config):
"""Set up the badnest component.""" """Set up the badnest component."""
if config.get(DOMAIN) is not None: if config.get(DOMAIN) is not None:
email = config[DOMAIN].get(CONF_EMAIL) user_id = config[DOMAIN].get(CONF_USER_ID)
password = config[DOMAIN].get(CONF_PASSWORD) access_token = config[DOMAIN].get(CONF_ACCESS_TOKEN)
issue_token = config[DOMAIN].get(CONF_ISSUE_TOKEN) issue_token = config[DOMAIN].get(CONF_ISSUE_TOKEN)
cookie = config[DOMAIN].get(CONF_COOKIE) cookie = config[DOMAIN].get(CONF_COOKIE)
api_key = config[DOMAIN].get(CONF_APIKEY) region = config[DOMAIN].get(CONF_REGION)
else: else:
email = None email = None
password = None password = None
issue_token = None issue_token = None
cookie = None cookie = None
api_key = None region = None
hass.data[DOMAIN] = { hass.data[DOMAIN] = {
CONF_EMAIL: email, 'api': NestAPI(
CONF_PASSWORD: password, user_id,
CONF_ISSUE_TOKEN: issue_token, access_token,
CONF_COOKIE: cookie, issue_token,
CONF_APIKEY: api_key cookie,
region,
),
} }
return True return True

@ -1,65 +1,90 @@
import requests
import logging import logging
import requests
API_URL = "https://home.nest.com" API_URL = "https://home.nest.com"
CAMERA_WEBAPI_BASE = "https://webapi.camera.home.nest.com" CAMERA_WEBAPI_BASE = "https://webapi.camera.home.nest.com"
CAMERA_URL = "https://nexusapi-us1.camera.home.nest.com"
USER_AGENT = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_5) " \ USER_AGENT = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_5) " \
"AppleWebKit/537.36 (KHTML, like Gecko) " \ "AppleWebKit/537.36 (KHTML, like Gecko) " \
"Chrome/75.0.3770.100 Safari/537.36" "Chrome/75.0.3770.100 Safari/537.36"
URL_JWT = "https://nestauthproxyservice-pa.googleapis.com/v1/issue_jwt" URL_JWT = "https://nestauthproxyservice-pa.googleapis.com/v1/issue_jwt"
# Nest website's (public) API key
NEST_API_KEY = "AIzaSyAdkSIMNc51XGNEAYWasX9UOWkS5P6sZE4"
KNOWN_BUCKET_TYPES = [
# Thermostats
"device",
"shared",
# Protect
"topaz",
# Temperature sensors
"kryptonite",
]
_LOGGER = logging.getLogger(__name__) _LOGGER = logging.getLogger(__name__)
class NestAPI: class NestAPI():
def __init__(self, def __init__(self,
email, user_id,
password, access_token,
issue_token, issue_token,
cookie, cookie,
api_key, region):
device_id=None): self.device_data = {}
self._user_id = None self._wheres = {}
self._access_token = None self._user_id = user_id
self._access_token = access_token
self._session = requests.Session() self._session = requests.Session()
self._session.headers.update({"Referer": "https://home.nest.com/"}) self._session.headers.update({
self._device_id = device_id "Referer": "https://home.nest.com/",
self._email = email "User-Agent": USER_AGENT,
self._password = password })
self._issue_token = issue_token self._issue_token = issue_token
self._cookie = cookie self._cookie = cookie
self._api_key = api_key self._czfe_url = None
self._camera_url = f'https://nexusapi-{region}1.camera.home.nest.com'
self.cameras = []
self.thermostats = []
self.temperature_sensors = []
self.protects = []
self.login() self.login()
self._get_devices()
self.update()
def __getitem__(self, name):
return getattr(self, name)
def __setitem__(self, name, value):
return setattr(self, name, value)
def __delitem__(self, name):
return delattr(self, name)
def __contains__(self, name):
return hasattr(self, name)
def login(self): def login(self):
if not self._email and not self._password: if self._issue_token and self._cookie:
self._login_google(self._issue_token, self._cookie, self._api_key) self._login_google(self._issue_token, self._cookie)
else: self._login_dropcam()
self._login_nest(self._email, self._password)
def _login_nest(self, email, password): def _login_google(self, issue_token, cookie):
r = self._session.post(
f"{API_URL}/session", json={"email": email, "password": password}
)
self._user_id = r.json()["userid"]
self._access_token = r.json()["access_token"]
def _login_google(self, issue_token, cookie, api_key):
headers = { headers = {
'Sec-Fetch-Mode': 'cors',
'User-Agent': USER_AGENT, 'User-Agent': USER_AGENT,
'Sec-Fetch-Mode': 'cors',
'X-Requested-With': 'XmlHttpRequest', 'X-Requested-With': 'XmlHttpRequest',
'Referer': 'https://accounts.google.com/o/oauth2/iframe', 'Referer': 'https://accounts.google.com/o/oauth2/iframe',
'cookie': cookie 'cookie': cookie
} }
r = requests.get(url=issue_token, headers=headers) r = self._session.get(url=issue_token, headers=headers)
access_token = r.json()['access_token'] access_token = r.json()['access_token']
headers = { headers = {
'Authorization': 'Bearer ' + access_token,
'User-Agent': USER_AGENT, 'User-Agent': USER_AGENT,
'x-goog-api-key': api_key, 'Authorization': 'Bearer ' + access_token,
'x-goog-api-key': NEST_API_KEY,
'Referer': 'https://home.nest.com' 'Referer': 'https://home.nest.com'
} }
params = { params = {
@ -68,46 +93,40 @@ class NestAPI:
"google_oauth_access_token": access_token, "google_oauth_access_token": access_token,
"policy_id": 'authproxy-oauth-policy' "policy_id": 'authproxy-oauth-policy'
} }
r = requests.post(url=URL_JWT, headers=headers, params=params) r = self._session.post(url=URL_JWT, headers=headers, params=params)
self._user_id = r.json()['claims']['subject']['nestId']['id'] self._user_id = r.json()['claims']['subject']['nestId']['id']
self._access_token = r.json()['jwt'] self._access_token = r.json()['jwt']
def _login_dropcam(self):
self._session.post(
f"{API_URL}/dropcam/api/login",
data={"access_token": self._access_token}
)
class NestThermostatAPI(NestAPI): def _get_cameras(self):
def __init__(self, cameras = []
email,
password,
issue_token,
cookie,
api_key,
device_id=None):
super(NestThermostatAPI, self).__init__(
email,
password,
issue_token,
cookie,
api_key,
device_id)
self._czfe_url = None
self._compressor_lockout_enabled = None
self._compressor_lockout_time = None
self._hvac_ac_state = None
self._hvac_heater_state = None
self.mode = None
self._time_to_target = None
self._fan_timer_timeout = None
self.can_heat = None
self.can_cool = None
self.has_fan = None
self.fan = None
self.current_temperature = None
self.target_temperature = None
self.target_temperature_high = None
self.target_temperature_low = None
self.current_humidity = None
self.update()
def get_devices(self): try:
r = self._session.get(
f"{CAMERA_WEBAPI_BASE}/api/cameras."
+ "get_owned_and_member_of_with_properties"
)
for camera in r.json()["items"]:
cameras.append(camera['uuid'])
self.device_data[camera['uuid']] = {}
return cameras
except requests.exceptions.RequestException as e:
_LOGGER.error(e)
_LOGGER.error('Failed to get cameras, trying again')
return self._get_cameras()
except KeyError:
_LOGGER.debug('Failed to get cameras, trying to log in again')
self.login()
return self._get_cameras()
def _get_devices(self):
try: try:
r = self._session.post( r = self._session.post(
f"{API_URL}/api/0.1/user/{self._user_id}/app_launch", f"{API_URL}/api/0.1/user/{self._user_id}/app_launch",
@ -117,292 +136,403 @@ class NestThermostatAPI(NestAPI):
}, },
headers={"Authorization": f"Basic {self._access_token}"}, headers={"Authorization": f"Basic {self._access_token}"},
) )
devices = []
self._czfe_url = r.json()["service_urls"]["urls"]["czfe_url"]
buckets = r.json()['updated_buckets'][0]['value']['buckets'] buckets = r.json()['updated_buckets'][0]['value']['buckets']
for bucket in buckets: for bucket in buckets:
if bucket.startswith('device.'): if bucket.startswith('topaz.'):
devices.append(bucket.replace('device.', '')) sn = bucket.replace('topaz.', '')
self.protects.append(sn)
self.device_data[sn] = {}
elif bucket.startswith('kryptonite.'):
sn = bucket.replace('kryptonite.', '')
self.temperature_sensors.append(sn)
self.device_data[sn] = {}
elif bucket.startswith('device.'):
sn = bucket.replace('device.', '')
self.thermostats.append(sn)
self.temperature_sensors.append(sn)
self.device_data[sn] = {}
self.cameras = self._get_cameras()
return devices
except requests.exceptions.RequestException as e: except requests.exceptions.RequestException as e:
_LOGGER.error(e) _LOGGER.error(e)
_LOGGER.error('Failed to get devices, trying to log in again') _LOGGER.error('Failed to get devices, trying again')
return self.get_devices()
except KeyError:
_LOGGER.debug('Failed to get devices, trying to log in again')
self.login() self.login()
return self.get_devices() return self.get_devices()
def get_action(self):
if self._hvac_ac_state: def _map_nest_protect_state(self, value):
return "cooling" if value == 0:
elif self._hvac_heater_state: return "Ok"
return "heating" elif value == 1 or value == 2:
return "Warning"
elif value == 3:
return "Emergency"
else: else:
return "off" return "Unknown"
def update(self): def update(self):
try: try:
# To get friendly names
r = self._session.post( r = self._session.post(
f"{API_URL}/api/0.1/user/{self._user_id}/app_launch", f"{API_URL}/api/0.1/user/{self._user_id}/app_launch",
json={ json={
"known_bucket_types": ["shared", "device"], "known_bucket_types": ["where"],
"known_bucket_versions": [], "known_bucket_versions": [],
}, },
headers={"Authorization": f"Basic {self._access_token}"}, headers={"Authorization": f"Basic {self._access_token}"},
) )
self._czfe_url = r.json()["service_urls"]["urls"]["czfe_url"]
temp_mode = None
for bucket in r.json()["updated_buckets"]: for bucket in r.json()["updated_buckets"]:
if bucket["object_key"] \ sensor_data = bucket["value"]
.startswith(f"shared.{self._device_id}"): sn = bucket["object_key"].split('.')[1]
thermostat_data = bucket["value"] if bucket["object_key"].startswith(
self.current_temperature = \ f"where.{sn}"):
thermostat_data["current_temperature"] wheres = sensor_data['wheres']
self.target_temperature = \ for where in wheres:
thermostat_data["target_temperature"] self._wheres[where['where_id']] = where['name']
self._compressor_lockout_enabled = thermostat_data[
"compressor_lockout_enabled" r = self._session.post(
f"{API_URL}/api/0.1/user/{self._user_id}/app_launch",
json={
"known_bucket_types": KNOWN_BUCKET_TYPES,
"known_bucket_versions": [],
},
headers={"Authorization": f"Basic {self._access_token}"},
)
for bucket in r.json()["updated_buckets"]:
sensor_data = bucket["value"]
sn = bucket["object_key"].split('.')[1]
# Thermostats (thermostat and sensors system)
if bucket["object_key"].startswith(
f"shared.{sn}"):
self.device_data[sn]['current_temperature'] = \
sensor_data["current_temperature"]
self.device_data[sn]['target_temperature'] = \
sensor_data["target_temperature"]
self.device_data[sn]['hvac_ac_state'] = \
sensor_data["hvac_ac_state"]
self.device_data[sn]['hvac_heater_state'] = \
sensor_data["hvac_heater_state"]
self.device_data[sn]['target_temperature_high'] = \
sensor_data["target_temperature_high"]
self.device_data[sn]['target_temperature_low'] = \
sensor_data["target_temperature_low"]
self.device_data[sn]['can_heat'] = \
sensor_data["can_heat"]
self.device_data[sn]['can_cool'] = \
sensor_data["can_cool"]
self.device_data[sn]['mode'] = \
sensor_data["target_temperature_type"]
if self.device_data[sn]['hvac_ac_state']:
self.device_data[sn]['action'] = "cooling"
elif self.device_data[sn]['hvac_heater_state']:
self.device_data[sn]['action'] = "heating"
else:
self.device_data[sn]['action'] = "off"
# Thermostats, pt 2
elif bucket["object_key"].startswith(
f"device.{sn}"):
self.device_data[sn]['name'] = self._wheres[
sensor_data['where_id']
] ]
self._compressor_lockout_time = thermostat_data[ # When acts as a sensor
"compressor_lockout_timeout" if 'backplate_temperature' in sensor_data:
self.device_data[sn]['temperature'] = \
sensor_data['backplate_temperature']
if 'battery_level' in sensor_data:
self.device_data[sn]['battery_level'] = \
sensor_data['battery_level']
if sensor_data.get('description', None):
self.device_data[sn]['name'] += \
f' ({sensor_data["description"]})'
self.device_data[sn]['name'] += ' Thermostat'
self.device_data[sn]['has_fan'] = \
sensor_data["has_fan"]
self.device_data[sn]['fan'] = \
sensor_data["fan_timer_timeout"]
self.device_data[sn]['current_humidity'] = \
sensor_data["current_humidity"]
self.device_data[sn]['target_humidity'] = \
sensor_data["target_humidity"]
self.device_data[sn]['target_humidity_enabled'] = \
sensor_data["target_humidity_enabled"]
if sensor_data["eco"]["mode"] == 'manual-eco' or \
sensor_data["eco"]["mode"] == 'auto-eco':
self.device_data[sn]['eco'] = True
else:
self.device_data[sn]['eco'] = False
# Protect
elif bucket["object_key"].startswith(
f"topaz.{sn}"):
self.device_data[sn]['name'] = self._wheres[
sensor_data['where_id']
] ]
self._hvac_ac_state = thermostat_data["hvac_ac_state"] if sensor_data.get('description', None):
self._hvac_heater_state = \ self.device_data[sn]['name'] += \
thermostat_data["hvac_heater_state"] f' ({sensor_data["description"]})'
if temp_mode is None: self.device_data[sn]['name'] += ' Protect'
temp_mode = thermostat_data["target_temperature_type"] self.device_data[sn]['co_status'] = \
self.target_temperature_high = thermostat_data[ self._map_nest_protect_state(sensor_data['co_status'])
"target_temperature_high" self.device_data[sn]['smoke_status'] = \
self._map_nest_protect_state(sensor_data['smoke_status'])
self.device_data[sn]['battery_health_state'] = \
self._map_nest_protect_state(sensor_data['battery_health_state'])
# Temperature sensors
elif bucket["object_key"].startswith(
f"kryptonite.{sn}"):
self.device_data[sn]['name'] = self._wheres[
sensor_data['where_id']
] ]
self.target_temperature_low = \ if sensor_data.get('description', None):
thermostat_data["target_temperature_low"] self.device_data[sn]['name'] += \
self.can_heat = thermostat_data["can_heat"] f' ({sensor_data["description"]})'
self.can_cool = thermostat_data["can_cool"] self.device_data[sn]['name'] += ' Temperature'
elif bucket["object_key"] \ self.device_data[sn]['temperature'] = \
.startswith(f"device.{self._device_id}"): sensor_data['current_temperature']
thermostat_data = bucket["value"] self.device_data[sn]['battery_level'] = \
self._time_to_target = thermostat_data["time_to_target"] sensor_data['battery_level']
self._fan_timer_timeout = \
thermostat_data["fan_timer_timeout"] # Cameras
self.has_fan = thermostat_data["has_fan"] for camera in self.cameras:
self.fan = thermostat_data["fan_timer_timeout"] > 0 r = self._session.get(
self.current_humidity = thermostat_data["current_humidity"] f"{API_URL}/dropcam/api/cameras/{camera}"
if thermostat_data["eco"]["mode"] == 'manual-eco' or \ )
thermostat_data["eco"]["mode"] == 'auto-eco': sensor_data = r.json()[0]
temp_mode = 'eco' self.device_data[camera]['name'] = \
self.mode = temp_mode sensor_data["name"]
self.device_data[camera]['is_online'] = \
sensor_data["is_online"]
self.device_data[camera]['is_streaming'] = \
sensor_data["is_streaming"]
self.device_data[camera]['battery_voltage'] = \
sensor_data["rq_battery_battery_volt"]
self.device_data[camera]['ac_voltage'] = \
sensor_data["rq_battery_vbridge_volt"]
self.device_data[camera]['location'] = \
sensor_data["location"]
self.device_data[camera]['data_tier'] = \
sensor_data["properties"]["streaming.data-usage-tier"]
except requests.exceptions.RequestException as e: except requests.exceptions.RequestException as e:
_LOGGER.error(e) _LOGGER.error(e)
_LOGGER.error('Failed to update, trying to log in again') _LOGGER.error('Failed to update, trying again')
self.update()
except KeyError:
_LOGGER.debug('Failed to update, trying to log in again')
self.login() self.login()
self.update() self.update()
def set_temp(self, temp, temp_high=None): def thermostat_set_temperature(self, device_id, temp, temp_high=None):
if temp_high is None: if device_id not in self.thermostats:
return
try:
if temp_high is None:
self._session.post(
f"{self._czfe_url}/v5/put",
json={
"objects": [
{
"object_key": f'shared.{device_id}',
"op": "MERGE",
"value": {"target_temperature": temp},
}
]
},
headers={"Authorization": f"Basic {self._access_token}"},
)
else:
self._session.post(
f"{self._czfe_url}/v5/put",
json={
"objects": [
{
"object_key": f'shared.{device_id}',
"op": "MERGE",
"value": {
"target_temperature_low": temp,
"target_temperature_high": temp_high,
},
}
]
},
headers={"Authorization": f"Basic {self._access_token}"},
)
except requests.exceptions.RequestException as e:
_LOGGER.error(e)
_LOGGER.error('Failed to set temperature, trying again')
self.thermostat_set_temperature(device_id, temp, temp_high)
except KeyError:
_LOGGER.debug('Failed to set temperature, trying to log in again')
self.login()
self.thermostat_set_temperature(device_id, temp, temp_high)
def thermostat_set_target_humidity(self, device_id, humidity):
if device_id not in self.thermostats:
return
try:
self._session.post( self._session.post(
f"{self._czfe_url}/v5/put", f"{self._czfe_url}/v5/put",
json={ json={
"objects": [ "objects": [
{ {
"object_key": f'shared.{self._device_id}', "object_key": f'device.{device_id}',
"op": "MERGE", "op": "MERGE",
"value": {"target_temperature": temp}, "value": {"target_humidity": humidity},
} }
] ]
}, },
headers={"Authorization": f"Basic {self._access_token}"}, headers={"Authorization": f"Basic {self._access_token}"},
) )
else: except requests.exceptions.RequestException as e:
_LOGGER.error(e)
_LOGGER.error('Failed to set humidity, trying again')
self.thermostat_set_target_humidity(device_id, humidity)
except KeyError:
_LOGGER.debug('Failed to set humidity, trying to log in again')
self.login()
self.thermostat_set_target_humidity(device_id, humidity)
def thermostat_set_mode(self, device_id, mode):
if device_id not in self.thermostats:
return
try:
self._session.post( self._session.post(
f"{self._czfe_url}/v5/put", f"{self._czfe_url}/v5/put",
json={ json={
"objects": [ "objects": [
{ {
"object_key": f'shared.{self._device_id}', "object_key": f'shared.{device_id}',
"op": "MERGE", "op": "MERGE",
"value": { "value": {"target_temperature_type": mode},
"target_temperature_low": temp,
"target_temperature_high": temp_high,
},
} }
] ]
}, },
headers={"Authorization": f"Basic {self._access_token}"}, headers={"Authorization": f"Basic {self._access_token}"},
) )
except requests.exceptions.RequestException as e:
_LOGGER.error(e)
_LOGGER.error('Failed to set mode, trying again')
self.thermostat_set_mode(device_id, mode)
except KeyError:
_LOGGER.debug('Failed to set mode, trying to log in again')
self.login()
self.thermostat_set_mode(device_id, mode)
def set_mode(self, mode): def thermostat_set_fan(self, device_id, date):
self._session.post( if device_id not in self.thermostats:
f"{self._czfe_url}/v5/put", return
json={
"objects": [
{
"object_key": f'shared.{self._device_id}',
"op": "MERGE",
"value": {"target_temperature_type": mode},
}
]
},
headers={"Authorization": f"Basic {self._access_token}"},
)
def set_fan(self, date): try:
self._session.post( self._session.post(
f"{self._czfe_url}/v5/put", f"{self._czfe_url}/v5/put",
json={ json={
"objects": [ "objects": [
{ {
"object_key": f'device.{self._device_id}', "object_key": f'device.{device_id}',
"op": "MERGE", "op": "MERGE",
"value": {"fan_timer_timeout": date}, "value": {"fan_timer_timeout": date},
} }
] ]
}, },
headers={"Authorization": f"Basic {self._access_token}"}, headers={"Authorization": f"Basic {self._access_token}"},
) )
except requests.exceptions.RequestException as e:
_LOGGER.error(e)
_LOGGER.error('Failed to set fan, trying again')
self.thermostat_set_fan(device_id, date)
except KeyError:
_LOGGER.debug('Failed to set fan, trying to log in again')
self.login()
self.thermostat_set_fan(device_id, date)
def set_eco_mode(self, state): def thermostat_set_eco_mode(self, device_id, state):
mode = 'manual-eco' if state else 'schedule' if device_id not in self.thermostats:
self._session.post( return
f"{self._czfe_url}/v5/put",
json={
"objects": [
{
"object_key": f'device.{self._device_id}',
"op": "MERGE",
"value": {"eco": {"mode": mode}},
}
]
},
headers={"Authorization": f"Basic {self._access_token}"},
)
try:
mode = 'manual-eco' if state else 'schedule'
self._session.post(
f"{self._czfe_url}/v5/put",
json={
"objects": [
{
"object_key": f'device.{device_id}',
"op": "MERGE",
"value": {"eco": {"mode": mode}},
}
]
},
headers={"Authorization": f"Basic {self._access_token}"},
)
except requests.exceptions.RequestException as e:
_LOGGER.error(e)
_LOGGER.error('Failed to set eco, trying again')
self.thermostat_set_eco_mode(device_id, state)
except KeyError:
_LOGGER.debug('Failed to set eco, trying to log in again')
self.login()
self.thermostat_set_eco_mode(device_id, state)
class NestTemperatureSensorAPI(NestAPI): def _camera_set_properties(self, device_id, property, value):
def __init__(self, if device_id not in self.cameras:
email, return
password,
issue_token,
cookie,
api_key,
device_id=None):
super(NestTemperatureSensorAPI, self).__init__(
email,
password,
issue_token,
cookie,
api_key,
device_id)
self.temperature = None
self._device_id = device_id
self.update()
def get_devices(self): try:
r = self._session.post( r = self._session.post(
f"{API_URL}/api/0.1/user/{self._user_id}/app_launch", f"{CAMERA_WEBAPI_BASE}/api/dropcams.set_properties",
json={ data={property: value, "uuid": device_id},
"known_bucket_types": ["buckets"], )
"known_bucket_versions": [],
},
headers={"Authorization": f"Basic {self._access_token}"},
)
devices = []
buckets = r.json()['updated_buckets'][0]['value']['buckets']
for bucket in buckets:
if bucket.startswith('kryptonite.'):
devices.append(bucket.replace('kryptonite.', ''))
return devices return r.json()["items"]
except requests.exceptions.RequestException as e:
_LOGGER.error(e)
_LOGGER.error('Failed to set camera property, trying again')
return self._camera_set_properties(device_id, property, value)
except KeyError:
_LOGGER.debug('Failed to set camera property, ' +
'trying to log in again')
self.login()
return self._camera_set_properties(device_id, property, value)
def update(self): def camera_turn_off(self, device_id):
r = self._session.post( if device_id not in self.cameras:
f"{API_URL}/api/0.1/user/{self._user_id}/app_launch", return
json={
"known_bucket_types": ["kryptonite"],
"known_bucket_versions": [],
},
headers={"Authorization": f"Basic {self._access_token}"},
)
for bucket in r.json()["updated_buckets"]: return self._set_properties(device_id, "streaming.enabled", "false")
if bucket["object_key"].startswith(
f"kryptonite.{self._device_id}"):
sensor_data = bucket["value"]
self.temperature = sensor_data["current_temperature"]
self.battery_level = sensor_data["battery_level"]
def camera_turn_on(self, device_id):
if device_id not in self.cameras:
return
class NestCameraAPI(NestAPI): return self._set_properties(device_id, "streaming.enabled", "true")
def __init__(self, email, password, issue_token, cookie, api_key):
super(NestCameraAPI, self).__init__(
email,
password,
issue_token,
cookie,
api_key)
# log into dropcam
self._session.post(
f"{API_URL}/dropcam/api/login",
data={"access_token": self._access_token}
)
self.location = None
self.name = "Nest Camera"
self.online = None
self.is_streaming = None
self.battery_voltage = None
self.ac_voltge = None
self.data_tier = None
self.update()
def set_device(self, uuid): def camera_get_image(self, device_id, now):
self._device_id = uuid if device_id not in self.cameras:
self.update() return
def update(self): try:
if self._device_id: r = self._session.get(
props = self.get_properties() f'{self._camera_url}/get_image?uuid={device_id}' +
self._location = None f'&cachebuster={now}'
self.name = props["name"] )
self.online = props["is_online"]
self.is_streaming = props["is_streaming"]
self.battery_voltage = props["rq_battery_battery_volt"]
self.ac_voltge = props["rq_battery_vbridge_volt"]
self.location = props["location"]
self.data_tier = props["properties"]["streaming.data-usage-tier"]
def _set_properties(self, property, value): return r.content
r = self._session.post( except requests.exceptions.RequestException as e:
f"{CAMERA_WEBAPI_BASE}/api/dropcams.set_properties", _LOGGER.error(e)
data={property: value, "uuid": self._device_id}, _LOGGER.error('Failed to get camera image, trying again')
) return self.camera_get_image(device_id, now)
except KeyError:
return r.json()["items"] _LOGGER.debug('Failed to get camera image, trying to log in again')
self.login()
def get_properties(self): return self.camera_get_image(device_id, now)
r = self._session.get(
f"{API_URL}/dropcam/api/cameras/{self._device_id}"
)
return r.json()[0]
def get_cameras(self):
r = self._session.get(
f"{CAMERA_WEBAPI_BASE}/api/cameras."
+ "get_owned_and_member_of_with_properties"
)
return r.json()["items"]
# def set_upload_quality(self, quality):
# quality = str(quality)
# return self._set_properties("streaming.data-usage-tier", quality)
def turn_off(self):
return self._set_properties("streaming.enabled", "false")
def turn_on(self):
return self._set_properties("streaming.enabled", "true")
def get_image(self, now):
r = self._session.get(
f"{CAMERA_URL}/get_image?uuid={self._device_id}&cachebuster={now}"
)
return r.content

@ -1,44 +1,32 @@
"""This component provides basic support for Foscam IP cameras.""" """This component provides basic support for Foscam IP cameras."""
import logging import logging
from datetime import timedelta from datetime import timedelta
from homeassistant.components.camera import (
Camera,
SUPPORT_ON_OFF,
)
from homeassistant.util.dt import utcnow from homeassistant.util.dt import utcnow
from homeassistant.components.camera import Camera, SUPPORT_ON_OFF from .const import (
DOMAIN
from homeassistant.const import CONF_EMAIL, CONF_PASSWORD )
from .api import NestCameraAPI
from .const import DOMAIN, CONF_ISSUE_TOKEN, CONF_COOKIE, CONF_APIKEY
_LOGGER = logging.getLogger(__name__) _LOGGER = logging.getLogger(__name__)
DEFAULT_NAME = "Nest Camera"
DATA_KEY = "camera.badnest"
async def async_setup_platform(hass, async def async_setup_platform(hass,
config, config,
async_add_entities, async_add_entities,
discovery_info=None): discovery_info=None):
"""Set up a Nest Camera.""" """Set up a Nest Camera."""
hass.data[DATA_KEY] = dict() api = hass.data[DOMAIN]['api']
api = NestCameraAPI(
hass.data[DOMAIN][CONF_EMAIL],
hass.data[DOMAIN][CONF_PASSWORD],
hass.data[DOMAIN][CONF_ISSUE_TOKEN],
hass.data[DOMAIN][CONF_COOKIE],
hass.data[DOMAIN][CONF_APIKEY]
)
# cameras = await hass.async_add_executor_job(nest.get_cameras())
cameras = [] cameras = []
_LOGGER.info("Adding cameras") _LOGGER.info("Adding temperature sensors")
for camera in api.get_cameras(): for camera in api['cameras']:
_LOGGER.info("Adding nest cam uuid: %s", camera["uuid"]) _LOGGER.info(f"Adding nest camera uuid: {camera}")
device = NestCamera(camera["uuid"], api) cameras.append(NestCamera(camera, api))
cameras.append(device)
hass.data[DATA_KEY][camera["uuid"]] = device
async_add_entities(cameras) async_add_entities(cameras)
@ -50,7 +38,6 @@ class NestCamera(Camera):
"""Initialize a Nest camera.""" """Initialize a Nest camera."""
super().__init__() super().__init__()
self._uuid = uuid self._uuid = uuid
api.set_device(self._uuid)
self._device = api self._device = api
self._time_between_snapshots = timedelta(seconds=30) self._time_between_snapshots = timedelta(seconds=30)
self._last_image = None self._last_image = None
@ -61,7 +48,7 @@ class NestCamera(Camera):
"""Return information about the device.""" """Return information about the device."""
return { return {
"identifiers": {(DOMAIN, self._uuid)}, "identifiers": {(DOMAIN, self._uuid)},
"name": self.name, "name": self._device.device_data[self._uuid]['name'],
"manufacturer": "Nest Labs", "manufacturer": "Nest Labs",
"model": "Camera", "model": "Camera",
} }
@ -78,20 +65,20 @@ class NestCamera(Camera):
@property @property
def is_on(self): def is_on(self):
"""Return true if on.""" """Return true if on."""
return self._device.online return self._device.device_data[self._uuid]['is_online']
@property @property
def is_recording(self): def is_recording(self):
return True return True
"""Return true if the device is recording.""" """Return true if the device is recording."""
return self._device.is_streaming return self._device.device_data[self._uuid]['is_streaming']
def turn_off(self): def turn_off(self):
self._device.turn_off() self._device.camera_turn_off(self._uuid)
self.schedule_update_ha_state() self.schedule_update_ha_state()
def turn_on(self): def turn_on(self):
self._device.turn_on() self._device.camera_turn_on(self._uuid)
self.schedule_update_ha_state() self.schedule_update_ha_state()
@property @property
@ -106,7 +93,7 @@ class NestCamera(Camera):
@property @property
def name(self): def name(self):
"""Return the name of this camera.""" """Return the name of this camera."""
return self._device.name return self._device.device_data[self._uuid]['name']
def _ready_for_snapshot(self, now): def _ready_for_snapshot(self, now):
return self._next_snapshot_at is None or now > self._next_snapshot_at return self._next_snapshot_at is None or now > self._next_snapshot_at
@ -115,8 +102,7 @@ class NestCamera(Camera):
"""Return a still image response from the camera.""" """Return a still image response from the camera."""
now = utcnow() now = utcnow()
if self._ready_for_snapshot(now) or True: if self._ready_for_snapshot(now) or True:
image = self._device.get_image(now) image = self._device.camera_get_image(self._uuid, now)
# _LOGGER.info(image)
self._next_snapshot_at = now + self._time_between_snapshots self._next_snapshot_at = now + self._time_between_snapshots
self._last_image = image self._last_image = image

@ -16,6 +16,7 @@ from homeassistant.components.climate.const import (
SUPPORT_PRESET_MODE, SUPPORT_PRESET_MODE,
SUPPORT_TARGET_TEMPERATURE, SUPPORT_TARGET_TEMPERATURE,
SUPPORT_TARGET_TEMPERATURE_RANGE, SUPPORT_TARGET_TEMPERATURE_RANGE,
SUPPORT_TARGET_HUMIDITY,
PRESET_ECO, PRESET_ECO,
PRESET_NONE, PRESET_NONE,
CURRENT_HVAC_HEAT, CURRENT_HVAC_HEAT,
@ -25,12 +26,11 @@ from homeassistant.components.climate.const import (
from homeassistant.const import ( from homeassistant.const import (
ATTR_TEMPERATURE, ATTR_TEMPERATURE,
TEMP_CELSIUS, TEMP_CELSIUS,
CONF_EMAIL,
CONF_PASSWORD,
) )
from .api import NestThermostatAPI from .const import (
from .const import DOMAIN, CONF_ISSUE_TOKEN, CONF_COOKIE, CONF_APIKEY DOMAIN,
)
NEST_MODE_HEAT_COOL = "range" NEST_MODE_HEAT_COOL = "range"
NEST_MODE_ECO = "eco" NEST_MODE_ECO = "eco"
@ -53,6 +53,10 @@ ACTION_NEST_TO_HASS = {
MODE_NEST_TO_HASS = {v: k for k, v in MODE_HASS_TO_NEST.items()} MODE_NEST_TO_HASS = {v: k for k, v in MODE_HASS_TO_NEST.items()}
ROUND_TARGET_HUMIDITY_TO_NEAREST = 5
NEST_HUMIDITY_MIN = 10
NEST_HUMIDITY_MAX = 60
PRESET_MODES = [PRESET_NONE, PRESET_ECO] PRESET_MODES = [PRESET_NONE, PRESET_ECO]
_LOGGER = logging.getLogger(__name__) _LOGGER = logging.getLogger(__name__)
@ -63,26 +67,13 @@ async def async_setup_platform(hass,
async_add_entities, async_add_entities,
discovery_info=None): discovery_info=None):
"""Set up the Nest climate device.""" """Set up the Nest climate device."""
api = NestThermostatAPI( api = hass.data[DOMAIN]['api']
hass.data[DOMAIN][CONF_EMAIL],
hass.data[DOMAIN][CONF_PASSWORD],
hass.data[DOMAIN][CONF_ISSUE_TOKEN],
hass.data[DOMAIN][CONF_COOKIE],
hass.data[DOMAIN][CONF_APIKEY]
)
thermostats = [] thermostats = []
_LOGGER.info("Adding thermostats") _LOGGER.info("Adding thermostats")
for thermostat in api.get_devices(): for thermostat in api['thermostats']:
_LOGGER.info(f"Adding nest thermostat uuid: {thermostat}") _LOGGER.info(f"Adding nest thermostat uuid: {thermostat}")
thermostats.append(NestClimate(thermostat, NestThermostatAPI( thermostats.append(NestClimate(thermostat, api))
hass.data[DOMAIN][CONF_EMAIL],
hass.data[DOMAIN][CONF_PASSWORD],
hass.data[DOMAIN][CONF_ISSUE_TOKEN],
hass.data[DOMAIN][CONF_COOKIE],
hass.data[DOMAIN][CONF_APIKEY],
thermostat
)))
async_add_entities(thermostats) async_add_entities(thermostats)
@ -105,28 +96,38 @@ class NestClimate(ClimateDevice):
self.device = api self.device = api
if self.device.can_heat and self.device.can_cool: if self.device.device_data[device_id]['can_heat'] \
and self.device.device_data[device_id]['can_cool']:
self._operation_list.append(HVAC_MODE_AUTO) self._operation_list.append(HVAC_MODE_AUTO)
self._support_flags |= SUPPORT_TARGET_TEMPERATURE_RANGE self._support_flags |= SUPPORT_TARGET_TEMPERATURE_RANGE
# Add supported nest thermostat features # Add supported nest thermostat features
if self.device.can_heat: if self.device.device_data[device_id]['can_heat']:
self._operation_list.append(HVAC_MODE_HEAT) self._operation_list.append(HVAC_MODE_HEAT)
if self.device.can_cool: if self.device.device_data[device_id]['can_cool']:
self._operation_list.append(HVAC_MODE_COOL) self._operation_list.append(HVAC_MODE_COOL)
self._operation_list.append(HVAC_MODE_OFF) self._operation_list.append(HVAC_MODE_OFF)
# feature of device # feature of device
if self.device.has_fan: if self.device.device_data[device_id]['has_fan']:
self._support_flags = self._support_flags | SUPPORT_FAN_MODE self._support_flags = self._support_flags | SUPPORT_FAN_MODE
if self.device.device_data[device_id]['target_humidity_enabled']:
self._support_flags = self._support_flags | SUPPORT_TARGET_HUMIDITY
@property @property
def unique_id(self): def unique_id(self):
"""Return an unique ID.""" """Return an unique ID."""
return self.device_id return self.device_id
@property
def name(self):
"""Return an friendly name."""
return self.device.device_data[self.device_id]['name']
@property @property
def supported_features(self): def supported_features(self):
"""Return the list of supported features.""" """Return the list of supported features."""
@ -137,11 +138,6 @@ class NestClimate(ClimateDevice):
"""Return the polling state.""" """Return the polling state."""
return True return True
@property
def name(self):
"""Return the name of the climate device."""
return self.device_id
@property @property
def temperature_unit(self): def temperature_unit(self):
"""Return the unit of measurement.""" """Return the unit of measurement."""
@ -150,53 +146,78 @@ class NestClimate(ClimateDevice):
@property @property
def current_temperature(self): def current_temperature(self):
"""Return the current temperature.""" """Return the current temperature."""
return self.device.current_temperature return self.device.device_data[self.device_id]['current_temperature']
@property @property
def current_humidity(self): def current_humidity(self):
"""Return the current humidity.""" """Return the current humidity."""
return self.device.current_humidity return self.device.device_data[self.device_id]['current_humidity']
@property
def target_humidity(self):
"""Return the target humidity."""
return self.device.device_data[self.device_id]['target_humidity']
@property
def min_humidity(self):
"""Return the min target humidity."""
return NEST_HUMIDITY_MIN
@property
def max_humidity(self):
"""Return the max target humidity."""
return NEST_HUMIDITY_MAX
@property @property
def target_temperature(self): def target_temperature(self):
"""Return the temperature we try to reach.""" """Return the temperature we try to reach."""
if self.device.mode not in (NEST_MODE_HEAT_COOL, NEST_MODE_ECO): if self.device.device_data[self.device_id]['mode'] \
return self.device.target_temperature != NEST_MODE_HEAT_COOL \
and not self.device.device_data[self.device_id]['eco']:
return \
self.device.device_data[self.device_id]['target_temperature']
return None return None
@property @property
def target_temperature_high(self): def target_temperature_high(self):
"""Return the highbound target temperature we try to reach.""" """Return the highbound target temperature we try to reach."""
if self.device.mode == NEST_MODE_ECO: if self.device.device_data[self.device_id]['mode'] \
# TODO: Grab properly == NEST_MODE_HEAT_COOL \
return None and not self.device.device_data[self.device_id]['eco']:
if self.device.mode == NEST_MODE_HEAT_COOL: return \
return self.device.target_temperature_high self.device. \
device_data[self.device_id]['target_temperature_high']
return None return None
@property @property
def target_temperature_low(self): def target_temperature_low(self):
"""Return the lowbound target temperature we try to reach.""" """Return the lowbound target temperature we try to reach."""
if self.device.mode == NEST_MODE_ECO: if self.device.device_data[self.device_id]['mode'] \
# TODO: Grab properly == NEST_MODE_HEAT_COOL \
return None and not self.device.device_data[self.device_id]['eco']:
if self.device.mode == NEST_MODE_HEAT_COOL: return \
return self.device.target_temperature_low self.device. \
device_data[self.device_id]['target_temperature_low']
return None return None
@property @property
def hvac_action(self): def hvac_action(self):
"""Return current operation ie. heat, cool, idle.""" """Return current operation ie. heat, cool, idle."""
return ACTION_NEST_TO_HASS[self.device.get_action()] return ACTION_NEST_TO_HASS[
self.device.device_data[self.device_id]['action']
]
@property @property
def hvac_mode(self): def hvac_mode(self):
"""Return hvac target hvac state.""" """Return hvac target hvac state."""
if self.device.mode is None or self.device.mode == NEST_MODE_ECO: if self.device.device_data[self.device_id]['mode'] is None \
or self.device.device_data[self.device_id]['eco']:
# We assume the first operation in operation list is the main one # We assume the first operation in operation list is the main one
return self._operation_list[0] return self._operation_list[0]
return MODE_NEST_TO_HASS[self.device.mode] return MODE_NEST_TO_HASS[
self.device.device_data[self.device_id]['mode']
]
@property @property
def hvac_modes(self): def hvac_modes(self):
@ -206,7 +227,7 @@ class NestClimate(ClimateDevice):
@property @property
def preset_mode(self): def preset_mode(self):
"""Return current preset mode.""" """Return current preset mode."""
if self.device.mode == NEST_MODE_ECO: if self.device.device_data[self.device_id]['eco']:
return PRESET_ECO return PRESET_ECO
return PRESET_NONE return PRESET_NONE
@ -219,16 +240,19 @@ class NestClimate(ClimateDevice):
@property @property
def fan_mode(self): def fan_mode(self):
"""Return whether the fan is on.""" """Return whether the fan is on."""
if self.device.has_fan: if self.device.device_data[self.device_id]['has_fan']:
# Return whether the fan is on # Return whether the fan is on
return FAN_ON if self.device.fan else FAN_AUTO if self.device.device_data[self.device_id]['fan']:
return FAN_ON
else:
return FAN_AUTO
# No Fan available so disable slider # No Fan available so disable slider
return None return None
@property @property
def fan_modes(self): def fan_modes(self):
"""Return the list of available fan modes.""" """Return the list of available fan modes."""
if self.device.has_fan: if self.device.device_data[self.device_id]['has_fan']:
return self._fan_modes return self._fan_modes
return None return None
@ -237,33 +261,64 @@ class NestClimate(ClimateDevice):
temp = None temp = None
target_temp_low = kwargs.get(ATTR_TARGET_TEMP_LOW) target_temp_low = kwargs.get(ATTR_TARGET_TEMP_LOW)
target_temp_high = kwargs.get(ATTR_TARGET_TEMP_HIGH) target_temp_high = kwargs.get(ATTR_TARGET_TEMP_HIGH)
if self.device.mode == NEST_MODE_HEAT_COOL: if self.device.device_data[self.device_id]['mode'] == \
NEST_MODE_HEAT_COOL:
if target_temp_low is not None and target_temp_high is not None: if target_temp_low is not None and target_temp_high is not None:
self.device.set_temp(target_temp_low, target_temp_high) self.device.thermostat_set_temperature(
self.device_id,
target_temp_low,
target_temp_high,
)
else: else:
temp = kwargs.get(ATTR_TEMPERATURE) temp = kwargs.get(ATTR_TEMPERATURE)
if temp is not None: if temp is not None:
self.device.set_temp(temp) self.device.thermostat_set_temperature(
self.device_id,
temp,
)
def set_humidity(self, humidity):
"""Set new target humidity."""
humidity = int(round(float(humidity) / ROUND_TARGET_HUMIDITY_TO_NEAREST) * ROUND_TARGET_HUMIDITY_TO_NEAREST)
if humidity < NEST_HUMIDITY_MIN:
humidity = NEST_HUMIDITY_MIN
if humidity > NEST_HUMIDITY_MAX:
humidity = NEST_HUMIDITY_MAX
self.device.thermostat_set_target_humidity(
self.device_id,
humidity,
)
def set_hvac_mode(self, hvac_mode): def set_hvac_mode(self, hvac_mode):
"""Set operation mode.""" """Set operation mode."""
self.device.set_mode(MODE_HASS_TO_NEST[hvac_mode]) self.device.thermostat_set_mode(
self.device_id,
MODE_HASS_TO_NEST[hvac_mode],
)
def set_fan_mode(self, fan_mode): def set_fan_mode(self, fan_mode):
"""Turn fan on/off.""" """Turn fan on/off."""
if self.device.has_fan: if self.device.device_data[self.device_id]['has_fan']:
if fan_mode == "on": if fan_mode == "on":
self.device.set_fan(int(datetime.now().timestamp() + 60 * 30)) self.device.thermostat_set_fan(
self.device_id,
int(datetime.now().timestamp() + 60 * 30),
)
else: else:
self.device.set_fan(0) self.device.thermostat_set_fan(
self.device_id,
0,
)
def set_preset_mode(self, preset_mode): def set_preset_mode(self, preset_mode):
"""Set preset mode.""" """Set preset mode."""
need_eco = preset_mode in (PRESET_ECO) need_eco = preset_mode == PRESET_ECO
is_eco = self.device.mode == NEST_MODE_ECO
if is_eco != need_eco: if need_eco != self.device.device_data[self.device_id]['eco']:
self.device.set_eco_mode(need_eco) self.device.thermostat_set_eco_mode(
self.device_id,
need_eco,
)
def update(self): def update(self):
"""Updates data""" """Updates data"""

@ -1,4 +1,6 @@
DOMAIN = 'badnest' DOMAIN = 'badnest'
CONF_ISSUE_TOKEN = 'issue_token' CONF_ISSUE_TOKEN = 'issue_token'
CONF_COOKIE = 'cookie' CONF_COOKIE = 'cookie'
CONF_APIKEY = 'api_key' CONF_USER_ID = 'user_id'
CONF_ACCESS_TOKEN = 'access_token'
CONF_REGION = 'region'

@ -2,54 +2,50 @@ import logging
from homeassistant.helpers.entity import Entity from homeassistant.helpers.entity import Entity
from .api import NestTemperatureSensorAPI from .const import DOMAIN
from .const import DOMAIN, CONF_APIKEY, CONF_COOKIE, CONF_ISSUE_TOKEN
from homeassistant.const import ( from homeassistant.const import (
ATTR_BATTERY_LEVEL, ATTR_BATTERY_LEVEL,
DEVICE_CLASS_TEMPERATURE, DEVICE_CLASS_TEMPERATURE,
CONF_EMAIL,
CONF_PASSWORD,
TEMP_CELSIUS TEMP_CELSIUS
) )
_LOGGER = logging.getLogger(__name__) _LOGGER = logging.getLogger(__name__)
PROTECT_SENSOR_TYPES = [
"co_status",
"smoke_status",
"battery_health_state"
]
async def async_setup_platform(hass, async def async_setup_platform(hass,
config, config,
async_add_entities, async_add_entities,
discovery_info=None): discovery_info=None):
"""Set up the Nest climate device.""" """Set up the Nest climate device."""
api = NestTemperatureSensorAPI( api = hass.data[DOMAIN]['api']
hass.data[DOMAIN][CONF_EMAIL],
hass.data[DOMAIN][CONF_PASSWORD],
hass.data[DOMAIN][CONF_ISSUE_TOKEN],
hass.data[DOMAIN][CONF_COOKIE],
hass.data[DOMAIN][CONF_APIKEY]
)
sensors = [] temperature_sensors = []
_LOGGER.info("Adding temperature sensors") _LOGGER.info("Adding temperature sensors")
for sensor in api.get_devices(): for sensor in api['temperature_sensors']:
_LOGGER.info(f"Adding nest temp sensor uuid: {sensor}") _LOGGER.info(f"Adding nest temp sensor uuid: {sensor}")
sensors.append( temperature_sensors.append(NestTemperatureSensor(sensor, api))
NestTemperatureSensor(
sensor,
NestTemperatureSensorAPI(
hass.data[DOMAIN][CONF_EMAIL],
hass.data[DOMAIN][CONF_PASSWORD],
hass.data[DOMAIN][CONF_ISSUE_TOKEN],
hass.data[DOMAIN][CONF_COOKIE],
hass.data[DOMAIN][CONF_APIKEY],
sensor
)))
async_add_entities(sensors) async_add_entities(temperature_sensors)
protect_sensors = []
_LOGGER.info("Adding protect sensors")
for sensor in api['protects']:
_LOGGER.info(f"Adding nest protect sensor uuid: {sensor}")
for sensor_type in PROTECT_SENSOR_TYPES:
protect_sensors.append(NestProtectSensor(sensor, sensor_type, api))
async_add_entities(protect_sensors)
class NestTemperatureSensor(Entity): class NestTemperatureSensor(Entity):
"""Implementation of the DHT sensor.""" """Implementation of the Nest Temperature Sensor."""
def __init__(self, device_id, api): def __init__(self, device_id, api):
"""Initialize the sensor.""" """Initialize the sensor."""
@ -58,15 +54,20 @@ class NestTemperatureSensor(Entity):
self.device_id = device_id self.device_id = device_id
self.device = api self.device = api
@property
def unique_id(self):
"""Return an unique ID."""
return self.device_id
@property @property
def name(self): def name(self):
"""Return the name of the sensor.""" """Return the name of the sensor."""
return self.device_id return self.device.device_data[self.device_id]['name']
@property @property
def state(self): def state(self):
"""Return the state of the sensor.""" """Return the state of the sensor."""
return self.device.temperature return self.device.device_data[self.device_id]['temperature']
@property @property
def device_class(self): def device_class(self):
@ -85,4 +86,38 @@ class NestTemperatureSensor(Entity):
@property @property
def device_state_attributes(self): def device_state_attributes(self):
"""Return the state attributes.""" """Return the state attributes."""
return {ATTR_BATTERY_LEVEL: self.device.battery_level} return {
ATTR_BATTERY_LEVEL:
self.device.device_data[self.device_id]['battery_level']
}
class NestProtectSensor(Entity):
"""Implementation of the Nest Protect sensor."""
def __init__(self, device_id, sensor_type, api):
"""Initialize the sensor."""
self._name = "Nest Protect Sensor"
self.device_id = device_id
self._sensor_type = sensor_type
self.device = api
@property
def unique_id(self):
"""Return an unique ID."""
return self.device_id + '_' + self._sensor_type
@property
def name(self):
"""Return the name of the sensor."""
return self.device.device_data[self.device_id]['name'] + \
f' {self._sensor_type}'
@property
def state(self):
"""Return the state of the sensor."""
return self.device.device_data[self.device_id][self._sensor_type]
def update(self):
"""Get the latest data from the Protect and updates the states."""
self.device.update()

@ -1,4 +1,4 @@
{ {
"name": "Bad Nest Thermostat", "name": "Bad Nest",
"domains": ["climate", "camera", "sensor"] "domains": ["climate", "camera", "sensor"]
} }

59
info.md

@ -1,26 +1,49 @@
NOTICE: THIS PROJECT IS RETIRED NOW THAT GOOGLE HAS RELEASED THE SDM SMART DEVICE MANAGMENT API. FUTHER WORK CAN BE FOUND AT <https://github.com/USA-RedDragon/badnest-sdm> and <https://github.com/USA-RedDragon/python-google-sdm>.
# badnest # badnest
A bad Nest thermostat and camera integration that uses the web api to work after Works with Nest was shut down (bad Google, go sit in your corner and think about what you did) A bad Nest integration that uses the web api to work after Works with Nest was shut down (bad Google, go sit in your corner and think about what you did)
## Why is it bad? ## Why is it bad
This isn't an advertised or public API, it's still better than web scraping, but will never be as good as the original API This isn't an advertised or public API, it's still better than web scraping, but will never be as reliable as the original API
## Features
- Doesn't use the now defunct Works with Nest API
- Works with migrated/new accounts via Google auth
- Nest Protect support
- Nest Thermostat support
- Nest Thermostat Sensor support
- Nest Camera support
## Drawbacks ## Drawbacks
- No proper error handling
- Won't work with 2FA enabled accounts (Works with 2fa Google Accounts)
- Tested with a single thermostat, I have no other devices to test with - Tested with a single thermostat, I have no other devices to test with
- Camera integration is untested by me - Camera integration is untested by me
- Nest could change their webapp api at any time, making this defunct - Nest Protect integration is untested by me
- Thermostat presets don't work (Eco, Away) - Nest could change their webapp api at any time, making this defunct (this has happened before, see <https://github.com/USA-RedDragon/badnest/issues/67>)
## Example configuration.yaml - When you're not using the Google Auth Login ## Configuration
The camera's region is one of `us` or `eu` depending on your region.
If you're not in the US or EU, you should be able to add your
two-character country code, and it should work.
### Example configuration.yaml - When you're not using the Google Auth Login
Google recently introduced reCAPTCHA when logging to Nest. That means username
and password cannot be used directly any more. Instead, you have to obtain
`user_id` and `access_token` for your account by logging in manually. To do that,
open developer tools in your browser, switch to the "Network" tab, log in to Nest
and look for the request similar to `https://home.nest.com/session?_=1578693398448`.
You will find `user_id` and `access_token` in the response to the request.
```yaml ```yaml
badnest: badnest:
email: email@domain.com user_id: 11111
password: !secret nest_password access_token: !secret nest_access_token
region: us
climate: climate:
- platform: badnest - platform: badnest
@ -33,13 +56,13 @@ sensor:
- platform: badnest - platform: badnest
``` ```
## Example configuration.yaml - When you are using the Google Auth Login ### Example configuration.yaml - When you are using the Google Auth Login
```yaml ```yaml
badnest: badnest:
issue_token: "https://accounts.google.com/o/oauth2/iframerpc....." issue_token: "https://accounts.google.com/o/oauth2/iframerpc....."
cookie: "OCAK=......" cookie: "OCAK=......"
api_key : "#YOURAPIKEYHERE#" region: us
climate: climate:
- platform: badnest - platform: badnest
@ -54,7 +77,7 @@ sensor:
Google Login support added with many thanks to: chrisjshull from <https://github.com/chrisjshull/homebridge-nest/> Google Login support added with many thanks to: chrisjshull from <https://github.com/chrisjshull/homebridge-nest/>
The values of `"issue_token"`, `"cookie"` and `"api_key"` are specific to your Google Account. To get them, follow these steps (only needs to be done once, as long as you stay logged into your Google Account). The values of `"issue_token"` and `"cookie"` are specific to your Google Account. To get them, follow these steps (only needs to be done once, as long as you stay logged into your Google Account).
1. Open a Chrome browser tab in Incognito Mode (or clear your cache). 1. Open a Chrome browser tab in Incognito Mode (or clear your cache).
2. Open Developer Tools (View/Developer/Developer Tools). 2. Open Developer Tools (View/Developer/Developer Tools).
@ -66,6 +89,10 @@ The values of `"issue_token"`, `"cookie"` and `"api_key"` are specific to your G
8. In the 'Filter' box, enter `oauth2/iframe` 8. In the 'Filter' box, enter `oauth2/iframe`
9. Several network calls will appear in the Dev Tools window. Click on the last `iframe` call. 9. Several network calls will appear in the Dev Tools window. Click on the last `iframe` call.
10. In the Headers tab, under Request Headers, copy the entire `cookie` (beginning `OCAK=...` - **include the whole string which is several lines long and has many field/value pairs** - do not include the `cookie:` name). This is your `"cookie"` in `configuration.yaml`. 10. In the Headers tab, under Request Headers, copy the entire `cookie` (beginning `OCAK=...` - **include the whole string which is several lines long and has many field/value pairs** - do not include the `cookie:` name). This is your `"cookie"` in `configuration.yaml`.
11. In the 'Filter' box, enter `issue_jwt`
12. Click on the last `issue_jwt` call. ## Notes
13. In the Headers tab, under Request Headers, copy the entire `x-goog-api-key` (do not include the `x-goog-api-key:` name). This is your `"api_key"` in `configuration.yaml`.
The target temperature reported by the integration sometimes _seems_ to be slightly off by a few tens of a degree.
This is caused by the fact that the Nest mobile app actually actually allows users to set the temperature in small
increments, but the displayed temperature is rounded to the nearest 0.5 degree. In other words, the temperature
displayed by the integration is correct, just _more exact_ than what is shown in the app.