8 Commits

Author SHA1 Message Date
RyanClark123
0cf3afef85 Bumping pyowlet, reauth config entry fix
#### Fix
* Bumping to pyowletapi 2023.5.24
* Reauthing now no longer re adds users' password to config entry
2023-05-17 18:59:38 +01:00
ryanbdclark
fa06157fe2 Update const.py
###Fix
* Error in sleep states constant corrected
2023-05-16 21:14:46 +01:00
RyanClark123
2b21188e73 Update CHANGELOG 2023-05-16 15:21:41 +01:00
RyanClark123
9b3392bdbc Added new sensors
###Feature
* Added new sensors, binary sensor awake, is on if baby awake, off otherwise. Sensor sleep state, shows baby sleep state, options are awake, light sleep, deep sleep
2023-05-16 15:06:01 +01:00
RyanClark123
dc710a1783 Integration now uses refresh token
-Makes use of pyowletapi 2023.5.23 to use the refresh token to reauthenticate, integration now no longer stores users password
-Default polling interval changed to 5 seconds to match owlet app
2023-05-16 14:05:26 +01:00
RyanClark123
8d9299a8f4 Updated changelog for new release
Updated changelog for new release
2023-05-15 15:56:37 +01:00
RyanClark123
228d54b641 bumping pyowletapi version
### Fix
* Bump pyowletapi to 2023.5.21, fix for unawaited authentication call believe to be causing an issue reauthenticating when token had expired
* Github username change reflected, won't change again
2023-05-15 11:21:50 +01:00
RyanClark123
3e147aa914 Added reauth flow, much better error handling on setup
### Feature
* Now supports reauthentication if credentials have expired/no longer work
* Better error handling when configuring integration, will notify user of incorrect credentials

### Fix
* Removed Owlet specific constants, now using homeassistant generic constants
* On initialisation the integration would crash when trying to update the auth token, the integration would then have to be deleted and setup again
2023-05-12 17:02:04 +01:00
16 changed files with 319 additions and 72 deletions

3
.gitignore vendored
View File

@@ -150,3 +150,6 @@ cython_debug/
# and can be added to the global gitignore or merged into this file. For a more nuclear
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
#.idea/
/custom_components/owlet.zip
custom_components/owlet/owlet.zip

28
CHANGELOG.md Normal file
View File

