-
-
Notifications
You must be signed in to change notification settings - Fork 4
/
camera.py
361 lines (297 loc) · 11.2 KB
/
camera.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
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
import asyncio
import logging
import email.utils as eut
import datetime as dt
import io
import pathlib
import shutil
import hashlib
import itertools
from urllib.parse import urlparse
from PIL import Image, UnidentifiedImageError
import aiohttp
import voluptuous as vol
from homeassistant.components.camera import (
DEFAULT_CONTENT_TYPE,
PLATFORM_SCHEMA,
SUPPORT_ON_OFF,
Camera,
async_get_still_stream,
)
from homeassistant.components.camera.const import DOMAIN as CAMERA_DOMAIN
from homeassistant.const import (
CONF_NAME,
CONF_USERNAME,
CONF_PASSWORD,
)
from homeassistant.core import HomeAssistant, callback
from homeassistant.exceptions import TemplateError
from homeassistant.helpers import config_validation as cv, entity_platform
from homeassistant.helpers.aiohttp_client import async_get_clientsession
from homeassistant.helpers.reload import async_setup_reload_service
import homeassistant.util.dt as dt_util
from .const import (
DOMAIN,
DEFAULT_NAME,
CONF_IMAGE_URL,
CONF_FETCH_INTERVAL,
CONF_MAX_FRAMES,
CONF_FRAMERATE,
CONF_QUALITY,
CONF_LOOP,
CONF_HEADERS,
CONF_PAUSED,
SERVICE_CLEAR_IMAGES,
SERVICE_PAUSE_RECORDING,
SERVICE_RESUME_RECORDING,
)
_LOGGER = logging.getLogger(__name__)
STORAGE_VERSION = 1
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
{
vol.Required(CONF_IMAGE_URL): cv.url,
vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
vol.Optional(CONF_FETCH_INTERVAL, default=60.0): vol.Any(
cv.small_float, cv.positive_int
),
vol.Optional(CONF_FRAMERATE, default=2): vol.Any(
cv.small_float, cv.positive_int
),
vol.Optional(CONF_MAX_FRAMES, default=100): cv.positive_int,
vol.Optional(CONF_QUALITY, default=75): vol.All(vol.Coerce(int), vol.Range(min=1, max=100)),
vol.Optional(CONF_LOOP, default=True): cv.boolean,
vol.Optional(CONF_HEADERS, default={}): dict,
vol.Optional(CONF_USERNAME): str,
vol.Optional(CONF_PASSWORD): str,
}
)
async def async_setup_entry(hass, entry, async_add_entities):
"""Setup Mjpeg Timelapse from a config entry."""
data = hass.data[DOMAIN].get(entry.entry_id)
async_add_entities([MjpegTimelapseCamera(hass, data)])
platform = entity_platform.async_get_current_platform()
platform.async_register_entity_service(
SERVICE_CLEAR_IMAGES,
{},
"clear_images",
)
platform.async_register_entity_service(
SERVICE_PAUSE_RECORDING,
{},
"pause_recording",
)
platform.async_register_entity_service(
SERVICE_RESUME_RECORDING,
{},
"resume_recording",
)
async def async_setup_platform(hass, config, async_add_entities, discovery_info=None):
"""Setup Mjpeg Timelapse Camera"""
async_add_entities([MjpegTimelapseCamera(hass, config)])
platform = entity_platform.async_get_current_platform()
platform.async_register_entity_service(
SERVICE_CLEAR_IMAGES,
{},
"clear_images",
)
class MjpegTimelapseCamera(Camera):
def __init__(self, hass, device_info):
super().__init__()
self.hass = hass
self.last_modified = None
self.last_updated = None
self._fetching_listener = None
self._attr_image_url = device_info[CONF_IMAGE_URL]
self._attr_attribution = urlparse(self._attr_image_url).netloc
self._attr_name = device_info.get(CONF_NAME, self._attr_attribution)
self._attr_unique_id = hashlib.sha256(self._attr_image_url.encode("utf-8")).hexdigest()
self.image_dir = pathlib.Path(hass.config.path(CAMERA_DOMAIN)) / self._attr_unique_id
self._attr_frame_rate = device_info.get(CONF_FRAMERATE, 2)
self._attr_fetch_interval = dt.timedelta(seconds=device_info.get(CONF_FETCH_INTERVAL, 60))
self._attr_max_frames = device_info.get(CONF_MAX_FRAMES, 100)
self._attr_quality = device_info.get(CONF_QUALITY, 100)
self._attr_supported_features = SUPPORT_ON_OFF
self._attr_loop = device_info.get(CONF_LOOP, False)
self._attr_headers = device_info.get(CONF_HEADERS, {})
self._attr_username = device_info.get(CONF_USERNAME, {})
self._attr_password = device_info.get(CONF_PASSWORD, {})
self._attr_is_paused = device_info.get(CONF_PAUSED, False)
if self._attr_is_on == True:
self.start_fetching()
@property
def should_poll(self):
"""Return false for should poll."""
return False
@property
def icon(self):
"""Return the icon."""
return "mdi:image-multiple"
@property
def image_url(self):
"""Return the image url."""
return self._attr_image_url
@property
def frame_rate(self):
"""Return the framerate."""
return self._attr_frame_rate
@property
def frame_interval(self):
"""Return the frame interval."""
return 1 / self.frame_rate
@property
def fetch_interval(self):
"""Return the fetch interval."""
return self._attr_fetch_interval
@property
def max_frames(self):
"""Return the maximum frames."""
return self._attr_max_frames
@property
def quality(self):
"""Return the quality."""
return self._attr_quality
@property
def loop(self):
"""Indicate whether to loop or not."""
return self._attr_loop
@property
def headers(self):
"""Return additional headers for request."""
return self._attr_headers
@property
def username(self):
"""Return the basic auth username."""
return self._attr_username
@property
def password(self):
"""Return the basic auth password."""
return self._attr_password
@property
def is_paused(self):
"""Returns whether recording is paused."""
return self._attr_is_paused
@property
def is_recording(self):
"""Indicate whether recording or not."""
return self._fetching_listener is not None
def turn_on(self):
"""Turn on the camera."""
if not self.is_paused:
self.start_fetching()
self._attr_is_on = True
def turn_off(self):
"""Turn off the camera."""
self.stop_fetching()
self._attr_is_on = False
@property
def extra_state_attributes(self):
return {
"image_url": self.image_url,
"fetch_interval": self.fetch_interval.total_seconds(),
"frame_rate": self.frame_rate,
"max_frames": self.max_frames,
"quality": self.quality,
"loop": self.loop,
"headers": self.headers,
"last_updated": self.last_updated
}
def start_fetching(self):
"""Start fetching images periodically."""
if self._fetching_listener is None:
self._fetching_listener = self.hass.helpers.event.async_track_time_interval(self.fetch_image, self.fetch_interval)
def stop_fetching(self):
"""Stop fetching images."""
if self._fetching_listener is not None:
self._fetching_listener()
self._fetching_listener = None
def pause_recording(self):
"""Pause recording images."""
self.stop_fetching()
self._attr_is_paused = True
self.schedule_update_ha_state()
def resume_recording(self):
"""Pause recording images."""
self.start_fetching()
self._attr_is_paused = False
self.schedule_update_ha_state()
async def fetch_image(self, _time):
headers = {**self.headers}
session = async_get_clientsession(self.hass)
auth = None
if self.last_modified:
headers["If-Modified-Since"] = self.last_modified
if self.username is not None:
auth = aiohttp.BasicAuth(self.username, self.password, 'utf-8')
try:
async with session.get(self.image_url, timeout=5, headers=headers, auth=auth) as res:
res.raise_for_status()
self._attr_available = True
if res.status == 304:
_LOGGER.debug("HTTP 304 - success")
return
last_modified = res.headers.get("Last-Modified")
if last_modified:
self.last_modified = last_modified
last_modified = dt.datetime(*eut.parsedate(last_modified)[:6])
data = await res.read()
_LOGGER.debug("HTTP %d - Last-Modified: %s", res.status, self.last_modified)
self.last_updated = dt_util.as_timestamp(dt_util.as_utc(last_modified or dt_util.utcnow()))
await self.hass.async_add_executor_job(self.save_image, str(int(self.last_updated)), data)
except OSError as err:
_LOGGER.error("Can't write image for '%s' to file: %s", self.name, err)
except (asyncio.TimeoutError, aiohttp.ClientError) as err:
_LOGGER.error("Failed to fetch image for '%s': %s", self.name, err)
self._attr_available = False
self.async_write_ha_state()
def save_image(self, basename, data):
try:
image = Image.open(io.BytesIO(data)).convert('RGB')
except UnidentifiedImageError as err:
raise vol.Invalid("Unable to identify image file") from err
self.image_dir.mkdir(parents=True, exist_ok=True)
media_file = self.image_dir / "{}.jpg".format(basename)
_LOGGER.debug("Storing file %s", media_file)
with media_file.open("wb") as target:
image.save(target, "JPEG", quality=self.quality)
self.cleanup()
def cleanup(self):
"""Removes excess images."""
images = self.image_filenames()
total_frames = len(images)
d = total_frames > self.max_frames and total_frames - self.max_frames or 0
for file in images[:d]:
file.unlink(missing_ok=True)
def clear_images(self):
"""Remove all images."""
return self.hass.async_add_executor_job(shutil.rmtree, self.image_dir)
def image_filenames(self):
return sorted(self.image_dir.glob("*.jpg"))
def camera_image(self):
try:
last_image = self.image_filenames().pop()
with open(last_image, "rb") as file:
return file.read()
except IndexError as err:
return None
async def handle_async_mjpeg_stream(self, request):
def get_images():
if self.loop:
return itertools.cycle(self.image_filenames())
else:
return iter(self.image_filenames())
images = get_images()
async def next_image():
nonlocal images
try:
while self.is_on:
try:
with open(next(images), "rb") as file:
return file.read()
except FileNotFoundError:
images = get_images()
except StopIteration:
return None
return await async_get_still_stream(request, next_image, DEFAULT_CONTENT_TYPE, self.frame_interval)
async def async_removed_from_registry(self):
self.stop_fetching()
await self.clear_images()