|
1
|
|
|
#!/usr/bin/env python |
|
2
|
|
|
# Nat Morris (c) 2017 |
|
3
|
|
|
"""CCTV GIF buffer - Service.""" |
|
4
|
|
|
|
|
5
|
|
|
import collections |
|
6
|
|
|
import imageio |
|
7
|
|
|
import logging |
|
8
|
|
|
import requests |
|
9
|
|
|
import threading |
|
10
|
|
|
import time |
|
11
|
|
|
import io |
|
12
|
|
|
|
|
13
|
|
|
from cctvgifbuffer import version |
|
14
|
|
|
from cctvgifbuffer.webserver import WebServer |
|
15
|
|
|
from requests.auth import HTTPBasicAuth |
|
16
|
|
|
|
|
17
|
|
|
LOG = logging.getLogger(__name__) |
|
18
|
|
|
|
|
19
|
|
|
|
|
20
|
|
|
def camworker(name, config, queue, lock): |
|
21
|
|
|
while True: |
|
22
|
|
|
with lock: |
|
23
|
|
|
respargs = {} |
|
24
|
|
|
if "auth" in config: |
|
25
|
|
|
if config["auth"] == "basic": |
|
26
|
|
|
respargs["auth"] = HTTPBasicAuth(config["username"], config["password"]) |
|
27
|
|
|
resp = requests.get(config["url"], **respargs) |
|
28
|
|
|
if resp.status_code == 200: |
|
29
|
|
|
queue.append(imageio.imread(io.BytesIO(resp.content), format='jpg')) |
|
30
|
|
|
if len(queue) > 30: |
|
31
|
|
|
queue.popleft() |
|
32
|
|
|
time.sleep(2) |
|
33
|
|
|
|
|
34
|
|
|
|
|
35
|
|
|
class Service(object): |
|
36
|
|
|
|
|
37
|
|
|
cameras = None |
|
38
|
|
|
|
|
39
|
|
|
def __init__(self, config): |
|
40
|
|
|
LOG.info("Initializing service v%s", version()) |
|
41
|
|
|
self.cameras = {} |
|
42
|
|
|
LOG.info("Checking camera configs") |
|
43
|
|
|
for name, cameracfg in config["cameras"].iteritems(): |
|
44
|
|
|
self.validate_camera_config(name=name, camera=cameracfg) |
|
45
|
|
|
self.cameras[name] = {"config": cameracfg} |
|
46
|
|
|
LOG.info("%d cameras: %s", len(self.cameras), ', '.join(self.cameras.keys())) |
|
47
|
|
|
# setup each camera with its own lock and thread |
|
48
|
|
|
for name, camera in self.cameras.iteritems(): |
|
49
|
|
|
LOG.debug("%s: %s", name, camera) |
|
50
|
|
|
camera["buffer"] = collections.deque() |
|
51
|
|
|
camera["lock"] = threading.Lock() |
|
52
|
|
|
camera["thread"] = threading.Thread(target=camworker, args=(name, camera["config"], camera["buffer"], camera["lock"])) |
|
53
|
|
|
|
|
54
|
|
|
def start(self): |
|
55
|
|
|
LOG.info("Starting camera threads") |
|
56
|
|
|
# start each camera |
|
57
|
|
|
for name, camera in self.cameras.iteritems(): |
|
58
|
|
|
camera["thread"].start() |
|
59
|
|
|
|
|
60
|
|
|
ws = WebServer(service=self) |
|
61
|
|
|
ws.start() |
|
62
|
|
|
|
|
63
|
|
|
while True: |
|
64
|
|
|
time.sleep(10) |
|
65
|
|
|
|
|
66
|
|
|
def validate_camera_config(self, name, camera): |
|
67
|
|
|
return |
|
68
|
|
|
|