Skip to content
This repository has been archived by the owner on Jan 24, 2024. It is now read-only.

Commit

Permalink
Merge pull request #10 from toringer/update_entities
Browse files Browse the repository at this point in the history
Force update of accounts after doing a transfer
  • Loading branch information
toringer authored Mar 12, 2022
2 parents 334e5b3 + dfa629b commit c9a1c4a
Show file tree
Hide file tree
Showing 10 changed files with 274 additions and 197 deletions.
11 changes: 7 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,15 +1,18 @@
[![home-assistant-sbanken](https://img.shields.io/github/release/toringer/home-assistant-sbanken.svg?1)](https://github.com/toringer/home-assistant-sbanken)
[![home-assistant-sbanken](https://img.shields.io/github/release/toringer/home-assistant-sbanken.svg?1)](https://github.com/toringer/home-assistant-sbanken)
[![Validate with hassfest](https://github.com/toringer/home-assistant-sbanken/workflows/Validate%20with%20hassfest/badge.svg)](https://github.com/toringer/home-assistant-sbanken/actions/workflows/hassfest.yaml)
[![HACS Validation](https://github.com/toringer/home-assistant-sbanken/actions/workflows/validate_hacs.yaml/badge.svg)](https://github.com/toringer/home-assistant-sbanken/actions/workflows/validate_hacs.yaml)
[![Maintenance](https://img.shields.io/maintenance/yes/2022.svg)](https://github.com/toringer/home-assistant-sbanken)
[![home-assistant-sbanken_downloads](https://img.shields.io/github/downloads/toringer/home-assistant-sbanken/total)](https://github.com/toringer/home-assistant-sbanken)
[![home-assistant-sbanken_downloads](https://img.shields.io/github/downloads/toringer/home-assistant-sbanken/total)](https://github.com/toringer/home-assistant-sbanken)
[![home-assistant-sbanken_downloads](https://img.shields.io/github/downloads/toringer/home-assistant-sbanken/latest/total)](https://github.com/toringer/home-assistant-sbanken)

# Sbanken sensor platform for Home Assistant

Get your Sbanken account information integrated into your Home Assistant. The Sbanken integration will create an entity for each of your bank accounts. The entity displays current available amount, transactions, payments and other information.

The integration adds two services

# Sbanken sensor platform for Home Assistant
Get your Sbanken account information integrated into your Home Assistant. The Sbanken integration will create an entity for each of your bank accounts. The entity displays current available amount, transactions, payments and other information. The integration also adds a service `sbanken.transfer` that allows you to transfer amounts between your accounts.
- `sbanken.transfer` to transfer amounts between your accounts.
- `sbanken.update_account` to force an account information update

![Header](https://github.com/toringer/home-assistant-sbanken/blob/master/accounts.png)

Expand Down
7 changes: 2 additions & 5 deletions custom_components/sbanken/__init__.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,11 @@
"""The SBanken integration."""
from __future__ import annotations
import logging
import voluptuous as vol
from .sbankenApi import SbankenApi
from .services import async_setup_services
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import Platform
from homeassistant.core import HomeAssistant
from .const import DOMAIN, CONF_CLIENT_ID, CONF_SECRET, CONF_NUMBER_OF_TRANSACTIONS
from .sbanken_api import SbankenApi
from .const import DOMAIN, CONF_CLIENT_ID, CONF_SECRET

_LOGGER = logging.getLogger(__name__)
PLATFORMS: list[Platform] = [Platform.SENSOR]
Expand All @@ -23,7 +21,6 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
api = SbankenApi(entry.options.get(CONF_CLIENT_ID), entry.options.get(CONF_SECRET))
hass.data[DOMAIN]["api"] = api
hass.data[DOMAIN]["listener"] = entry.add_update_listener(update_listener)
await async_setup_services(hass)
return True


Expand Down
5 changes: 2 additions & 3 deletions custom_components/sbanken/config_flow.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,13 @@
"""Config flow for Sbanken integration."""
from __future__ import annotations
import logging
import voluptuous as vol
from typing import Any
import voluptuous as vol
from homeassistant import config_entries
from homeassistant.core import HomeAssistant
from homeassistant.data_entry_flow import FlowResult
from homeassistant.exceptions import HomeAssistantError
from homeassistant.core import callback
from .sbankenApi import SbankenApi
from .sbanken_api import SbankenApi
from .const import (
DOMAIN,
CONF_CLIENT_ID,
Expand Down
6 changes: 5 additions & 1 deletion custom_components/sbanken/const.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@

from homeassistant.exceptions import HomeAssistantError


DOMAIN = "sbanken"
TITLE = "Sbanken"
CONF_CLIENT_ID = "client_id"
Expand All @@ -19,6 +18,11 @@
ATTR_TRANSACTIONS = "transactions"
ATTR_PAYMENTS = "payments"
ATTR_STANDING_ORDERS = "standing_orders"
ATTR_AMOUNT = "amount"
ATTR_FROM_ACCOUNT_ENTITY = "from_account_entity"
ATTR_TO_ACCOUNT_ENTITY = "to_account_entity"
ATTR_MESSAGE = "message"
ATTR_UPDATE_ACCOUNT_ENTITY = "update_account_entity"


class InvalidAuth(HomeAssistantError):
Expand Down
2 changes: 1 addition & 1 deletion custom_components/sbanken/manifest.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"domain": "sbanken",
"name": "Sbanken",
"version": "2.0.9",
"version": "2.1.0",
"config_flow": true,
"documentation": "https://github.com/toringer/home-assistant-sbanken",
"issue_tracker": "https://github.com/toringer/home-assistant-sbanken/issues",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,12 +23,9 @@ def __init__(self, client_id: string, secret: string) -> None:

def get_session(self) -> OAuth2Session:
"""Get session"""
if (
self._session is None
or self._session.authorized is False
or self._session_expires_at < datetime.now()
):
_LOGGER.info("Create new session")
_LOGGER.debug("Get session")
if self._session is None or self._session_expires_at < datetime.now():
_LOGGER.debug("Create new session")
self._session = self._create_session(self.client_id, self.secret)
return self._session

Expand Down
176 changes: 176 additions & 0 deletions custom_components/sbanken/sbanken_entities.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,176 @@
""" Sbanken entities"""
import logging
from datetime import datetime
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity import DeviceInfo
from homeassistant.components.sensor import (
SensorDeviceClass,
SensorStateClass,
)
from homeassistant.helpers.entity import Entity
from .sbanken_api import SbankenApi
from .const import (
ATTR_ACCOUNT_ID,
ATTR_ACCOUNT_LIMIT,
ATTR_ACCOUNT_NUMBER,
ATTR_ACCOUNT_TYPE,
ATTR_AVAILABLE,
ATTR_BALANCE,
ATTR_LAST_UPDATE,
ATTR_NAME,
ATTR_PAYMENTS,
ATTR_STANDING_ORDERS,
ATTR_TRANSACTIONS,
DOMAIN,
)

_LOGGER = logging.getLogger(__name__)


class SbankenAccountSensor(Entity):
"""Representation of a Sensor."""

def __init__(
self,
account,
api: SbankenApi,
number_of_transactions: int,
hass: HomeAssistant,
customer_info,
) -> None:
"""Initialize the sensor."""
self.api = api
self.number_of_transactions = number_of_transactions
self.hass = hass
self.customer_info = customer_info
self._account = account
self._account_id = account["accountId"]
self._transactions = []
self._payments = []
self._standing_orders = []
self._state = float(account["available"])
self._attr_state_class = SensorStateClass.MEASUREMENT
self._attr_device_class = SensorDeviceClass.MONETARY
self._attr_unique_id = self._account["accountNumber"]
self._attr_name = f"{self._account['name']} ({self._account['accountNumber']})"
self._attr_unit_of_measurement = "NOK"
self._attr_icon = "mdi:cash"

@property
def device_info(self):
"""Return the device_info of the device."""
device_info = DeviceInfo(
identifiers={(DOMAIN, self.customer_info["customerId"])},
name=f"Sbanken: {self.customer_info['firstName']} {self.customer_info['lastName']}",
manufacturer="Sbanken",
configuration_url="https://sbanken.no/",
)
return device_info

@property
def state(self) -> float:
"""Return the state of the sensor."""
return self._state

@property
def extra_state_attributes(self):
"""Return the state attributes."""
return {
ATTR_ACCOUNT_ID: self._account_id,
ATTR_AVAILABLE: self._account["available"],
ATTR_BALANCE: self._account["balance"],
ATTR_ACCOUNT_NUMBER: self._account["accountNumber"],
ATTR_NAME: self._account["name"],
ATTR_ACCOUNT_TYPE: self._account["accountType"],
ATTR_ACCOUNT_LIMIT: self._account["creditLimit"],
ATTR_LAST_UPDATE: datetime.now().strftime("%d/%m/%Y %H:%M:%S"),
ATTR_TRANSACTIONS: self._transactions,
ATTR_PAYMENTS: self._payments,
ATTR_STANDING_ORDERS: self._standing_orders,
}

async def async_update(self):
"""Fetch new state data for the sensor.
This is the only method that should fetch new data for Home Assistant.
"""
account = await self.hass.async_add_executor_job(
self.api.get_account, self._account_id
)
transactions = await self.hass.async_add_executor_job(
self.api.get_transactions,
self._account_id,
self.number_of_transactions,
)
payments = await self.hass.async_add_executor_job(
self.api.get_payments,
self._account_id,
self.number_of_transactions,
)

standing_orders = await self.hass.async_add_executor_job(
self.api.get_standing_orders, self._account_id
)

self._transactions = transactions
self._payments = payments
self._account = account
self._standing_orders = standing_orders
self._state = float(account["available"])
_LOGGER.debug(f"Updating Sbanken Sensors: {self._attr_name}")


class CustomerInformationSensor(Entity):
"""Representation of a Sensor."""

def __init__(self, api: SbankenApi, hass: HomeAssistant, customer_info) -> None:
"""Initialize the sensor."""
self.api = api
self.hass = hass
self.customer_info = customer_info
self._state = (
f"{self.customer_info['firstName']} {self.customer_info['lastName']}"
)
self._attr_unique_id = self.customer_info["customerId"]
self._attr_name = "Customer information"
self._attr_icon = "mdi:information-outline"

@property
def device_info(self):
"""Return the device_info of the device."""
device_info = DeviceInfo(
identifiers={(DOMAIN, self.customer_info["customerId"])},
name=f"Sbanken: {self.customer_info['firstName']} {self.customer_info['lastName']}",
manufacturer="Sbanken",
configuration_url="https://sbanken.no/",
)
return device_info

@property
def state(self):
"""Return the state of the sensor."""
return self._state

@property
def extra_state_attributes(self):
"""Return the state attributes."""
return {
"customerId": self.customer_info["customerId"],
"firstName": self.customer_info["firstName"],
"lastName": self.customer_info["lastName"],
"emailAddress": self.customer_info["emailAddress"],
"dateOfBirth": self.customer_info["dateOfBirth"],
"postalAddress": self.customer_info["postalAddress"],
"streetAddress": self.customer_info["streetAddress"],
"phoneNumbers": self.customer_info["phoneNumbers"],
}

async def async_update(self):
"""Fetch new state data for the sensor.
This is the only method that should fetch new data for Home Assistant.
"""
self.customer_info = await self.hass.async_add_executor_job(
self.api.get_customer_information
)
_LOGGER.debug(f"Updating Sbanken Sensors: {self._attr_name}")
Loading

0 comments on commit c9a1c4a

Please sign in to comment.