-
Notifications
You must be signed in to change notification settings - Fork 645
/
config.py
1784 lines (1311 loc) · 60.3 KB
/
config.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
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright (c) 2013 Calin Crisan
# This file is part of motionEye.
#
# motionEye is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import collections
import datetime
import errno
import logging
import os.path
import re
import shlex
import subprocess
import urlparse
from tornado.ioloop import IOLoop
import diskctl
import powerctl
import settings
import update
import utils
import v4l2ctl
_CAMERA_CONFIG_FILE_NAME = 'thread-%(id)s.conf'
_MAIN_CONFIG_FILE_NAME = 'motion.conf'
_main_config_cache = None
_camera_config_cache = {}
_camera_ids_cache = None
_additional_section_funcs = []
_additional_config_funcs = []
_additional_structure_cache = {}
# starting with r490 motion config directives have changed a bit
_LAST_OLD_CONFIG_VERSIONS = (490, '3.2.12')
_KNOWN_MOTION_OPTIONS = set([
'auto_brightness', 'brightness', 'contrast', 'emulate_motion', 'event_gap', 'ffmpeg_bps', 'ffmpeg_output_movies', 'ffmpeg_variable_bitrate', 'ffmpeg_video_codec',
'framerate', 'height', 'hue', 'lightswitch', 'locate_motion_mode', 'locate_motion_style', 'minimum_motion_frames', 'movie_filename', 'max_movie_time', 'max_mpeg_time',
'noise_level', 'noise_tune', 'on_event_end', 'on_event_start', 'output_pictures', 'picture_filename', 'post_capture', 'pre_capture', 'quality', 'rotate', 'saturation',
'snapshot_filename', 'snapshot_interval', 'stream_auth_method', 'stream_authentication', 'stream_localhost', 'stream_maxrate', 'stream_motion', 'stream_port', 'stream_quality',
'target_dir', 'text_changes', 'text_double', 'text_left', 'text_right', 'threshold', 'videodevice', 'width',
'webcam_localhost', 'webcam_port', 'webcam_maxrate', 'webcam_quality', 'webcam_motion', 'ffmpeg_cap_new', 'output_normal', 'output_motion', 'jpeg_filename', 'output_all', 'gap', 'locate',
'netcam_url', 'netcam_userpass', 'netcam_http', 'netcam_tolerant_check', 'netcam_keepalive', 'rtsp_uses_tcp'
])
def additional_section(func):
_additional_section_funcs.append(func)
def additional_config(func):
_additional_config_funcs.append(func)
import wifictl # @UnusedImport
import tzctl # @UnusedImport
def get_main(as_lines=False):
global _main_config_cache
if not as_lines and _main_config_cache is not None:
return _main_config_cache
config_file_path = os.path.join(settings.CONF_PATH, _MAIN_CONFIG_FILE_NAME)
logging.debug('reading main config from file %(path)s...' % {'path': config_file_path})
lines = None
try:
file = open(config_file_path, 'r')
except IOError as e:
if e.errno == errno.ENOENT: # file does not exist
logging.info('main config file %(path)s does not exist, using default values' % {'path': config_file_path})
lines = []
else:
logging.error('could not open main config file %(path)s: %(msg)s' % {
'path': config_file_path, 'msg': unicode(e)})
raise
if lines is None:
try:
lines = [l[:-1] for l in file.readlines()]
except Exception as e:
logging.error('could not read main config file %(path)s: %(msg)s' % {
'path': config_file_path, 'msg': unicode(e)})
raise
finally:
file.close()
if as_lines:
return lines
main_config = _conf_to_dict(lines,
list_names=['thread'],
no_convert=['@admin_username', '@admin_password', '@normal_username', '@normal_password'])
_get_additional_config(main_config)
_set_default_motion(main_config, old_motion=is_old_motion())
_main_config_cache = main_config
return main_config
def set_main(main_config):
global _main_config_cache
main_config = dict(main_config)
for n, v in _main_config_cache.iteritems():
main_config.setdefault(n, v)
_main_config_cache = main_config
main_config = dict(main_config)
_set_additional_config(main_config)
config_file_path = os.path.join(settings.CONF_PATH, _MAIN_CONFIG_FILE_NAME)
# read the actual configuration from file
lines = get_main(as_lines=True)
# write the configuration to file
logging.debug('writing main config to %(path)s...' % {'path': config_file_path})
try:
file = open(config_file_path, 'w')
except Exception as e:
logging.error('could not open main config file %(path)s for writing: %(msg)s' % {
'path': config_file_path, 'msg': unicode(e)})
raise
lines = _dict_to_conf(lines, main_config, list_names=['thread'])
try:
file.writelines([utils.make_str(l) + '\n' for l in lines])
except Exception as e:
logging.error('could not write main config file %(path)s: %(msg)s' % {
'path': config_file_path, 'msg': unicode(e)})
raise
finally:
file.close()
def get_camera_ids(filter_valid=True):
global _camera_ids_cache
if _camera_ids_cache is not None:
return _camera_ids_cache
config_path = settings.CONF_PATH
logging.debug('listing config dir %(path)s...' % {'path': config_path})
try:
ls = os.listdir(config_path)
except Exception as e:
logging.error('failed to list config dir %(path)s: %(msg)s', {
'path': config_path, 'msg': unicode(e)})
raise
camera_ids = []
pattern = '^' + _CAMERA_CONFIG_FILE_NAME.replace('%(id)s', '(\d+)') + '$'
for name in ls:
match = re.match(pattern, name)
if match:
camera_id = int(match.groups()[0])
logging.debug('found camera with id %(id)s' % {
'id': camera_id})
camera_ids.append(camera_id)
camera_ids.sort()
if not filter_valid:
return camera_ids
filtered_camera_ids = []
for camera_id in camera_ids:
if get_camera(camera_id):
filtered_camera_ids.append(camera_id)
_camera_ids_cache = filtered_camera_ids
return filtered_camera_ids
def get_enabled_local_motion_cameras():
if not get_main().get('@enabled'):
return []
camera_ids = get_camera_ids()
cameras = [get_camera(camera_id) for camera_id in camera_ids]
return [c for c in cameras if c.get('@enabled') and utils.local_motion_camera(c)]
def get_network_shares():
if not get_main().get('@enabled'):
return []
camera_ids = get_camera_ids()
cameras = [get_camera(camera_id) for camera_id in camera_ids]
mounts = []
for camera in cameras:
if camera.get('@storage_device') != 'network-share':
continue
mounts.append({
'server': camera['@network_server'],
'share': camera['@network_share_name'],
'username': camera['@network_username'],
'password': camera['@network_password'],
})
return mounts
def get_camera(camera_id, as_lines=False):
global _camera_config_cache
if not as_lines and camera_id in _camera_config_cache:
return _camera_config_cache[camera_id]
camera_config_path = os.path.join(settings.CONF_PATH, _CAMERA_CONFIG_FILE_NAME) % {'id': camera_id}
logging.debug('reading camera config from %(path)s...' % {'path': camera_config_path})
try:
file = open(camera_config_path, 'r')
except Exception as e:
logging.error('could not open camera config file: %(msg)s' % {'msg': unicode(e)})
raise
try:
lines = [l.strip() for l in file.readlines()]
except Exception as e:
logging.error('could not read camera config file %(path)s: %(msg)s' % {
'path': camera_config_path, 'msg': unicode(e)})
raise
finally:
file.close()
if as_lines:
return lines
camera_config = _conf_to_dict(lines,
no_convert=['@name', '@network_share_name', '@network_server',
'@network_username', '@network_password', '@storage_device'])
if utils.local_motion_camera(camera_config):
# determine the enabled status
main_config = get_main()
threads = main_config.get('thread', [])
camera_config['@enabled'] = _CAMERA_CONFIG_FILE_NAME % {'id': camera_id} in threads
camera_config['@id'] = camera_id
old_motion = is_old_motion()
# adapt directives from old configuration, if needed
if old_motion:
logging.debug('using old motion config directives')
if 'output_normal' in camera_config:
camera_config['output_pictures'] = camera_config.pop('output_normal')
if 'output_all' in camera_config:
camera_config['emulate_motion'] = camera_config.pop('output_all')
if 'ffmpeg_cap_new' in camera_config:
camera_config['ffmpeg_output_movies'] = camera_config.pop('ffmpeg_cap_new')
if 'locate' in camera_config:
camera_config['locate_motion_mode'] = camera_config.pop('locate')
if 'jpeg_filename' in camera_config:
camera_config['picture_filename'] = camera_config.pop('jpeg_filename')
if 'max_mpeg_time' in camera_config:
camera_config['max_movie_time'] = camera_config.pop('max_mpeg_time')
if 'webcam_port' in camera_config:
camera_config['stream_port'] = camera_config.pop('webcam_port')
if 'webcam_quality' in camera_config:
camera_config['stream_quality'] = camera_config.pop('webcam_quality')
if 'webcam_motion' in camera_config:
camera_config['stream_motion'] = camera_config.pop('webcam_motion')
if 'webcam_maxrate' in camera_config:
camera_config['stream_maxrate'] = camera_config.pop('webcam_maxrate')
if 'webcam_localhost' in camera_config:
camera_config['stream_localhost'] = camera_config.pop('webcam_localhost')
if 'gap' in camera_config:
camera_config['event_gap'] = camera_config.pop('gap')
if 'netcam_http' in camera_config:
camera_config['netcam_keepalive'] = camera_config.pop('netcam_http') in ['1.1', 'keepalive']
_get_additional_config(camera_config, camera_id=camera_id)
elif utils.remote_camera(camera_config):
pass
elif utils.simple_mjpeg_camera(camera_config):
_get_additional_config(camera_config, camera_id=camera_id)
else: # incomplete configuration
logging.warn('camera config file at %s is incomplete, ignoring' % camera_config_path)
return None
_camera_config_cache[camera_id] = dict(camera_config)
return camera_config
def set_camera(camera_id, camera_config):
global _camera_config_cache
camera_config['@id'] = camera_id
_camera_config_cache[camera_id] = camera_config
camera_config = dict(camera_config)
if utils.local_motion_camera(camera_config):
old_motion = is_old_motion()
# adapt directives to old configuration, if needed
if old_motion:
logging.debug('using old motion config directives')
if 'output_pictures' in camera_config:
camera_config['output_normal'] = camera_config.pop('output_pictures')
if 'emulate_motion' in camera_config:
camera_config['output_all'] = camera_config.pop('emulate_motion')
if 'ffmpeg_output_movies' in camera_config:
camera_config['ffmpeg_cap_new'] = camera_config.pop('ffmpeg_output_movies')
if 'locate_motion_mode' in camera_config:
camera_config['locate'] = camera_config.pop('locate_motion_mode')
if 'picture_filename' in camera_config:
camera_config['jpeg_filename'] = camera_config.pop('picture_filename')
if 'max_movie_time' in camera_config:
camera_config['max_mpeg_time'] = camera_config.pop('max_movie_time')
if 'stream_port' in camera_config:
camera_config['webcam_port'] = camera_config.pop('stream_port')
if 'stream_quality' in camera_config:
camera_config['webcam_quality'] = camera_config.pop('stream_quality')
if 'stream_motion' in camera_config:
camera_config['webcam_motion'] = camera_config.pop('stream_motion')
if 'stream_maxrate' in camera_config:
camera_config['webcam_maxrate'] = camera_config.pop('stream_maxrate')
if 'stream_localhost' in camera_config:
camera_config['webcam_localhost'] = camera_config.pop('stream_localhost')
if 'stream_auth_method' in camera_config:
camera_config.pop('stream_auth_method')
if 'stream_authentication' in camera_config:
camera_config.pop('stream_authentication')
if 'event_gap' in camera_config:
camera_config['gap'] = camera_config.pop('event_gap')
if 'netcam_keepalive' in camera_config:
camera_config['netcam_http'] = '1.1' if camera_config.pop('netcam_keepalive') else '1.0'
# set the enabled status in main config
main_config = get_main()
threads = main_config.setdefault('thread', [])
config_file_name = _CAMERA_CONFIG_FILE_NAME % {'id': camera_id}
if camera_config['@enabled'] and config_file_name not in threads:
threads.append(config_file_name)
elif not camera_config['@enabled']:
threads = [t for t in threads if t != config_file_name]
main_config['thread'] = threads
set_main(main_config)
_set_additional_config(camera_config, camera_id=camera_id)
elif utils.remote_camera(camera_config):
pass
elif utils.simple_mjpeg_camera(camera_config):
_set_additional_config(camera_config, camera_id=camera_id)
# read the actual configuration from file
config_file_path = os.path.join(settings.CONF_PATH, _CAMERA_CONFIG_FILE_NAME) % {'id': camera_id}
if os.path.isfile(config_file_path):
lines = get_camera(camera_id, as_lines=True)
else:
lines = []
# write the configuration to file
camera_config_path = os.path.join(settings.CONF_PATH, _CAMERA_CONFIG_FILE_NAME) % {'id': camera_id}
logging.debug('writing camera config to %(path)s...' % {'path': camera_config_path})
try:
file = open(camera_config_path, 'w')
except Exception as e:
logging.error('could not open camera config file %(path)s for writing: %(msg)s' % {
'path': camera_config_path, 'msg': unicode(e)})
raise
lines = _dict_to_conf(lines, camera_config)
try:
file.writelines([utils.make_str(l) + '\n' for l in lines])
except Exception as e:
logging.error('could not write camera config file %(path)s: %(msg)s' % {
'path': camera_config_path, 'msg': unicode(e)})
raise
finally:
file.close()
def add_camera(device_details):
global _camera_ids_cache
global _camera_config_cache
proto = device_details['proto']
if proto in ['netcam', 'mjpeg']:
host = device_details['host']
if device_details['port']:
host += ':' + str(device_details['port'])
if device_details['username'] and proto == 'mjpeg':
if device_details['password']:
host = device_details['username'] + ':' + device_details['password'] + '@' + host
else:
host = device_details['username'] + '@' + host
device_details['url'] = urlparse.urlunparse((device_details['scheme'], host, device_details['path'], '', '', ''))
# determine the last camera id
camera_ids = get_camera_ids()
camera_id = 1
while camera_id in camera_ids:
camera_id += 1
logging.info('adding new camera with id %(id)s...' % {'id': camera_id})
# prepare a default camera config
camera_config = {'@enabled': True}
if proto == 'v4l2':
# find a suitable resolution
for (w, h) in v4l2ctl.list_resolutions(device_details['path']):
if w > 300:
camera_config['width'] = w
camera_config['height'] = h
break
camera_config['videodevice'] = device_details['path']
elif proto == 'motioneye':
camera_config['@proto'] = 'motioneye'
camera_config['@scheme'] = device_details['scheme']
camera_config['@host'] = device_details['host']
camera_config['@port'] = device_details['port']
camera_config['@path'] = device_details['path']
camera_config['@username'] = device_details['username']
camera_config['@password'] = device_details['password']
camera_config['@remote_camera_id'] = device_details['remote_camera_id']
elif proto == 'netcam':
camera_config['netcam_url'] = device_details['url']
camera_config['text_double'] = True
if device_details['username']:
camera_config['netcam_userpass'] = device_details['username'] + ':' + device_details['password']
camera_config['netcam_keepalive'] = device_details.get('keep_alive', False)
camera_config['netcam_tolerant_check'] = True
if device_details.get('camera_index') == 'udp':
camera_config['rtsp_uses_tcp'] = False
if camera_config['netcam_url'].startswith('rtsp'):
camera_config['width'] = 640
camera_config['height'] = 480
else: # assuming mjpeg
camera_config['@proto'] = 'mjpeg'
camera_config['@url'] = device_details['url']
if utils.local_motion_camera(camera_config):
_set_default_motion_camera(camera_id, camera_config)
# go through the config conversion functions back and forth once
camera_config = motion_camera_ui_to_dict(motion_camera_dict_to_ui(camera_config), camera_config)
elif utils.simple_mjpeg_camera(camera_config):
_set_default_simple_mjpeg_camera(camera_id, camera_config)
# go through the config conversion functions back and forth once
camera_config = simple_mjpeg_camera_ui_to_dict(simple_mjpeg_camera_dict_to_ui(camera_config), camera_config)
# write the configuration to file
set_camera(camera_id, camera_config)
_camera_ids_cache = None
_camera_config_cache = {}
camera_config = get_camera(camera_id)
return camera_config
def rem_camera(camera_id):
global _camera_ids_cache
global _camera_config_cache
camera_config_name = _CAMERA_CONFIG_FILE_NAME % {'id': camera_id}
camera_config_path = os.path.join(settings.CONF_PATH, _CAMERA_CONFIG_FILE_NAME) % {'id': camera_id}
# remove the camera from the main config
main_config = get_main()
threads = main_config.setdefault('thread', [])
threads = [t for t in threads if t != camera_config_name]
main_config['thread'] = threads
set_main(main_config)
logging.info('removing camera config file %(path)s...' % {'path': camera_config_path})
_camera_ids_cache = None
_camera_config_cache = {}
try:
os.remove(camera_config_path)
except Exception as e:
logging.error('could not remove camera config file %(path)s: %(msg)s' % {
'path': camera_config_path, 'msg': unicode(e)})
raise
def main_ui_to_dict(ui):
data = {
'@enabled': ui['enabled'],
'@show_advanced': ui['show_advanced'],
'@admin_username': ui['admin_username'],
'@admin_password': ui['admin_password'],
'@normal_username': ui['normal_username'],
'@normal_password': ui['normal_password']
}
# additional configs
for name, value in ui.iteritems():
if not name.startswith('_'):
continue
data['@' + name] = value
return data
def main_dict_to_ui(data):
ui = {
'enabled': data['@enabled'],
'show_advanced': data['@show_advanced'],
'admin_username': data['@admin_username'],
'admin_password': data['@admin_password'],
'normal_username': data['@normal_username'],
'normal_password': data['@normal_password']
}
# additional configs
for name, value in data.iteritems():
if not name.startswith('@_'):
continue
ui[name[1:]] = value
return ui
def motion_camera_ui_to_dict(ui, old_config=None):
import meyectl
import smbctl
old_config = dict(old_config or {})
main_config = get_main() # needed for surveillance password
data = {
# device
'@name': ui['name'],
'@enabled': ui['enabled'],
'auto_brightness': ui['auto_brightness'],
'framerate': int(ui['framerate']),
'rotate': int(ui['rotation']),
# file storage
'@storage_device': ui['storage_device'],
'@network_server': ui['network_server'],
'@network_share_name': ui['network_share_name'],
'@network_username': ui['network_username'],
'@network_password': ui['network_password'],
# text overlay
'text_left': '',
'text_right': '',
'text_double': False,
# streaming
'stream_localhost': not ui['video_streaming'],
'stream_port': int(ui['streaming_port']),
'stream_maxrate': int(ui['streaming_framerate']),
'stream_quality': max(1, int(ui['streaming_quality'])),
'@webcam_resolution': max(1, int(ui['streaming_resolution'])),
'@webcam_server_resize': ui['streaming_server_resize'],
'stream_motion': ui['streaming_motion'],
'stream_auth_method': {'disabled': 0, 'basic': 1, 'digest': 2}.get(ui['streaming_auth_mode'], 0),
'stream_authentication': main_config['@normal_username'] + ':' + main_config['@normal_password'],
# still images
'output_pictures': False,
'snapshot_interval': 0,
'picture_filename': '',
'snapshot_filename': '',
'quality': max(1, int(ui['image_quality'])),
'@preserve_pictures': int(ui['preserve_pictures']),
# movies
'ffmpeg_output_movies': False,
'movie_filename': ui['movie_file_name'],
'ffmpeg_bps': 44000, # a quality of about 85% for 320x240x2fps
'max_movie_time': ui['max_movie_length'],
'@preserve_movies': int(ui['preserve_movies']),
# motion detection
'@motion_detection': ui['motion_detection'],
'emulate_motion': False,
'text_changes': ui['show_frame_changes'],
'locate_motion_mode': ui['show_frame_changes'],
'noise_tune': ui['auto_noise_detect'],
'noise_level': max(1, int(round(int(ui['noise_level']) * 2.55))),
'lightswitch': ui['light_switch_detect'],
'event_gap': int(ui['event_gap']),
'pre_capture': int(ui['pre_capture']),
'post_capture': int(ui['post_capture']),
'minimum_motion_frames': int(ui['minimum_motion_frames']),
# working schedule
'@working_schedule': '',
# events
'on_event_start': '',
'on_event_end': ''
}
if utils.v4l2_camera(old_config):
proto = 'v4l2'
else:
proto = 'netcam'
if proto == 'v4l2':
# leave videodevice unchanged
# resolution
if not ui['resolution']:
ui['resolution'] = '320x240'
width = int(ui['resolution'].split('x')[0])
height = int(ui['resolution'].split('x')[1])
data['width'] = width
data['height'] = height
threshold = int(float(ui['frame_change_threshold']) * width * height / 100)
if 'brightness' in ui:
if int(ui['brightness']) == 50:
data['brightness'] = 0
else:
data['brightness'] = max(1, int(round(int(ui['brightness']) * 2.55)))
if 'contrast' in ui:
if int(ui['contrast']) == 50:
data['contrast'] = 0
else:
data['contrast'] = max(1, int(round(int(ui['contrast']) * 2.55)))
if 'saturation' in ui:
if int(ui['saturation']) == 50:
data['saturation'] = 0
else:
data['saturation'] = max(1, int(round(int(ui['saturation']) * 2.55)))
if 'hue' in ui:
if int(ui['hue']) == 50:
data['hue'] = 0
else:
data['hue'] = max(1, int(round(int(ui['hue']) * 2.55)))
else: # assuming netcam
if data.get('netcam_url', old_config.get('netcam_url', '')).startswith('rtsp'):
# motion uses the configured width and height for RTSP cameras
width = int(ui['resolution'].split('x')[0])
height = int(ui['resolution'].split('x')[1])
data['width'] = width
data['height'] = height
threshold = int(float(ui['frame_change_threshold']) * width * height / 100)
else: # width & height are not available for other netcams
threshold = int(float(ui['frame_change_threshold']) * 640 * 480 / 100)
data['threshold'] = threshold
if (ui['storage_device'] == 'network-share') and settings.SMB_SHARES:
mount_point = smbctl.make_mount_point(ui['network_server'], ui['network_share_name'], ui['network_username'])
if ui['root_directory'].startswith('/'):
ui['root_directory'] = ui['root_directory'][1:]
data['target_dir'] = os.path.normpath(os.path.join(mount_point, ui['root_directory']))
elif ui['storage_device'].startswith('local-disk'):
target_dev = ui['storage_device'][10:].replace('-', '/')
mounted_partitions = diskctl.list_mounted_partitions()
partition = mounted_partitions[target_dev]
mount_point = partition['mount_point']
if ui['root_directory'].startswith('/'):
ui['root_directory'] = ui['root_directory'][1:]
data['target_dir'] = os.path.normpath(os.path.join(mount_point, ui['root_directory']))
else:
data['target_dir'] = ui['root_directory']
if ui['text_overlay']:
left_text = ui['left_text']
if left_text == 'camera-name':
data['text_left'] = ui['name']
elif left_text == 'timestamp':
data['text_left'] = '%Y-%m-%d\\n%T'
elif left_text == 'disabled':
data['text_left'] = ''
else:
data['text_left'] = ui['custom_left_text']
right_text = ui['right_text']
if right_text == 'camera-name':
data['text_right'] = ui['name']
elif right_text == 'timestamp':
data['text_right'] = '%Y-%m-%d\\n%T'
elif right_text == 'disabled':
data['text_right'] = ''
else:
data['text_right'] = ui['custom_right_text']
if proto == 'netcam' or data['width'] > 320:
data['text_double'] = True
if ui['still_images']:
capture_mode = ui['capture_mode']
if capture_mode == 'motion-triggered':
data['output_pictures'] = True
data['picture_filename'] = ui['image_file_name']
elif capture_mode == 'interval-snapshots':
data['snapshot_interval'] = int(ui['snapshot_interval'])
data['snapshot_filename'] = ui['image_file_name']
elif capture_mode == 'all-frames':
data['output_pictures'] = True
data['emulate_motion'] = True
data['picture_filename'] = ui['image_file_name']
if ui['movies']:
data['ffmpeg_output_movies'] = True
recording_mode = ui['recording_mode']
if recording_mode == 'motion-triggered':
data['emulate_motion'] = False
elif recording_mode == 'continuous':
data['emulate_motion'] = True
if proto == 'v4l2':
max_val = data['width'] * data['height'] * data['framerate']
else: # assume a netcam image size of 640x480, since we have no means to know it at this point
max_val = 640 * 480 * data['framerate']
max_val = min(max_val, 9999999)
data['ffmpeg_bps'] = int(int(ui['movie_quality']) * max_val / 100)
# working schedule
if ui['working_schedule']:
data['@working_schedule'] = (
ui['monday_from'] + '-' + ui['monday_to'] + '|' +
ui['tuesday_from'] + '-' + ui['tuesday_to'] + '|' +
ui['wednesday_from'] + '-' + ui['wednesday_to'] + '|' +
ui['thursday_from'] + '-' + ui['thursday_to'] + '|' +
ui['friday_from'] + '-' + ui['friday_to'] + '|' +
ui['saturday_from'] + '-' + ui['saturday_to'] + '|' +
ui['sunday_from'] + '-' + ui['sunday_to'])
data['@working_schedule_type'] = ui['working_schedule_type']
# event start
on_event_start = ['%(script)s start %%t' % {'script': meyectl.find_command('relayevent')}]
if ui['email_notifications_enabled']:
send_mail_path = os.path.join(settings.PROJECT_PATH, 'sendmail.py')
send_mail_path = os.path.abspath(send_mail_path)
emails = re.sub('\\s', '', ui['email_notifications_addresses'])
on_event_start.append("%(script)s '%(server)s' '%(port)s' '%(account)s' '%(password)s' '%(tls)s' '%(to)s' 'motion_start' '%%t' '%%Y-%%m-%%dT%%H:%%M:%%S' '%(timespan)s'" % {
'script': meyectl.find_command('sendmail'),
'server': ui['email_notifications_smtp_server'],
'port': ui['email_notifications_smtp_port'],
'account': ui['email_notifications_smtp_account'],
'password': ui['email_notifications_smtp_password'],
'tls': ui['email_notifications_smtp_tls'],
'to': emails,
'timespan': ui['email_notifications_picture_time_span']})
if ui['web_hook_notifications_enabled']:
url = re.sub('\\s', '+', ui['web_hook_notifications_url'])
on_event_start.append("%(script)s '%(method)s' '%(url)s'" % {
'script': meyectl.find_command('webhook'),
'method': ui['web_hook_notifications_http_method'],
'url': url})
if ui['command_notifications_enabled']:
commands = ui['command_notifications_exec'].split(';')
on_event_start += [c.strip() for c in commands]
data['on_event_start'] = '; '.join(on_event_start)
# event end
on_event_end = ['%(script)s stop %%t' % {'script': meyectl.find_command('relayevent')}]
data['on_event_end'] = '; '.join(on_event_end)
# additional configs
for name, value in ui.iteritems():
if not name.startswith('_'):
continue
data['@' + name] = value
# extra motion options
for name in old_config.keys():
if name not in _KNOWN_MOTION_OPTIONS and not name.startswith('@'):
old_config.pop(name)
extra_options = ui.get('extra_options', [])
for name, value in extra_options:
data[name] = value or ''
old_config.update(data)
return old_config
def motion_camera_dict_to_ui(data):
import smbctl
ui = {
# device
'name': data['@name'],
'enabled': data['@enabled'],
'id': data['@id'],
'auto_brightness': data['auto_brightness'],
'framerate': int(data['framerate']),
'rotation': int(data['rotate']),
# file storage
'smb_shares': settings.SMB_SHARES,
'storage_device': data['@storage_device'],
'network_server': data['@network_server'],
'network_share_name': data['@network_share_name'],
'network_username': data['@network_username'],
'network_password': data['@network_password'],
'disk_used': 0,
'disk_total': 0,
'available_disks': diskctl.list_mounted_disks(),
# text overlay
'text_overlay': False,
'left_text': 'camera-name',
'right_text': 'timestamp',
'custom_left_text': '',
'custom_right_text': '',
# streaming
'video_streaming': not data['stream_localhost'],
'streaming_framerate': int(data['stream_maxrate']),
'streaming_quality': int(data['stream_quality']),
'streaming_resolution': int(data['@webcam_resolution']),
'streaming_server_resize': data['@webcam_server_resize'],
'streaming_port': int(data['stream_port']),
'streaming_auth_mode': {0: 'disabled', 1: 'basic', 2: 'digest'}.get(data.get('stream_auth_method'), 'disabled'),
'streaming_motion': int(data['stream_motion']),
# still images
'still_images': False,
'capture_mode': 'motion-triggered',
'image_file_name': '%Y-%m-%d/%H-%M-%S',
'image_quality': data['quality'],
'snapshot_interval': 0,
'preserve_pictures': data['@preserve_pictures'],
# movies
'movies': False,
'recording_mode': 'motion-triggered',
'movie_file_name': data['movie_filename'],
'max_movie_length': data['max_movie_time'],
'preserve_movies': data['@preserve_movies'],
# motion detection
'motion_detection': data['@motion_detection'],
'show_frame_changes': data['text_changes'] or data['locate_motion_mode'],
'auto_noise_detect': data['noise_tune'],
'noise_level': int(int(data['noise_level']) / 2.55),
'light_switch_detect': data['lightswitch'],
'event_gap': int(data['event_gap']),
'pre_capture': int(data['pre_capture']),
'post_capture': int(data['post_capture']),
'minimum_motion_frames': int(data['minimum_motion_frames']),
# motion notifications
'email_notifications_enabled': False,
'web_hook_notifications_enabled': False,
'command_notifications_enabled': False,
# working schedule
'working_schedule': False,
'working_schedule_type': 'during',
'monday_from': '', 'monday_to': '',
'tuesday_from': '', 'tuesday_to': '',
'wednesday_from': '', 'wednesday_to': '',
'thursday_from': '', 'thursday_to': '',
'friday_from': '', 'friday_to': '',
'saturday_from': '', 'saturday_to': '',
'sunday_from': '', 'sunday_to': ''
}
if utils.net_camera(data):
ui['device_url'] = data['netcam_url']
ui['proto'] = 'netcam'
# resolutions
if data['netcam_url'].startswith('rtsp'):
# motion uses the configured width and height for RTSP cameras
resolutions = utils.COMMON_RESOLUTIONS
ui['available_resolutions'] = [(str(w) + 'x' + str(h)) for (w, h) in resolutions]
ui['resolution'] = str(data['width']) + 'x' + str(data['height'])
threshold = data['threshold'] * 100.0 / (data['width'] * data['height'])
else: # width & height are not available for other netcams
# we have no other choice but use something like 640x480 as reference