1
|
|
|
#!/usr/bin/env python |
2
|
|
|
# -*- coding: utf-8 -*- |
3
|
|
|
|
4
|
|
|
import logging |
5
|
|
|
from doorpi.action.base import SingleAction |
6
|
|
|
import doorpi |
7
|
|
|
import subprocess as sub |
|
|
|
|
8
|
|
|
import os |
9
|
|
|
import datetime |
10
|
|
|
import glob |
11
|
|
|
|
12
|
|
|
logger = logging.getLogger(__name__) |
13
|
|
|
logger.debug("%s loaded", __name__) |
14
|
|
|
conf = doorpi.DoorPi().config |
15
|
|
|
|
16
|
|
|
DOORPI_SECTION = 'DoorPi' |
17
|
|
|
|
18
|
|
|
|
19
|
|
|
def get_last_snapshot(snapshot_path=None): |
20
|
|
|
if not snapshot_path: |
21
|
|
|
snapshot_path = conf.get_string_parsed(DOORPI_SECTION, 'snapshot_path', '/tmp') |
22
|
|
|
files = sorted(glob.glob(os.path.join(snapshot_path, "*.*")), key=os.path.getctime) |
23
|
|
|
if len(files) > 0: |
24
|
|
|
return files[-1] |
25
|
|
|
else: |
26
|
|
|
return False |
27
|
|
|
|
28
|
|
|
|
29
|
|
|
def get_next_filename(snapshot_path): |
30
|
|
|
if not os.path.exists(snapshot_path): |
31
|
|
|
os.makedirs(snapshot_path) |
32
|
|
|
|
33
|
|
|
files = sorted(glob.glob(os.path.join(snapshot_path, "*.*")), key=os.path.getctime) |
34
|
|
|
if len(files) > conf.get_int(DOORPI_SECTION, 'number_of_snapshots', 10): |
35
|
|
|
try: |
36
|
|
|
os.remove(os.path.join(snapshot_path, files[0])) |
37
|
|
|
except OSError as exp: |
38
|
|
|
logger.warning("couldn't delete snapshot file %s with error %s" % (files[0], exp)) |
39
|
|
|
|
40
|
|
|
return os.path.join( |
41
|
|
|
snapshot_path, |
42
|
|
|
datetime.datetime.now().strftime("%Y-%m-%d_%H-%M-%S")+".jpg" |
43
|
|
|
) |
44
|
|
|
|
45
|
|
|
|
46
|
|
|
def get_snapshot_from_picam(snapshot_path): |
47
|
|
|
import picamera |
48
|
|
|
filename = get_next_filename(snapshot_path) |
49
|
|
|
with picamera.PiCamera() as camera: |
50
|
|
|
camera.resolution = (1024, 768) |
51
|
|
|
camera.capture(filename) |
52
|
|
|
conf.set_value(DOORPI_SECTION, 'last_snapshot', filename) |
53
|
|
|
return filename |
54
|
|
|
|
55
|
|
|
|
56
|
|
|
def get_snapshot_from_url(snapshot_path, url): |
57
|
|
|
import requests |
58
|
|
|
filename = get_next_filename(snapshot_path) |
59
|
|
|
r = requests.get(url, stream=True) |
60
|
|
|
with open(filename, 'wb') as fd: |
61
|
|
|
for chunk in r.iter_content(1024): |
62
|
|
|
fd.write(chunk) |
63
|
|
|
conf.set_value(DOORPI_SECTION, 'last_snapshot', filename) |
64
|
|
|
return filename |
65
|
|
|
|
66
|
|
|
|
67
|
|
|
def get(parameters=""): |
68
|
|
|
snapshot_path = conf.get_string_parsed(DOORPI_SECTION, 'snapshot_path', '/tmp') |
69
|
|
|
if parameters == "": |
70
|
|
|
return SnapShotAction(get_snapshot_from_picam, snapshot_path=snapshot_path) |
71
|
|
|
else: |
72
|
|
|
return SnapShotAction(get_snapshot_from_url, snapshot_path=snapshot_path, url=parameters) |
73
|
|
|
|
74
|
|
|
|
75
|
|
|
class SnapShotAction(SingleAction): |
76
|
|
|
pass |
77
|
|
|
|