@@ -0,0 +1,28 @@
# Changelog
<!--next-version-placeholder-->
## 2023-05-3 (2023-05-17)
#### Fix
* Bumping to pyowletapi 2023.5.24
* Reauthing now no longer re adds users' password to config entry
## 2023-05-2 (2023-05-16)
#### Feature
* Integration now makes use of refresh token from pyowletapi to reauthenticate, user password in no longer stored by integration ([`dc710a1`](https://github.com/ryanbdclark/owlet/commit/dc710a1783a4cad9d6cf355240fe12ac779a87ef))
* New sensors create for baby sleep state ([`9b3392b`](https://github.com/ryanbdclark/owlet/commit/9b3392bdbcd82015ed31d3a50a517e4e22905684))
## 2023-05-1 (2023-05-15)
#### Feature
* Changed versioning to date based
### Fix
* Bumping to pyowletapi 2023.5.21 to fix issue with unawaited authentication call, should resolve issue with refreshing authentication ([`228d54b`](https://github.com/ryanbdclark/owlet/commit/228d54b6414e0b9171064254246d1f36c3af8f5b))
## v1.5.0 (2023-05-12)
### Feature
* Now supports reauthentication if credentials have expired/no longer work
* Better error handling when configuring integration, will notify user of incorrect credentials
### Fix
* Removed Owlet specific constants, now using homeassistant generic constants
* On initialisation the integration would crash when trying to update the auth token, the integration would then have to be deleted and setup again

50
README.md Normal file
View File

@@ -0,0 +1,50 @@
# Owlet Custom Integration
[![GitHub Release][releases-shield]][releases]
[![GitHub Activity][commits-shield]][commits]
[![License][license-shield]][license]
[![hacs][hacsbadge]][hacs]
[![Project Maintenance][maintenance-shield]][user_profile]
A custom component for the Owlet smart sock, currently this only supports the owlet smart sock 3.
If you have a smart sock 2 and would like to contribute then please do so.
## Installation
1. Use [HACS](https://hacs.xyz/docs/setup/download), in `HACS > Integrations > Explore & Add Repositories` search for "Owlet". After adding this `https://github.com/ryanbdclark/owlet` as a custom repository.
2. Restart Home Assistant.
3. [![Add Integration][add-integration-badge]][add-integration] or in the HA UI go to "Settings" -> "Devices & Services" then click "+" and search for "Owlet Smart Sock".
<!---->
## Usage
The `Owlet` integration offers integration with the Owlet Smart Sock cloud service. This provides sensors such as heart rate, oxygen saturation, charge percentage.
This integration provides the following entities:
- Binary sensors - charging status, high heart rate alert, low heart rate alert, high oxygen alert, low oxygen alert, low battery alert, lost power alert, sock diconnected alert, and sock status.
- Sensors - battery level, oxygen saturation, oxygen saturation 10 minute average, heart rate, battery time remaining, signal strength, and skin temperature.
## Options
- Seconds between polling - Number of seconds between each call for data from the owlet cloud service, default is 5 seconds.
---
[commits-shield]: https://img.shields.io/github/commit-activity/w/ryanbdclark/owlet?style=for-the-badge
[commits]: https://github.com/ryanbdclark/owlet/commits/main
[hacs]: https://github.com/hacs/integration
[hacsbadge]: https://img.shields.io/badge/HACS-Custom-orange.svg?style=for-the-badge
[license]: LICENSE
[license-shield]: https://img.shields.io/github/license/ryanbdclark/owlet.svg?style=for-the-badge
[maintenance-shield]: https://img.shields.io/badge/maintainer-Ryan%20Clark%20%40ryanbdclark-blue.svg?style=for-the-badge
[releases-shield]: https://img.shields.io/github/release/ryanbdclark/owlet.svg?style=for-the-badge
[releases]: https://github.com/ryanbdclark/owlet/releases
[user_profile]: https://github.com/ryanbdclark
[add-integration]: https://my.home-assistant.io/redirect/config_flow_start?domain=owlet
[add-integration-badge]: https://my.home-assistant.io/badges/config_flow_start.svg

View File

@@ -0,0 +1 @@
"""Custom Integrations for Home Assistant."""

View File

@@ -5,20 +5,23 @@ import logging
from pyowletapi.api import OwletAPI
from pyowletapi.sock import Sock
from pyowletapi.exceptions import OwletAuthenticationError, OwletDevicesError
from pyowletapi.exceptions import OwletAuthenticationError
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import Platform
from homeassistant.config_entries import ConfigEntry, ConfigEntryAuthFailed
from homeassistant.const import (
Platform,
CONF_REGION,
CONF_USERNAME,
CONF_PASSWORD,
CONF_SCAN_INTERVAL,
CONF_API_TOKEN,
)
from homeassistant.core import HomeAssistant
from homeassistant.helpers.aiohttp_client import async_get_clientsession
from .const import (
DOMAIN,
CONF_OWLET_REGION,
CONF_OWLET_USERNAME,
CONF_OWLET_PASSWORD,
CONF_OWLET_POLLINTERVAL,
CONF_OWLET_EXPIRY,
CONF_OWLET_TOKEN,
CONF_OWLET_REFRESH,
SUPPORTED_VERSIONS,
)
from .coordinator import OwletCoordinator
@@ -33,20 +36,18 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
hass.data.setdefault(DOMAIN, {})
owlet_api = OwletAPI(
entry.data[CONF_OWLET_REGION],
entry.data[CONF_OWLET_USERNAME],
entry.data[CONF_OWLET_PASSWORD],
entry.data[CONF_OWLET_TOKEN],
entry.data[CONF_OWLET_EXPIRY],
async_get_clientsession(hass),
region=entry.data[CONF_REGION],
token=entry.data[CONF_API_TOKEN],
expiry=entry.data[CONF_OWLET_EXPIRY],
refresh=entry.data[CONF_OWLET_REFRESH],
session=async_get_clientsession(hass),
)
try:
token = await owlet_api.authenticate()
if token:
entry.data[CONF_OWLET_TOKEN] = token[CONF_OWLET_TOKEN]
entry.data[CONF_OWLET_EXPIRY] = token[CONF_OWLET_EXPIRY]
hass.config_entries.async_update_entry(entry, data={**entry.data, **token})
socks = {
device["device"]["dsn"]: Sock(owlet_api, device["device"])
@@ -54,11 +55,13 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
}
except OwletAuthenticationError as err:
_LOGGER.error("Login failed %s", err)
return False
_LOGGER.error("Credentials no longer valid, please setup owlet again")
raise ConfigEntryAuthFailed(
f"Credentials expired for {entry.data[CONF_USERNAME]}"
) from err
coordinators = [
OwletCoordinator(hass, sock, entry.options.get(CONF_OWLET_POLLINTERVAL))
OwletCoordinator(hass, sock, entry.options.get(CONF_SCAN_INTERVAL))
for sock in socks.values()
]

View File

@@ -86,6 +86,12 @@ SENSORS: tuple[OwletBinarySensorEntityDescription, ...] = (
device_class=BinarySensorDeviceClass.POWER,
element="sock_off",
),
OwletBinarySensorEntityDescription(
key="awake",
name="Awake",
element="sleep_state",
icon="mdi:sleep",
),
)
@@ -112,13 +118,21 @@ class OwletBinarySensor(OwletBaseEntity, BinarySensorEntity):
sensor_description: OwletBinarySensorEntityDescription,
) -> None:
"""Initialize the binary sensor."""
self.entity_description = sensor_description
self._attr_unique_id = (
f"{coordinator.config_entry.entry_id}-{self.entity_description.name}"
)
super().__init__(coordinator)
self.entity_description = sensor_description
self._attr_unique_id = f"{self.sock.serial}-{self.entity_description.name}"
@property
def is_on(self) -> bool:
"""Return true if the binary sensor is on."""
return self.sock.properties[self.entity_description.element]
state = self.sock.properties[self.entity_description.element]
if self.entity_description.element == "sleep_state":
if self.sock.properties["charging"]:
return None
if state in [8, 15]:
state = False
else:
state = True
return state

View File

@@ -7,29 +7,32 @@ from typing import Any
from pyowletapi.api import OwletAPI
from pyowletapi.sock import Sock
from pyowletapi.exceptions import (
OwletConnectionError,
OwletAuthenticationError,
OwletDevicesError,
OwletEmailError,
OwletPasswordError,
)
import voluptuous as vol
from homeassistant import config_entries
from homeassistant import config_entries, exceptions
from homeassistant.data_entry_flow import FlowResult
from homeassistant.config_entries import ConfigEntry
from homeassistant.helpers.aiohttp_client import async_get_clientsession
from homeassistant.core import callback
from homeassistant.const import (
CONF_REGION,
CONF_USERNAME,
CONF_PASSWORD,
CONF_SCAN_INTERVAL,
CONF_API_TOKEN,
)
from .const import (
DOMAIN,
CONF_OWLET_REGION,
CONF_OWLET_USERNAME,
CONF_OWLET_PASSWORD,
CONF_OWLET_POLLINTERVAL,
CONF_OWLET_TOKEN,
CONF_OWLET_EXPIRY,
POLLING_INTERVAL,
SUPPORTED_VERSIONS,
CONF_OWLET_REFRESH,
)
_LOGGER = logging.getLogger(__name__)
@@ -54,6 +57,7 @@ class OwletConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
self._username: str
self._password: str
self._devices: dict[str, Sock]
self.reauth_entry: ConfigEntry | None = None
async def async_step_user(
self, user_input: dict[str, Any] | None = None
@@ -61,9 +65,9 @@ class OwletConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
"""Handle the initial step."""
errors: dict[str, str] = {}
if user_input is not None:
self._region = user_input[CONF_OWLET_REGION]
self._username = user_input[CONF_OWLET_USERNAME]
self._password = user_input[CONF_OWLET_PASSWORD]
self._region = user_input[CONF_REGION]
self._username = user_input[CONF_USERNAME]
self._password = user_input[CONF_PASSWORD]
owlet_api = OwletAPI(
self._region,
@@ -82,21 +86,21 @@ class OwletConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
return self.async_create_entry(
title=self._username,
data={
CONF_OWLET_REGION: self._region,
CONF_OWLET_USERNAME: self._username,
CONF_OWLET_PASSWORD: self._password,
CONF_OWLET_TOKEN: token[CONF_OWLET_TOKEN],
CONF_REGION: self._region,
CONF_USERNAME: self._username,
CONF_API_TOKEN: token[CONF_API_TOKEN],
CONF_OWLET_EXPIRY: token[CONF_OWLET_EXPIRY],
CONF_OWLET_REFRESH: token[CONF_OWLET_REFRESH],
},
options={CONF_OWLET_POLLINTERVAL: POLLING_INTERVAL},
options={CONF_SCAN_INTERVAL: POLLING_INTERVAL},
)
except OwletDevicesError:
errors["base"] = "no_devices"
except OwletConnectionError:
errors["base"] = "cannot_connect"
except OwletAuthenticationError:
errors["base"] = "invalid_auth"
except OwletEmailError:
errors["base"] = "invalid_email"
except OwletPasswordError:
errors["base"] = "invalid_password"
except Exception: # pylint: disable=broad-except
_LOGGER.exception("Unexpected exception")
errors["base"] = "unknown"
@@ -111,6 +115,50 @@ class OwletConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
"""Get the options flow for this handler."""
return OptionsFlowHandler(config_entry)
async def async_step_reauth(self, user_input=None):
"""Handle reauth"""
self.reauth_entry = self.hass.config_entries.async_get_entry(
self.context["entry_id"]
)
return await self.async_step_reauth_confirm()
async def async_step_reauth_confirm(self, user_input=None):
"""Dialog that informs the user that reauth is required"""
assert self.reauth_entry is not None
errors: dict[str, str] = {}
if user_input is not None:
entry_data = self.reauth_entry.data
owlet_api = OwletAPI(
entry_data[CONF_REGION],
entry_data[CONF_USERNAME],
user_input[CONF_PASSWORD],
session=async_get_clientsession(self.hass),
)
try:
token = await owlet_api.authenticate()
if token:
self.hass.config_entries.async_update_entry(
self.reauth_entry, data={**entry_data, **token}
)
await self.hass.config_entries.async_reload(self.reauth_entry.entry_id)
return self.async_abort(reason="reauth_successful")
except OwletEmailError:
errors["base"] = "invalid_email"
except OwletPasswordError:
errors["base"] = "invalid_password"
except Exception: # pylint: disable=broad-except
_LOGGER.exception("error reauthing")
return self.async_show_form(
step_id="reauth_confirm",
data_schema=vol.Schema({vol.Required(CONF_PASSWORD): str}),
errors=errors,
)
class OptionsFlowHandler(config_entries.OptionsFlow):
"""Handle a options flow for owlet"""
@@ -127,10 +175,14 @@ class OptionsFlowHandler(config_entries.OptionsFlow):
schema = vol.Schema(
{
vol.Required(
CONF_OWLET_POLLINTERVAL,
default=self.config_entry.options.get(CONF_OWLET_POLLINTERVAL),
CONF_SCAN_INTERVAL,
default=self.config_entry.options.get(CONF_SCAN_INTERVAL),
): vol.All(vol.Coerce(int), vol.Range(min=10)),
}
)
return self.async_show_form(step_id="init", data_schema=schema)
class InvalidAuth(exceptions.HomeAssistantError):
"""Error to indiciate there is invalud auth"""

View File

@@ -2,14 +2,10 @@
DOMAIN = "owlet"
CONF_OWLET_REGION = "region"
CONF_OWLET_USERNAME = "username"
CONF_OWLET_PASSWORD = "password"
CONF_OWLET_DEVICES = "devices"
CONF_OWLET_POLLINTERVAL = "pollinterval"
CONF_OWLET_TOKEN = "token"
CONF_OWLET_EXPIRY = "expiry"
CONF_OWLET_REFRESH = "refresh"
SUPPORTED_VERSIONS = [3]
POLLING_INTERVAL = 10
POLLING_INTERVAL = 5
MANUFACTURER = "Owlet Baby Care"
SLEEP_STATES = {0: "Unknown", 1: "Awake", 8: "Light Sleep", 15: "Deep Sleep"}

View File

@@ -5,16 +5,18 @@ from datetime import timedelta
import logging
from pyowletapi.sock import Sock
from pyowletapi.exceptions import OwletError
from pyowletapi.exceptions import (
OwletError,
OwletConnectionError,
OwletAuthenticationError,
)
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity import DeviceInfo
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed
from homeassistant.const import CONF_API_TOKEN
from .const import (
DOMAIN,
MANUFACTURER,
)
from .const import DOMAIN, MANUFACTURER, CONF_OWLET_EXPIRY, CONF_OWLET_REFRESH
_LOGGER = logging.getLogger(__name__)
@@ -49,5 +51,16 @@ class OwletCoordinator(DataUpdateCoordinator):
"""Fetch the data from the device."""
try:
await self.sock.update_properties()
except OwletError as err:
tokens = await self.sock.api.tokens_changed(
{
CONF_API_TOKEN: self.config_entry.data[CONF_API_TOKEN],
CONF_OWLET_EXPIRY: self.config_entry.data[CONF_OWLET_EXPIRY],
CONF_OWLET_REFRESH: self.config_entry.data[CONF_OWLET_REFRESH],
}
)
if tokens:
self.hass.config_entries.async_update_entry(
self.config_entry, data={**self.config_entry.data, **tokens}
)
except (OwletError, OwletConnectionError, OwletAuthenticationError) as err:
raise UpdateFailed(err) from err

View File

@@ -2,7 +2,7 @@
"domain": "owlet",
"name": "Owlet Smart Sock",
"codeowners": [
"@RyanClark123"
"@ryanbdclark"
],
"config_flow": true,
"dependencies": [],
@@ -10,7 +10,7 @@
"homekit": {},
"iot_class": "cloud_polling",
"requirements": [
"pyowletapi==2023.5.18"
"pyowletapi==2023.5.24"
],
"version":"1.4.0"
"version":"2023.5.3"
}

View File

@@ -18,7 +18,7 @@ from homeassistant.const import (
UnitOfTemperature,
)
from .const import DOMAIN
from .const import DOMAIN, SLEEP_STATES
from .coordinator import OwletCoordinator
from .entity import OwletBaseEntity
@@ -107,6 +107,7 @@ async def async_setup_entry(
coordinator: OwletCoordinator = hass.data[DOMAIN][config_entry.entry_id]
entities = [OwletSensor(coordinator, sensor) for sensor in SENSORS]
entities.append(OwletSleepStateSensor(coordinator))
async_add_entities(entities)
@@ -120,11 +121,9 @@ class OwletSensor(OwletBaseEntity, SensorEntity):
sensor_description: OwletSensorEntityDescription,
) -> None:
"""Initialize the sensor."""
self.entity_description = sensor_description
self._attr_unique_id = (
f"{coordinator.config_entry.entry_id}-{self.entity_description.name}"
)
super().__init__(coordinator)
self.entity_description = sensor_description
self._attr_unique_id = f"{self.sock.serial}-{self.entity_description.name}"
@property
def native_value(self):
@@ -137,10 +136,38 @@ class OwletSensor(OwletBaseEntity, SensorEntity):
"battery_minutes",
"oxygen_saturation",
"skin_temperature",
"oxygen_10_av"
"oxygen_10_av",
]
and self.sock.properties["charging"]
):
return None
return self.sock.properties[self.entity_description.element]
class OwletSleepStateSensor(OwletBaseEntity, SensorEntity):
"""Representation of an Owlet sleep state sensor."""
def __init__(
self,
coordinator: OwletCoordinator,
) -> None:
"""Initialize the sensor."""
super().__init__(coordinator)
self._attr_unique_id = f"{self.sock.serial}-Sleep State"
self._attr_icon = "mdi:sleep"
self._attr_device_class = SensorDeviceClass.ENUM
self._attr_translation_key = "sleepstate"
self._attr_name = "Sleep State"
@property
def native_value(self):
"""Return sensor value"""
if self.sock.properties["charging"]:
return None
return SLEEP_STATES[self.sock.properties["sleep_state"]]
@property
def options(self) -> list[str]:
return SLEEP_STATES.values()

View File

@@ -8,11 +8,18 @@
"username": "Email",
"password": "Password"
}
},
"reauth_confirm":{
"title": "Reauthentiaction required for Owlet",
"data":{
"password": "Password"
}
}
},
"error": {
"cannot_connect": "[%key:common::config_flow::error::cannot_connect%]",
"invalid_auth": "[%key:common::config_flow::error::invalid_auth%]",
"invalid_email": "Entered email address is incorrect",
"invalid_password": "Entered password is incorrect",
"unknown": "[%key:common::config_flow::error::unknown%]"
},
"abort": {

View File

@@ -8,11 +8,18 @@
"username": "Email",
"password": "Password"
}
},
"reauth_confirm":{
"title": "Reauthentiaction required for Owlet",
"data":{
"password": "Password"
}
}
},
"error": {
"cannot_connect": "[%key:common::config_flow::error::cannot_connect%]",
"invalid_auth": "[%key:common::config_flow::error::invalid_auth%]",
"invalid_email": "Entered email address is incorrect",
"invalid_password": "Entered password is incorrect",
"unknown": "[%key:common::config_flow::error::unknown%]"
},
"abort": {

View File

@@ -8,11 +8,18 @@
"username": "Email",
"password": "Password"
}
},
"reauth_confirm":{
"title": "Reauthentiaction required for Owlet",
"data":{
"password": "Password"
}
}
},
"error": {
"cannot_connect": "[%key:common::config_flow::error::cannot_connect%]",
"invalid_auth": "[%key:common::config_flow::error::invalid_auth%]",
"invalid_email": "Entered email address is incorrect",
"invalid_password": "Entered password is incorrect",
"unknown": "[%key:common::config_flow::error::unknown%]"
},
"abort": {

View File

@@ -1,5 +1,7 @@
{
"name": "Owlet",
"hacs": "1.31.1",
"hacs": "1.32.1",
"homeassistant": "2023.04.1",
"zip_release": true,
"filename": "owlet.zip"
}

37
info.md Normal file
View File

@@ -0,0 +1,37 @@
# Owlet Custom Integration
[![GitHub Release][releases-shield]][releases]
[![GitHub Activity][commits-shield]][commits]
[![License][license-shield]][license]
[![hacs][hacsbadge]][hacs]
[![Project Maintenance][maintenance-shield]][user_profile]
A custom component for the Owlet smart sock, currently this only supports the owlet smart sock 3.
If you have a smart sock 2 and would like to contribute then please do so.
## Installation
1. Click install.
2. Reboot Home Assistant.
3. Hard refresh browser cache.
4. [![Add Integration][add-integration-badge]][add-integration] or in the HA UI go to "Configuration" -> "Integrations" click "+" and search for "Owlet Smart Sock".
<!---->
---
[commits-shield]: https://img.shields.io/github/commit-activity/w/ryanbdclark/owlet?style=for-the-badge
[commits]: https://github.com/ryanbdclark/owlet/commits/main
[hacs]: https://github.com/hacs/integration
[hacsbadge]: https://img.shields.io/badge/HACS-Custom-orange.svg?style=for-the-badge
[license]: LICENSE
[license-shield]: https://img.shields.io/github/license/ryanbdclark/owlet.svg?style=for-the-badge
[maintenance-shield]: https://img.shields.io/badge/maintainer-Ryan%20Clark%20%40ryanbdclark-blue.svg?style=for-the-badge
[releases-shield]: https://img.shields.io/github/release/ryanbdclark/owlet.svg?style=for-the-badge
[releases]: https://github.com/ryanbdclark/owlet/releases
[user_profile]: https://github.com/ryanbdclark
[add-integration]: https://my.home-assistant.io/redirect/config_flow_start?domain=owlet
[add-integration-badge]: https://my.home-assistant.io/badges/config_flow_start.svg