Repository navigation
Expand file tree
/
Copy pathviseron.py
More file actions
199 lines (164 loc) · 5.92 KB
/
Copy pathviseron.py
File metadata and controls
199 lines (164 loc) · 5.92 KB
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
import logging
import signal
from queue import Queue
from threading import Thread
from const import LOG_LEVELS
from lib.cleanup import Cleanup
from lib.config import CONFIG, NVRConfig, ViseronConfig
from lib.detector import Detector
from lib.mqtt import MQTT
from lib.nvr import FFMPEGNVR
from lib.post_processors import PostProcessor
from viseron_exceptions import FFprobeError
LOGGER = logging.getLogger()
class Viseron:
def __init__(self):
config = ViseronConfig(CONFIG)
log_settings(config)
LOGGER.info("-------------------------------------------")
LOGGER.info("Initializing...")
schedule_cleanup(config)
mqtt_queue = None
mqtt = None
if config.mqtt:
mqtt_queue = Queue(maxsize=100)
mqtt = MQTT(config)
mqtt_publisher = Thread(target=mqtt.publisher, args=(mqtt_queue,))
mqtt_publisher.daemon = True
detector_queue = Queue(maxsize=2)
detector = Detector(config.object_detection)
detector_thread = Thread(
target=detector.object_detection, args=(detector_queue,)
)
detector_thread.daemon = True
detector_thread.start()
post_processors = {}
for (
post_processor_type,
post_processor_config,
) in config.post_processors.post_processors.items():
post_processors[post_processor_type] = PostProcessor(
config, post_processor_type, post_processor_config, mqtt_queue
)
LOGGER.info("Initializing NVR threads")
self.setup_threads = []
self.nvr_threads = []
for camera in config.cameras:
setup_thread = Thread(
target=self.setup_nvr,
args=(
config,
camera,
detector,
detector_queue,
post_processors,
mqtt_queue,
),
)
setup_thread.start()
self.setup_threads.append(setup_thread)
for thread in self.setup_threads:
thread.join()
if mqtt:
mqtt.connect()
mqtt_publisher.start()
for thread in self.nvr_threads:
thread.start()
LOGGER.info("Initialization complete")
def signal_term(*_):
LOGGER.info("Kill received! Sending kill to threads..")
for thread in self.nvr_threads:
thread.stop()
for thread in self.nvr_threads:
thread.join()
# Listen to sigterm
signal.signal(signal.SIGTERM, signal_term)
try:
for thread in self.nvr_threads:
thread.join()
except KeyboardInterrupt:
LOGGER.info("Ctrl-C received! Sending kill to threads..")
for thread in self.nvr_threads:
thread.stop()
for thread in self.nvr_threads:
thread.join()
LOGGER.info("Exiting")
def setup_nvr(
self, config, camera, detector, detector_queue, post_processors, mqtt_queue,
):
camera_config = NVRConfig(
camera,
config.object_detection,
config.motion_detection,
config.recorder,
config.mqtt,
config.logging,
)
try:
nvr = FFMPEGNVR(
camera_config,
detector,
detector_queue,
post_processors,
mqtt_queue=mqtt_queue,
)
self.nvr_threads.append(nvr)
except FFprobeError:
LOGGER.error(f"Failed to initialize camera {camera_config.camera.name}")
def schedule_cleanup(config):
LOGGER.debug("Starting cleanup scheduler")
cleanup = Cleanup(config)
cleanup.start()
LOGGER.debug("Running initial cleanup")
cleanup.cleanup()
def log_settings(config):
LOGGER.setLevel(LOG_LEVELS[config.logging.level])
formatter = logging.Formatter(
"[%(asctime)s] [%(name)-12s] [%(levelname)-8s] - %(message)s",
"%Y-%m-%d %H:%M:%S",
)
formatter = MyFormatter()
handler = logging.StreamHandler()
handler.setFormatter(formatter)
handler.addFilter(DuplicateFilter())
LOGGER.addHandler(handler)
class MyFormatter(logging.Formatter):
# pylint: disable=protected-access
base_format = "[%(asctime)s] [%(name)-24s] [%(levelname)-8s] - %(message)s"
overwrite_fmt = "\x1b[80D\x1b[1A\x1b[K" + base_format
def __init__(self):
super().__init__(
fmt=self.base_format, datefmt="%Y-%m-%d %H:%M:%S", style="%",
)
self.current_count = 0
def format(self, record):
# Save the original format configured by the user
# when the logger formatter was instantiated
format_orig = self._style._fmt
# Replace the original format with one customized by logging level
if "message repeated" in str(record.msg):
self._style._fmt = self.overwrite_fmt
# Call the original formatter class to do the grunt work
result = logging.Formatter.format(self, record)
# Restore the original format configured by the user
self._style._fmt = format_orig
return result
class DuplicateFilter(logging.Filter):
# pylint: disable=attribute-defined-outside-init
def filter(self, record):
current_log = (record.name, record.module, record.levelno, record.msg)
try:
if current_log != getattr(self, "last_log", None):
self.last_log = current_log
self.current_count = 0
else:
self.current_count += 1
if sel
37B8
f.current_count > 0:
record.msg = "{}, message repeated {} times".format(
record.msg, self.current_count + 1
)
except ValueError:
pass
return True
if __name__ == "__main__":
Viseron()