1
0
mirror of https://github.com/USA-RedDragon/badnest.git synced 2025-09-06 17:21:52 +01:00

22 Commits
2.0.2 ... 3.2.1

Author SHA1 Message Date
Jacob McSwain
3d49b85c50 Merge pull request #24 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 #23 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
Jacob McSwain
1228304609 Merge pull request #21 from USA-RedDragon/eco-visual-bug
Fix eco going in and out on UI
2019-10-22 13:47:22 -05:00
Jacob McSwain
68e71850be Fix eco going in and out on UI 2019-10-22 13:46:47 -05:00
Jacob McSwain
5f4b14514c Merge pull request #20 from USA-RedDragon/start-error-handling
Add preliminary error handling support
2019-10-22 13:34:59 -05:00
Jacob McSwain
6f097c58a8 Merge pull request #19 from USA-RedDragon/auto-eco-mode
Add auto eco mode to set of eco modes
2019-10-22 13:34:25 -05:00
Jacob McSwain
98daabc5d7 Add preliminary error handling support 2019-10-22 13:34:00 -05:00
Jacob McSwain
c4f702b859 Add auto eco mode to set of eco modes 2019-10-22 13:32:52 -05:00
Jacob McSwain
977c553a8d Merge pull request #18 from USA-RedDragon/visual-bug-auto-mode
Fix a visual bug wherein the mode kept going into the 'unknown' state
2019-10-20 20:08:39 -05:00
Jacob McSwain
f1abecefce Fix a visual bug wherein the mode kept going into the 'unknown' state 2019-10-20 20:07:42 -05:00
Jacob McSwain
c7c011720c Merge pull request #16 from USA-RedDragon/eco-preset
Thermostat eco preset support
2019-10-20 19:53:06 -05:00
Jacob McSwain
b4debfcf9c Thermostat eco preset support 2019-10-20 19:52:13 -05:00
Jacob McSwain
10bd645c0f Merge pull request #15 from USA-RedDragon/release-content-type
Add content type to releases workflow
2019-10-19 21:09:55 -05:00
Jacob McSwain
de8312b722 Add content type to releases workflow 2019-10-19 21:09:21 -05:00
Jacob McSwain
ed105b74c1 Merge pull request #14 from USA-RedDragon/temperature-sensors-readme
Add sensors to README
2019-10-19 21:06:08 -05:00
Jacob McSwain
52d381f471 Add sensors to README 2019-10-19 21:05:26 -05:00
Jacob McSwain
074a2fdf44 Merge pull request #13 from USA-RedDragon/temperature-sensors
Add temperature sensor support
2019-10-19 21:04:13 -05:00
Jacob McSwain
87c65ab23e Add temperature sensor support 2019-10-19 21:03:30 -05:00
Jacob McSwain
7ac7989bf4 Merge pull request #12 from USA-RedDragon/multiple-thermostats
Add multiple thermostat support
2019-10-19 20:32:55 -05:00
Jacob McSwain
f2643d4427 Add multiple thermostat support 2019-10-19 20:31:51 -05:00
7 changed files with 343 additions and 99 deletions

View File

@@ -12,6 +12,6 @@ jobs:
run: zip -r badnest.zip hacs.json info.md custom_components
- uses: JasonEtco/upload-to-release@master
with:
args: badnest.zip
args: badnest.zip application/zip
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

View File

