File size: 1,497 Bytes
f021ba1
7ee22ad
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f021ba1
 
7ee22ad
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import os
import logging
from threading import Thread, Event, Lock

log = logging.getLogger(__name__)

_camera_thread = None
_camera_stop = Event()
_socketio_instance = None
_camera_lock = Lock()


def _start_camera():
    global _camera_thread, _camera_stop, _socketio_instance
    if not _socketio_instance:
        log.warning("Cannot start camera: no socketio instance")
        return
    if os.getenv("DISABLE_CAMERA", "").strip() in ("1", "true", "yes"):
        return
    from camera_service import start_camera
    with _camera_lock:
        if _camera_thread and _camera_thread.is_alive():
            return
        _camera_stop.clear()
        _camera_thread = Thread(
            target=start_camera, args=(_socketio_instance, _camera_stop), daemon=True
        )
        _camera_thread.start()
        log.info("Camera started")


def _stop_camera():
    global _camera_stop, _camera_thread
    with _camera_lock:
        if not _camera_thread:
            return
        _camera_stop.set()
        thread = _camera_thread
        _camera_thread = None
    thread.join(timeout=2)
    log.info("Camera stopped")


def register_camera_handlers(socketio):
    global _socketio_instance
    _socketio_instance = socketio

    @socketio.on("request_camera")
    def on_request_camera():
        log.info("request_camera received")
        _start_camera()

    @socketio.on("release_camera")
    def on_release_camera():
        log.info("release_camera received")
        _stop_camera()