-
Notifications
You must be signed in to change notification settings - Fork 3
/
sensor.py
214 lines (179 loc) · 6.43 KB
/
sensor.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
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
"""Support for Bbox Bouygues Modem Router."""
from __future__ import annotations
from datetime import timedelta
import logging
import requests
import voluptuous as vol
from .pybbox import Bbox
from homeassistant.components.sensor import (
PLATFORM_SCHEMA,
SensorEntity,
SensorEntityDescription,
SensorStateClass,
SensorDeviceClass
)
from homeassistant.const import (
CONF_MONITORED_VARIABLES,
CONF_NAME,
CONF_PASSWORD,
CONF_HOST,
UnitOfDataRate
)
import homeassistant.helpers.config_validation as cv
from homeassistant.util import Throttle
from homeassistant.util.dt import utcnow
_LOGGER = logging.getLogger(__name__)
ATTRIBUTION = "Powered by Bouygues Telecom"
DEFAULT_NAME = "Bbox"
DEFAULT_HOST = "mabbox.bytel.fr"
MIN_TIME_BETWEEN_UPDATES = timedelta(seconds=60)
SENSOR_TYPES: tuple[SensorEntityDescription, ...] = (
SensorEntityDescription(
key="down_max_bandwidth",
name="Maximum Download Bandwidth",
native_unit_of_measurement=UnitOfDataRate.MEGABITS_PER_SECOND,
icon="mdi:download",
),
SensorEntityDescription(
key="up_max_bandwidth",
name="Maximum Upload Bandwidth",
native_unit_of_measurement=UnitOfDataRate.MEGABITS_PER_SECOND,
icon="mdi:upload",
),
SensorEntityDescription(
key="current_down_bandwidth",
name="Currently Used Download Bandwidth",
native_unit_of_measurement=UnitOfDataRate.MEGABITS_PER_SECOND,
state_class=SensorStateClass.MEASUREMENT,
icon="mdi:download",
),
SensorEntityDescription(
key="current_up_bandwidth",
name="Currently Used Upload Bandwidth",
native_unit_of_measurement=UnitOfDataRate.MEGABITS_PER_SECOND,
state_class=SensorStateClass.MEASUREMENT,
icon="mdi:upload",
),
SensorEntityDescription(
key="number_of_reboots",
name="Number of reboot",
icon="mdi:restart",
),
)
SENSOR_TYPES_UPTIME: tuple[SensorEntityDescription, ...] = (
SensorEntityDescription(
key="uptime",
name="Uptime",
icon="mdi:clock",
),
)
SENSOR_KEYS: list[str] = [desc.key for desc in (*SENSOR_TYPES, *SENSOR_TYPES_UPTIME)]
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
{
vol.Required(CONF_MONITORED_VARIABLES): vol.All(
cv.ensure_list, [vol.In(SENSOR_KEYS)]
),
vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
vol.Required(CONF_PASSWORD, default=""): cv.string,
vol.Optional(CONF_HOST, default=DEFAULT_HOST): cv.string
}
)
def setup_platform(hass, config, add_entities, discovery_info=None):
password = config[CONF_PASSWORD]
host = config[CONF_HOST]
"""Set up the Bbox sensor."""
# Create a data fetcher to support all of the configured sensors. Then make
# the first call to init the data.
try:
bbox_data = BboxData(host, password)
bbox_data.update()
except requests.exceptions.HTTPError as error:
_LOGGER.error(error)
return False
name = config[CONF_NAME]
monitored_variables = config[CONF_MONITORED_VARIABLES]
entities: list[BboxSensor | BboxUptimeSensor] = [
BboxSensor(bbox_data, name, password, host, description)
for description in SENSOR_TYPES
if description.key in monitored_variables
]
entities.extend(
[
BboxUptimeSensor(bbox_data, name, password, host, description)
for description in SENSOR_TYPES_UPTIME
if description.key in monitored_variables
]
)
add_entities(entities, True)
class BboxUptimeSensor(SensorEntity):
"""Bbox uptime sensor."""
_attr_attribution = ATTRIBUTION
_attr_device_class = SensorDeviceClass.TIMESTAMP
def __init__(self, bbox_data, name, password, host, description: SensorEntityDescription):
"""Initialize the sensor."""
self.entity_description = description
self._attr_name = f"{name} {description.name}"
self.bbox_data = bbox_data
self.host = host
self.password = password
def update(self):
"""Get the latest data from Bbox and update the state."""
self.bbox_data.update()
self._attr_native_value = utcnow() - timedelta(
seconds=self.bbox_data.router_infos["device"]["uptime"]
)
class BboxSensor(SensorEntity):
"""Implementation of a Bbox sensor."""
_attr_attribution = ATTRIBUTION
def __init__(self, bbox_data, name, password, host, description: SensorEntityDescription):
"""Initialize the sensor."""
self.entity_description = description
self._attr_name = f"{name} {description.name}"
self.bbox_data = bbox_data
self.host = host
self.password = password
def update(self):
"""Get the latest data from Bbox and update the state."""
self.bbox_data.update()
sensor_type = self.entity_description.key
if sensor_type == "down_max_bandwidth":
self._attr_native_value = round(
self.bbox_data.data["rx"]["maxBandwidth"] / 1000, 2
)
elif sensor_type == "up_max_bandwidth":
self._attr_native_value = round(
self.bbox_data.data["tx"]["maxBandwidth"] / 1000, 2
)
elif sensor_type == "current_down_bandwidth":
self._attr_native_value = round(
self.bbox_data.data["rx"]["bandwidth"] / 1000, 2
)
elif sensor_type == "current_up_bandwidth":
self._attr_native_value = round(
self.bbox_data.data["tx"]["bandwidth"] / 1000, 2
)
elif sensor_type == "number_of_reboots":
self._attr_native_value = self.bbox_data.router_infos["device"][
"numberofboots"
]
class BboxData:
"""Get data from the Bbox."""
def __init__(self, host, password):
"""Initialize the data object."""
self.data = None
self.router_infos = None
self.host = host
self.password = password
@Throttle(MIN_TIME_BETWEEN_UPDATES)
def update(self):
"""Get the latest data from the Bbox."""
try:
box = Bbox(ip=self.host)
box.login(self.password)
self.data = box.get_ip_stats()
self.router_infos = box.get_bbox_info()
except requests.exceptions.HTTPError as error:
_LOGGER.error(error)
self.data = None
self.router_infos = None
return False