@@ -1,4 +1,5 @@
import requests
import logging
API_URL = "https://home.nest.com"
CAMERA_WEBAPI_BASE = "https://webapi.camera.home.nest.com"
@@ -8,18 +9,34 @@ USER_AGENT = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_5) " \
"Chrome/75.0.3770.100 Safari/537.36"
URL_JWT = "https://nestauthproxyservice-pa.googleapis.com/v1/issue_jwt"
_LOGGER = logging.getLogger(__name__)
class NestAPI:
def __init__(self, email, password, issue_token, cookie, api_key):
def __init__(self,
email,
password,
issue_token,
cookie,
api_key,
device_id=None):
self._user_id = None
self._access_token = None
self._session = requests.Session()
self._session.headers.update({"Referer": "https://home.nest.com/"})
self._device_id = None
if not email and not password:
self._login_google(issue_token, cookie, api_key)
self._device_id = device_id
self._email = email
self._password = password
self._issue_token = issue_token
self._cookie = cookie
self._api_key = api_key
self.login()
def login(self):
if not self._email and not self._password:
self._login_google(self._issue_token, self._cookie, self._api_key)
else:
self._login_nest(email, password)
self._login_nest(self._email, self._password)
def _login_nest(self, email, password):
r = self._session.post(
@@ -57,14 +74,20 @@ class NestAPI:
class NestThermostatAPI(NestAPI):
def __init__(self, email, password, issue_token, cookie, api_key):
def __init__(self,
email,
password,
issue_token,
cookie,
api_key,
device_id=None):
super(NestThermostatAPI, self).__init__(
email,
password,
issue_token,
cookie,
api_key)
self._shared_id = None
api_key,
device_id)
self._czfe_url = None
self._compressor_lockout_enabled = None
self._compressor_lockout_time = None
@@ -77,7 +100,6 @@ class NestThermostatAPI(NestAPI):
self.can_cool = None
self.has_fan = None
self.fan = None
self.away = None
self.current_temperature = None
self.target_temperature = None
self.target_temperature_high = None
@@ -85,6 +107,32 @@ class NestThermostatAPI(NestAPI):
self.current_humidity = None
self.update()
def get_devices(self):
try:
r = self._session.post(
f"{API_URL}/api/0.1/user/{self._user_id}/app_launch",
json={
"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('device.'):
devices.append(bucket.replace('device.', ''))
return devices
except requests.exceptions.RequestException as e:
_LOGGER.error(e)
_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()
return self.get_devices()
def get_action(self):
if self._hvac_ac_state:
return "cooling"
@@ -94,49 +142,66 @@ class NestThermostatAPI(NestAPI):
return "off"
def update(self):
r = self._session.post(
f"{API_URL}/api/0.1/user/{self._user_id}/app_launch",
json={
"known_bucket_types": ["shared", "device"],
"known_bucket_versions": [],
},
headers={"Authorization": f"Basic {self._access_token}"},
)
try:
r = self._session.post(
f"{API_URL}/api/0.1/user/{self._user_id}/app_launch",
json={
"known_bucket_types": ["shared", "device"],
"known_bucket_versions": [],
},
headers={"Authorization": f"Basic {self._access_token}"},
)
self._czfe_url = r.json()["service_urls"]["urls"]["czfe_url"]
self._czfe_url = r.json()["service_urls"]["urls"]["czfe_url"]
for bucket in r.json()["updated_buckets"]:
if bucket["object_key"].startswith("shared."):
self._shared_id = bucket["object_key"]
thermostat_data = bucket["value"]
self.current_temperature = \
thermostat_data["current_temperature"]
self.target_temperature = thermostat_data["target_temperature"]
self._compressor_lockout_enabled = thermostat_data[
"compressor_lockout_enabled"
]
self._compressor_lockout_time = thermostat_data[
"compressor_lockout_timeout"
]
self._hvac_ac_state = thermostat_data["hvac_ac_state"]
self._hvac_heater_state = thermostat_data["hvac_heater_state"]
self.mode = thermostat_data["target_temperature_type"]
self.target_temperature_high = thermostat_data[
"target_temperature_high"
]
self.target_temperature_low = \
thermostat_data["target_temperature_low"]
self.can_heat = thermostat_data["can_heat"]
self.can_cool = thermostat_data["can_cool"]
elif bucket["object_key"].startswith("device."):
self._device_id = bucket["object_key"]
thermostat_data = bucket["value"]
self._time_to_target = thermostat_data["time_to_target"]
self._fan_timer_timeout = thermostat_data["fan_timer_timeout"]
self.has_fan = thermostat_data["has_fan"]
self.fan = thermostat_data["fan_timer_timeout"] > 0
self.current_humidity = thermostat_data["current_humidity"]
self.away = thermostat_data["home_away_input"]
temp_mode = None
for bucket in r.json()["updated_buckets"]:
if bucket["object_key"] \
.startswith(f"shared.{self._device_id}"):
thermostat_data = bucket["value"]
self.current_temperature = \
thermostat_data["current_temperature"]
self.target_temperature = \
thermostat_data["target_temperature"]
self._compressor_lockout_enabled = thermostat_data[
"compressor_lockout_enabled"
]
self._compressor_lockout_time = thermostat_data[
"compressor_lockout_timeout"
]
self._hvac_ac_state = thermostat_data["hvac_ac_state"]
self._hvac_heater_state = \
thermostat_data["hvac_heater_state"]
if temp_mode is None:
temp_mode = thermostat_data["target_temperature_type"]
self.target_temperature_high = thermostat_data[
"target_temperature_high"
]
self.target_temperature_low = \
thermostat_data["target_temperature_low"]
self.can_heat = thermostat_data["can_heat"]
self.can_cool = thermostat_data["can_cool"]
elif bucket["object_key"] \
.startswith(f"device.{self._device_id}"):
thermostat_data = bucket["value"]
self._time_to_target = thermostat_data["time_to_target"]
self._fan_timer_timeout = \
thermostat_data["fan_timer_timeout"]
self.has_fan = thermostat_data["has_fan"]
self.fan = thermostat_data["fan_timer_timeout"] > 0
self.current_humidity = thermostat_data["current_humidity"]
if thermostat_data["eco"]["mode"] == 'manual-eco' or \
thermostat_data["eco"]["mode"] == 'auto-eco':
temp_mode = 'eco'
self.mode = temp_mode
except requests.exceptions.RequestException as e:
_LOGGER.error(e)
_LOGGER.error('Failed to update, trying again')
self.update()
except KeyError:
_LOGGER.debug('Failed to update, trying to log in again')
self.login()
self.update()
def set_temp(self, temp, temp_high=None):
if temp_high is None:
@@ -145,7 +210,7 @@ class NestThermostatAPI(NestAPI):
json={
"objects": [
{
"object_key": self._shared_id,
"object_key": f'shared.{self._device_id}',
"op": "MERGE",
"value": {"target_temperature": temp},
}
@@ -159,7 +224,7 @@ class NestThermostatAPI(NestAPI):
json={
"objects": [
{
"object_key": self._shared_id,
"object_key": f'shared.{self._device_id}',
"op": "MERGE",
"value": {
"target_temperature_low": temp,
@@ -177,7 +242,7 @@ class NestThermostatAPI(NestAPI):
json={
"objects": [
{
"object_key": self._shared_id,
"object_key": f'shared.{self._device_id}',
"op": "MERGE",
"value": {"target_temperature_type": mode},
}
@@ -192,7 +257,7 @@ class NestThermostatAPI(NestAPI):
json={
"objects": [
{
"object_key": self._device_id,
"object_key": f'device.{self._device_id}',
"op": "MERGE",
"value": {"fan_timer_timeout": date},
}
@@ -201,15 +266,16 @@ class NestThermostatAPI(NestAPI):
headers={"Authorization": f"Basic {self._access_token}"},
)
def set_eco_mode(self):
def set_eco_mode(self, state):
mode = 'manual-eco' if state else 'schedule'
self._session.post(
f"{self._czfe_url}/v5/put",
json={
"objects": [
{
"object_key": self._device_id,
"object_key": f'device.{self._device_id}',
"op": "MERGE",
"value": {"eco": {"mode": "manual-eco"}},
"value": {"eco": {"mode": mode}},
}
]
},
@@ -217,19 +283,99 @@ class NestThermostatAPI(NestAPI):
)
class NestTemperatureSensorAPI(NestAPI):
def __init__(self,
email,
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(
f"{API_URL}/api/0.1/user/{self._user_id}/app_launch",
json={
"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
except requests.exceptions.RequestException as e:
_LOGGER.error(e)
_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()
return self.get_devices()
def update(self):
try:
r = self._session.post(
f"{API_URL}/api/0.1/user/{self._user_id}/app_launch",
json={
"known_bucket_types": ["kryptonite"],
"known_bucket_versions": [],
},
headers={"Authorization": f"Basic {self._access_token}"},
)
for bucket in r.json()["updated_buckets"]:
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"]
except requests.exceptions.RequestException as e:
_LOGGER.error(e)
_LOGGER.error('Failed to update, trying again')
self.update()
except KeyError:
_LOGGER.debug('Failed to update, trying to log in again')
self.login()
self.update()
class NestCameraAPI(NestAPI):
def __init__(self, email, password, issue_token, cookie, api_key):
def __init__(self,
email,
password,
issue_token,
cookie,
api_key,
device_id=None):
super(NestCameraAPI, self).__init__(
email,
password,
issue_token,
cookie,
api_key)
api_key,
device_id)
# log into dropcam
self._session.post(
f"{API_URL}/dropcam/api/login",
data={"access_token": self._access_token}
)
self._device_id = device_id
self.location = None
self.name = "Nest Camera"
self.online = None
@@ -239,10 +385,6 @@ class NestCameraAPI(NestAPI):
self.data_tier = None
self.update()
def set_device(self, uuid):
self._device_id = uuid
self.update()
def update(self):
if self._device_id:
props = self.get_properties()

View File

@@ -13,7 +13,6 @@ from .const import DOMAIN, CONF_ISSUE_TOKEN, CONF_COOKIE, CONF_APIKEY
_LOGGER = logging.getLogger(__name__)
DEFAULT_NAME = "Nest Camera"
DATA_KEY = "camera.badnest"
async def async_setup_platform(hass,
@@ -21,8 +20,6 @@ async def async_setup_platform(hass,
async_add_entities,
discovery_info=None):
"""Set up a Nest Camera."""
hass.data[DATA_KEY] = dict()
api = NestCameraAPI(
hass.data[DOMAIN][CONF_EMAIL],
hass.data[DOMAIN][CONF_PASSWORD],
@@ -36,9 +33,15 @@ async def async_setup_platform(hass,
_LOGGER.info("Adding cameras")
for camera in api.get_cameras():
_LOGGER.info("Adding nest cam uuid: %s", camera["uuid"])
device = NestCamera(camera["uuid"], api)
device = NestCamera(camera["uuid"], 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],
camera["uuid"]
))
cameras.append(device)
hass.data[DATA_KEY][camera["uuid"]] = device
async_add_entities(cameras)
@@ -50,7 +53,6 @@ class NestCamera(Camera):
"""Initialize a Nest camera."""
super().__init__()
self._uuid = uuid
api.set_device(self._uuid)
self._device = api
self._time_between_snapshots = timedelta(seconds=30)
self._last_image = None

View File

@@ -13,9 +13,9 @@ from homeassistant.components.climate.const import (
HVAC_MODE_HEAT,
HVAC_MODE_OFF,
SUPPORT_FAN_MODE,
SUPPORT_PRESET_MODE,
SUPPORT_TARGET_TEMPERATURE,
SUPPORT_TARGET_TEMPERATURE_RANGE,
PRESET_AWAY,
PRESET_ECO,
PRESET_NONE,
CURRENT_HVAC_HEAT,
@@ -53,9 +53,7 @@ ACTION_NEST_TO_HASS = {
MODE_NEST_TO_HASS = {v: k for k, v in MODE_HASS_TO_NEST.items()}
PRESET_AWAY_AND_ECO = "Away and Eco"
PRESET_MODES = [PRESET_NONE, PRESET_AWAY, PRESET_ECO, PRESET_AWAY_AND_ECO]
PRESET_MODES = [PRESET_NONE, PRESET_ECO]
_LOGGER = logging.getLogger(__name__)
@@ -65,7 +63,7 @@ async def async_setup_platform(hass,
async_add_entities,
discovery_info=None):
"""Set up the Nest climate device."""
nest = NestThermostatAPI(
api = NestThermostatAPI(
hass.data[DOMAIN][CONF_EMAIL],
hass.data[DOMAIN][CONF_PASSWORD],
hass.data[DOMAIN][CONF_ISSUE_TOKEN],
@@ -73,21 +71,34 @@ async def async_setup_platform(hass,
hass.data[DOMAIN][CONF_APIKEY]
)
async_add_entities([NestClimate(nest)])
thermostats = []
_LOGGER.info("Adding thermostats")
for thermostat in api.get_devices():
_LOGGER.info(f"Adding nest thermostat uuid: {thermostat}")
thermostats.append(NestClimate(thermostat, NestThermostatAPI(
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)
class NestClimate(ClimateDevice):
"""Representation of a Nest climate device."""
def __init__(self, api):
def __init__(self, device_id, api):
"""Initialize the thermostat."""
self._name = "Nest Thermostat"
self._unit_of_measurement = TEMP_CELSIUS
self._fan_modes = [FAN_ON, FAN_AUTO]
self.device_id = device_id
# Set the default supported features
self._support_flags = SUPPORT_TARGET_TEMPERATURE
# | SUPPORT_PRESET_MODE
self._support_flags = SUPPORT_TARGET_TEMPERATURE | SUPPORT_PRESET_MODE
# Not all nest devices support cooling and heating remove unused
self._operation_list = []
@@ -111,6 +122,11 @@ class NestClimate(ClimateDevice):
if self.device.has_fan:
self._support_flags = self._support_flags | SUPPORT_FAN_MODE
@property
def unique_id(self):
"""Return an unique ID."""
return self.device_id
@property
def supported_features(self):
"""Return the list of supported features."""
@@ -124,7 +140,7 @@ class NestClimate(ClimateDevice):
@property
def name(self):
"""Return the name of the climate device."""
return self._name
return self.device_id
@property
def temperature_unit(self):
@@ -136,6 +152,11 @@ class NestClimate(ClimateDevice):
"""Return the current temperature."""
return self.device.current_temperature
@property
def current_humidity(self):
"""Return the current humidity."""
return self.device.current_humidity
@property
def target_temperature(self):
"""Return the temperature we try to reach."""
@@ -185,16 +206,10 @@ class NestClimate(ClimateDevice):
@property
def preset_mode(self):
"""Return current preset mode."""
if self.device.away and self.device.mode == NEST_MODE_ECO:
return PRESET_AWAY_AND_ECO
if self.device.away:
return PRESET_AWAY
if self.device.mode == NEST_MODE_ECO:
return PRESET_ECO
return None
return PRESET_NONE
@property
def preset_modes(self):
@@ -244,20 +259,11 @@ class NestClimate(ClimateDevice):
def set_preset_mode(self, preset_mode):
"""Set preset mode."""
need_away = preset_mode in (PRESET_AWAY, PRESET_AWAY_AND_ECO)
need_eco = preset_mode in (PRESET_ECO, PRESET_AWAY_AND_ECO)
is_away = self.device.away
need_eco = preset_mode in (PRESET_ECO)
is_eco = self.device.mode == NEST_MODE_ECO
if is_away != need_away:
pass
# self.device.set_away()
if is_eco != need_eco:
if need_eco:
self.device.set_eco_mode()
else:
self.device.mode = MODE_HASS_TO_NEST[self._operation_list[0]]
self.device.set_eco_mode(need_eco)
def update(self):
"""Updates data"""

View File

@@ -0,0 +1,88 @@
import logging
from homeassistant.helpers.entity import Entity
from .api import NestTemperatureSensorAPI
from .const import DOMAIN, CONF_APIKEY, CONF_COOKIE, CONF_ISSUE_TOKEN
from homeassistant.const import (
ATTR_BATTERY_LEVEL,
DEVICE_CLASS_TEMPERATURE,
CONF_EMAIL,
CONF_PASSWORD,
TEMP_CELSIUS
)
_LOGGER = logging.getLogger(__name__)
async def async_setup_platform(hass,
config,
async_add_entities,
discovery_info=None):
"""Set up the Nest climate device."""
api = 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]
)
sensors = []
_LOGGER.info("Adding temperature sensors")
for sensor in api.get_devices():
_LOGGER.info(f"Adding nest temp sensor uuid: {sensor}")
sensors.append(
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)
class NestTemperatureSensor(Entity):
"""Implementation of the DHT sensor."""
def __init__(self, device_id, api):
"""Initialize the sensor."""
self._name = "Nest Temperature Sensor"
self._unit_of_measurement = TEMP_CELSIUS
self.device_id = device_id
self.device = api
@property
def name(self):
"""Return the name of the sensor."""
return self.device_id
@property
def state(self):
"""Return the state of the sensor."""
return self.device.temperature
@property
def device_class(self):
"""Return the device class of this entity."""
return DEVICE_CLASS_TEMPERATURE
@property
def unit_of_measurement(self):
"""Return the unit of measurement of this entity, if any."""
return self._unit_of_measurement
def update(self):
"""Get the latest data from the DHT and updates the states."""
self.device.update()
@property
def device_state_attributes(self):
"""Return the state attributes."""
return {ATTR_BATTERY_LEVEL: self.device.battery_level}

View File

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

View File

@@ -28,6 +28,9 @@ climate:
camera:
- platform: badnest
sensor:
- platform: badnest
```
## Example configuration.yaml - When you are using the Google Auth Login
@@ -44,6 +47,9 @@ climate:
camera:
- platform: badnest
sensor:
- platform: badnest
```
Google Login support added with many thanks to: chrisjshull from <https://github.com/chrisjshull/homebridge-nest/>