-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy path__init__.py
executable file
·177 lines (134 loc) · 5.13 KB
/
__init__.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
"""
Sbanken Sensor Platform
- platform: sbanken
customer_id: 01010112345
client_id: token
secret: secret
"""
import asyncio
import logging
import datetime
import voluptuous as vol
from random import randrange
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.entity import Entity
from homeassistant.helpers.event import track_time_interval
from homeassistant.components.sensor import PLATFORM_SCHEMA
from homeassistant.const import (CONF_SCAN_INTERVAL)
REQUIREMENTS = ['oauthlib==2.0.6', 'requests-oauthlib==0.8.0']
_LOGGER = logging.getLogger(__name__)
SCAN_INTERVAL = datetime.timedelta(minutes=30)
ATTR_AVAILABLE = 'available'
ATTR_BALANCE = 'balance'
ATTR_ACCOUNT_NUMBER = 'account_number'
ATTR_NAME = 'name'
ATTR_ACCOUNT_TYPE = 'account_type'
ATTR_ACCOUNT_LIMIT = 'credit_limit'
CONF_CUSTOMER_ID = 'customer_id'
CONF_CLIENT_ID = 'client_id'
CONF_SECRET = 'secret'
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
vol.Optional(CONF_CLIENT_ID): cv.string,
vol.Optional(CONF_SECRET): cv.string,
vol.Optional(CONF_SCAN_INTERVAL, default=SCAN_INTERVAL): cv.time_period,
})
def setup_platform(hass, config, add_devices, discovery_info=None):
"""Setup the sensor platform."""
_LOGGER.debug("Setting up Sbanken Sensor Platform.")
api = SbankenApi(config.get(CONF_CUSTOMER_ID), config.get(CONF_CLIENT_ID), config.get(CONF_SECRET))
accounts = api.get_accounts()
sensors = []
for account in accounts:
sensors.append(SbankenSensor(account, config, api))
add_devices(sensors)
return True
class SbankenSensor(Entity):
"""Representation of a Sensor."""
def __init__(self, account, config, api):
"""Initialize the sensor."""
self.config = config
self.api = api
self._account = account
self._state = account['balance']
@property
def name(self):
"""Return the name of the sensor."""
return self._account['name'] + ' (' + self._account['accountNumber'] + ')'
@property
def state(self):
"""Return the state of the sensor."""
return self._state
@property
def unit_of_measurement(self):
"""Return the unit of measurement."""
return 'kr'
@property
def should_poll(self):
"""Camera should poll periodically."""
return True
@property
def icon(self):
"""Icon to use in the frontend, if any."""
return 'mdi:cash'
@property
def device_state_attributes(self):
"""Return the state attributes."""
return {
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']
}
def update(self):
"""Fetch new state data for the sensor.
This is the only method that should fetch new data for Home Assistant.
"""
account = self.api.get_account(self._account['accountNumber'])
self._account = account
self._state = account['balance']
self.schedule_update_ha_state()
class SbankenApi(object):
"""Get the latest data and update the states."""
def __init__(self, customer_id, client_id, secret):
"""Initialize the data object."""
self.customer_id = customer_id
self.client_id = client_id
self.secret = secret
self.session = self.create_session()
def create_session(self):
from requests_oauthlib import OAuth2Session
from oauthlib.oauth2 import BackendApplicationClient
oauth2_client = BackendApplicationClient(client_id=self.client_id)
session = OAuth2Session(client=oauth2_client)
session.fetch_token(
token_url='https://api.sbanken.no/identityserver/connect/token',
client_id=self.client_id,
client_secret=self.secret
)
return session
def get_customer_information(self):
response = self.session.get(
"https://api.sbanken.no/customers/api/v1/Customers/{}".format(self.customer_id)
).json()
if not response["isError"]:
return response["item"]
else:
raise RuntimeError("{} {}".format(response["errorType"], response["errorMessage"]))
def get_accounts(self):
response = self.session.get(
"https://api.sbanken.no/bank/api/v1/Accounts/{}".format(self.customer_id)
).json()
if not response["isError"]:
return response["items"]
else:
raise RuntimeError("{} {}".format(response["errorType"], response["errorMessage"]))
def get_account(self, accountnumber):
response = self.session.get(
"https://api.sbanken.no/bank/api/v1/Accounts/{}/{}".format(self.customer_id, accountnumber)
).json()
if not response["isError"]:
return response['item']
else:
raise RuntimeError("{} {}".format(response["errorType"], response["errorMessage"]))