/
tesla_dashcam.py
3428 lines (3003 loc) · 122 KB
/
tesla_dashcam.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
"""
Merges the 3 Tesla Dashcam and Sentry camera video files into 1 video. If
then further concatenates the files together to make 1 movie.
"""
import argparse
import logging
import os
import sys
from datetime import datetime, timedelta, timezone
from fnmatch import fnmatch
from glob import glob
from pathlib import Path
from re import search
from shlex import split as shlex_split
from shutil import which
from subprocess import CalledProcessError, run
from tempfile import mkstemp
from time import sleep, time as timestamp, mktime
from typing import List, Optional
import requests
from dateutil.parser import isoparse
from psutil import disk_partitions
from tzlocal import get_localzone
_LOGGER = logging.getLogger(__name__)
# TODO: Move everything into classes and separate files. For example,
# update class, font class (for timestamp), folder class, clip class (
# combining front, left, and right info), file class (for individual file).
# Clip class would then have to merge the camera clips, folder class would
# have to concatenate the merged clips. Settings class to take in all settings
# TODO: Create kind of logger or output classes for output. That then allows
# different ones to be created based on where it should go to (stdout,
# log file, ...).
VERSION = {"major": 0, "minor": 1, "patch": 16, "beta": -1}
VERSION_STR = "v{major}.{minor}.{patch}".format(
major=VERSION["major"], minor=VERSION["minor"], patch=VERSION["patch"]
)
if VERSION["beta"] > -1:
VERSION_STR = VERSION_STR + "b{beta}".format(beta=VERSION["beta"])
MONITOR_SLEEP_TIME = 5
GITHUB = {
"URL": "https://api.github.com",
"owner": "ehendrix23",
"repo": "tesla_dashcam",
}
FFMPEG = {
"darwin": "ffmpeg",
"win32": "ffmpeg.exe",
"cygwin": "ffmpeg",
"linux": "ffmpeg",
"freebsd11": "ffmpeg",
}
# noinspection PyPep8
MOVIE_HOMEDIR = {
"darwin": "Movies/Tesla_Dashcam",
"win32": "Videos\Tesla_Dashcam",
"cygwin": "Videos/Tesla_Dashcam",
"linux": "Videos/Tesla_Dashcam",
"freebsd11": "Videos/Tesla_Dashcam",
}
DEFAULT_CLIP_HEIGHT = 960
DEFAULT_CLIP_WIDTH = 1280
MOVIE_QUALITY = {
"HIGH": "18",
"MEDIUM": "20",
"LOW": "23",
"LOWER": "28",
"LOWEST": "33",
}
MOVIE_ENCODING = {
"x264": "libx264",
"x264_nvidia": "h264_nvenc",
"x264_mac": "h264_videotoolbox",
"x264_intel": "h264_qsv",
"x264_rpi": "h264_omx",
"x265": "libx265",
"x265_nvidia": "hevc_nvenc",
"x265_mac": "hevc_videotoolbox",
"x265_intel": "hevc_qsv",
"x265_rpi": "h265",
}
DEFAULT_FONT = {
"darwin": "/Library/Fonts/Arial Unicode.ttf",
"win32": "/Windows/Fonts/arial.ttf",
"cygwin": "/cygdrive/c/Windows/Fonts/arial.ttf",
"linux": "/usr/share/fonts/truetype/freefont/FreeSans.ttf",
"freebsd11": "/usr/share/local/fonts/freefont-ttf/FreeSans.ttf",
}
HALIGN = {"LEFT": "10", "CENTER": "(w/2-text_w/2)", "RIGHT": "(w-text_w)"}
VALIGN = {"TOP": "10", "MIDDLE": "(h/2-(text_h/2))", "BOTTOM": "(h-(text_h*2))"}
TOASTER_INSTANCE = None
display_ts = False
class Font(object):
""" Font Class
"""
def __init__(self, layout, font=None, size=None, color=None):
self._layout = layout
self._font = font
self._size = size
self._color = color
self._halign = None
self._valign = None
self._xpos = None
self._ypos = None
@property
def font(self):
return self._font
@font.setter
def font(self, value):
self._font = value
@property
def size(self):
if hasattr(self._layout, "_font_size"):
return getattr(self._layout, "_font_size")()
return (
int(max(16, 16 * self._layout.scale)) if self._size is None else self._size
)
@size.setter
def size(self, value):
self._size = value
@property
def color(self):
return self._color
@color.setter
def color(self, value):
self._color = value
@property
def halign(self):
if hasattr(self._layout, "_font_halign"):
return getattr(self._layout, "_font_halign")()
return HALIGN.get(self._halign, self._halign)
@halign.setter
def halign(self, value):
self._halign = value
@property
def valign(self):
if hasattr(self._layout, "_font_valign"):
return getattr(self._layout, "_font_valign")()
return VALIGN.get(self._valign, self._valign)
@valign.setter
def valign(self, value):
self._valign = value
@property
def xpos(self):
return self._xpos
@xpos.setter
def xpos(self, value):
self._xpos = value
@property
def ypos(self):
return self._ypos
@ypos.setter
def ypos(self, value):
self._ypos = value
class Camera(object):
""" Camera Class
"""
def __init__(self, layout, camera):
self._layout = layout
self._camera = camera
self._include = True
self._width = 1280
self._height = 960
self._xpos = 0
self._ypos = 0
self._scale = 0
self._options = ""
@property
def camera(self):
return self._camera
@camera.setter
def camera(self, value):
self._camera = value
@property
def include(self):
return self._include
@include.setter
def include(self, value):
self._include = value
@property
def width(self):
return (
getattr(self._layout, "_" + self._camera + "_width")()
if hasattr(self._layout, "_" + self._camera + "_width")
else int(self._width * self.scale * self.include)
)
@width.setter
def width(self, value):
self._width = value
@property
def height(self):
return (
getattr(self._layout, "_" + self._camera + "_height")()
if hasattr(self._layout, "_" + self._camera + "_height")
else int(self._height * self.scale * self.include)
)
@height.setter
def height(self, value):
self._height = value
@property
def xpos(self):
if hasattr(self._layout, "_" + self._camera + "_xpos"):
return getattr(self._layout, "_" + self._camera + "_xpos")() * self.include
return self._xpos * self.include
@xpos.setter
def xpos(self, value):
self._xpos = value
@property
def ypos(self):
if hasattr(self._layout, "_" + self._camera + "_ypos"):
return getattr(self._layout, "_" + self._camera + "_ypos")() * self.include
return self._ypos * self.include
@ypos.setter
def ypos(self, value):
self._ypos = value
@property
def scale(self):
return self._scale
@scale.setter
def scale(self, value):
if value is None:
self._scale = None
elif len(str(value).split("x")) == 1:
# Scale provided is a multiplier
self._scale = float(str(value).split("x")[0])
else:
# Scale is a resolution.
self.width = int(str(value).split("x")[0])
self.height = int(str(value).split("x")[1])
self._scale = 1
@property
def options(self):
return self._options
@options.setter
def options(self, value):
self._options = value
class MovieLayout(object):
""" Main Layout class
"""
def __init__(self):
self._cameras = {
"Front": Camera(layout=self, camera="front"),
"Left": Camera(layout=self, camera="left"),
"Right": Camera(layout=self, camera="right"),
"Rear": Camera(layout=self, camera="rear"),
}
self._font = Font(layout=self)
self._swap_left_right = False
self._swap_front_rear = False
self._perspective = False
self._font.halign = "CENTER"
self._font.valign = "BOTTOM"
def cameras(self, camera):
return self._cameras.get(camera, self._cameras)
@property
def font(self):
return self._font
@font.setter
def font(self, value):
self._font = value
@property
def swap_left_right(self):
return self._swap_left_right
@swap_left_right.setter
def swap_left_right(self, value):
self._swap_left_right = value
@property
def swap_front_rear(self):
return self._swap_front_rear
@swap_front_rear.setter
def swap_front_rear(self, value):
self._swap_front_rear = value
@property
def perspective(self):
return self._perspective
@perspective.setter
def perspective(self, new_perspective):
self._perspective = new_perspective
if self._perspective:
self.cameras("Left").options = (
", pad=iw+4:3/2*ih:-1:ih/8:0x00000000, "
"perspective=x0=0:y0=1*H/5:x1=W:y1=-3/44*H:"
"x2=0:y2=6*H/5:x3=7/8*W:y3=5*H/6:sense=destination"
)
self.cameras("Right").options = (
", pad=iw+4:3/2*ih:-1:ih/8:0x00000000,"
"perspective=x0=0:y1=1*H/5:x1=W:y0=-3/44*H:"
"x2=1/8*W:y3=6*H/5:x3=W:y2=5*H/6:sense=destination"
)
else:
self.cameras("Left").options = ""
self.cameras("Right").options = ""
@property
def scale(self):
# Return scale of new video based on 1280x960 video = scale:1
return (self.video_height * self.video_width) / (1280 * 960)
@scale.setter
def scale(self, scale):
self.cameras("Front").scale = scale
self.cameras("Left").scale = scale
self.cameras("Right").scale = scale
self.cameras("Rear").scale = scale
@property
def video_width(self):
return int(
max(
self.cameras("Front").xpos + self.cameras("Front").width,
self.cameras("Left").xpos + self.cameras("Left").width,
self.cameras("Right").xpos + self.cameras("Right").width,
self.cameras("Rear").xpos + self.cameras("Rear").width,
)
)
@property
def video_height(self):
perspective_adjustement = 3 / 2 if self.perspective else 1
return int(
max(
self.cameras("Front").ypos + self.cameras("Front").height,
perspective_adjustement * self.cameras("Left").ypos
+ self.cameras("Left").height,
perspective_adjustement * self.cameras("Right").ypos
+ self.cameras("Right").height,
self.cameras("Rear").ypos + self.cameras("Rear").height,
)
)
@property
def center_xpos(self):
return int(self.video_width / 2)
@property
def center_ypos(self):
return int(self.video_height / 2)
class FullScreen(MovieLayout):
""" FullScreen Movie Layout
[FRONT_CAMERA]
[LEFT_CAMERA][REAR_CAMERA][RIGHT_CAMERA]
"""
def __init__(self):
super().__init__()
self.scale = 1 / 2
@property
def video_width(self):
return int(
max(
self.cameras("Front").width,
self.cameras("Left").width
+ self.cameras("Rear").width
+ self.cameras("Right").width,
)
)
@property
def video_height(self):
perspective_adjustement = 3 / 2 if self.perspective else 1
return int(
self.cameras("Front").height
+ max(
perspective_adjustement * self.cameras("Left").height,
self.cameras("Rear").height,
perspective_adjustement * self.cameras("Right").height,
)
)
def _front_height(self):
# For height keep same ratio of 4/3
return int(self.cameras("Front").width / 4 * 3)
def _front_xpos(self):
# Make sure that front is placed in the middle
return (
max(
0,
self.center_xpos
- int(
(
self.cameras("Left").width
+ self.cameras("Front").width
+ self.cameras("Right").width
)
/ 2
)
+ self.cameras("Left").width,
)
* self.cameras("Front").include
)
def _left_xpos(self):
return (
max(
0,
self.center_xpos
- int(
(
self.cameras("Left").width
+ self.cameras("Rear").width
+ self.cameras("Right").width
)
/ 2
),
)
* self.cameras("Left").include
)
def _left_ypos(self):
return (
self.cameras("Front").ypos + self.cameras("Front").height
) * self.cameras("Left").include
def _rear_xpos(self):
return (
max(
0,
self.center_xpos
- int(
(
self.cameras("Left").width
+ self.cameras("Rear").width
+ self.cameras("Right").width
)
/ 2
)
+ self.cameras("Left").width,
)
* self.cameras("Rear").include
)
def _rear_ypos(self):
return (
self.cameras("Front").ypos + self.cameras("Front").height
) * self.cameras("Rear").include
def _right_xpos(self):
return (
max(
0,
self.center_xpos
- int(
(
self.cameras("Left").width
+ self.cameras("Rear").width
+ self.cameras("Right").width
)
/ 2
)
+ self.cameras("Left").width
+ self.cameras("Rear").width,
)
* self.cameras("Right").include
)
def _right_ypos(self):
return (
self.cameras("Front").ypos + self.cameras("Front").height
) * self.cameras("Right").include
# noinspection PyProtectedMember
class WideScreen(FullScreen):
""" WideScreen Movie Layout
[ FRONT_CAMERA ]
[LEFT_CAMERA][REAR_CAMERA][RIGHT_CAMERA]
"""
def __init__(self):
super().__init__()
self.scale = 1 / 2
# Set front scale to None so we know if it was overriden or not.
self.cameras("Front").scale = None
# Only front_width has to be adjusted as by default width would be left+rear+right instead of normal scale.
def _front_width(self):
return (
(
self.cameras("Left").width
+ self.cameras("Rear").width
+ self.cameras("Right").width
)
* self.cameras("Front").include
if self.cameras("Front").scale is None
else int(
(
self.cameras("Front")._width
* self.cameras("Front").scale
* self.cameras("Front").include
)
)
)
class Cross(FullScreen):
""" Cross Movie Layout
[FRONT_CAMERA]
[LEFT_CAMERA][RIGHT_CAMERA]
[REAR_CAMERA]
"""
def __init__(self):
super().__init__()
self.scale = 1 / 2
@property
def video_width(self):
return max(
self.cameras("Front").width,
self.cameras("Left").width + self.cameras("Right").width,
self.cameras("Rear").width,
)
@property
def video_height(self):
if self.perspective:
height = int(
max(
3 / 2 * self.cameras("Left").height,
3 / 2 * self.cameras("Right").height,
)
)
if (
self.cameras("Left").include
and self.cameras("Left").scale >= self.cameras("Rear").scale
and self.cameras("Right").include
and self.cameras("Right").scale >= self.cameras("Rear").scale
and self.cameras("Rear").include
):
height = int(height / 3 * 2)
height += self.cameras("Rear").height
else:
height = (
max(self.cameras("Left").height, self.cameras("Right").height)
+ self.cameras("Rear").height
)
return int(height + self.cameras("Front").height)
def _front_xpos(self):
return (
int(max(0, self.center_xpos - (self.cameras("Front").width / 2)))
* self.cameras("Front").include
)
def _left_xpos(self):
return (
max(
0,
self.center_xpos
- int((self.cameras("Left").width + self.cameras("Right").width) / 2),
)
* self.cameras("Left").include
)
def _left_ypos(self):
return (
self.cameras("Front").height
+ int(
(
max(self.cameras("Left").height, self.cameras("Right").height)
- self.cameras("Left").height
)
/ 2
)
) * self.cameras("Left").include
def _right_xpos(self):
return (
max(
0,
self.center_xpos
- int((self.cameras("Left").width + self.cameras("Right").width) / 2)
+ self.cameras("Left").width,
)
* self.cameras("Right").include
)
def _right_ypos(self):
return (
self.cameras("Front").height
+ int(
(
max(self.cameras("Left").height, self.cameras("Right").height)
- self.cameras("Right").height
)
/ 2
)
) * self.cameras("Right").include
def _rear_xpos(self):
return (
int(max(0, self.center_xpos - (self.cameras("Rear").width / 2)))
* self.cameras("Rear").include
)
def _rear_ypos(self):
return int(max(0, self.video_height - self.cameras("Rear").height))
# noinspection PyProtectedMember
class Diamond(Cross):
""" Diamond Movie Layout
[FRONT_CAMERA]
[LEFT_CAMERA] [RIGHT_CAMERA]
[REAR_CAMERA]
"""
def __init__(self):
super().__init__()
self.scale = 1 / 2
self._font.valign = "MIDDLE"
def _font_halign(self):
if self._font._halign == "CENTER":
# Change alignment to left or right if one of the left/right cameras is excluded.
if (self.cameras("Left").include and not self.cameras("Right").include) or (
self.cameras("Right").include and not self.cameras("Left").include
):
x_pos = int(
max(
self.cameras("Front").xpos + self.cameras("Front").width / 2,
self.cameras("Rear").xpos + self.cameras("Rear").width / 2,
)
)
return f"({x_pos} - text_w / 2)"
return HALIGN.get(self._font._halign, self._font._halign)
def _font_valign(self):
if self._font._valign == "MIDDLE":
if self.cameras("Front").include:
return (
f'({self.cameras("Front").ypos + self.cameras("Front").height} + 5)'
)
elif self.cameras("Rear").include:
return f'({self.cameras("Rear").ypos} - 5 - text_h)'
return VALIGN.get(self._font._valign, self._font._valign)
def _font_size(self):
# For this layout the video height has to include font size. But default for calculating
# font size is based on video height.
# Thus overriding font size to get video height without font size to figure our scaling.
if self.font._size is None:
scale = (
self._video_height(include_fontsize=False)
* self.video_width
/ (1280 * 960)
)
return int(max(16, 16 * scale))
else:
return self.font.size
@property
def video_width(self):
return (
max(self.cameras("Front").width, self.cameras("Rear").width)
+ self.cameras("Left").width
+ self.cameras("Right").width
)
def _video_height(self, include_fontsize=True):
perspective = 3 / 2 if self.perspective else 1
fontsize = self.font.size if include_fontsize else 0
return int(
max(
perspective
* max(self.cameras("Left").height, self.cameras("Right").height),
self.cameras("Front").height + self.cameras("Rear").height + fontsize,
)
)
@property
def video_height(self):
return self._video_height(include_fontsize=True)
def _front_xpos(self):
return (
self.cameras("Left").width
+ int(
(
max(self.cameras("Front").width, self.cameras("Rear").width)
- self.cameras("Front").width
)
/ 2
)
) * self.cameras("Front").include
def _left_xpos(self):
return 0
def _left_ypos(self):
return max(0, self.center_ypos - int(self.cameras("Left").height / 2))
def _right_xpos(self):
return max(
self.cameras("Front").xpos + self.cameras("Front").width,
self.cameras("Rear").xpos + self.cameras("Rear").width,
)
def _right_ypos(self):
return max(0, self.center_ypos - int(self.cameras("Right").height / 2))
def _rear_xpos(self):
return (
self.cameras("Left").width
+ int(
(
max(self.cameras("Front").width, self.cameras("Rear").width)
- self.cameras("Rear").width
)
/ 2
)
) * self.cameras("Rear").include
class MyArgumentParser(argparse.ArgumentParser):
def convert_arg_line_to_args(self, arg_line):
# Remove comments.
return shlex_split(arg_line, comments=True)
def args_to_dict(self, arguments, default):
argument_list = []
if arguments is None:
return argument_list
for argument in arguments:
argument_dict = {}
for argument_value in argument:
if "=" in argument_value:
key = argument_value.split("=")[0].lower()
value = (
argument_value.split("=")[1].strip()
if argument_value.split("=")[1].strip() != ""
else None
)
else:
key = default
value = argument_value
argument_dict.update({key: value})
argument_list.append(argument_dict)
return argument_list
# noinspection PyCallByClass,PyProtectedMember
class SmartFormatter(argparse.HelpFormatter):
""" Formatter for argument help. """
def _split_lines(self, text, width):
""" Provide raw output allowing for prettier help output """
if text.startswith("R|"):
return text[2:].splitlines()
# this is the RawTextHelpFormatter._split_lines
return argparse.HelpFormatter._split_lines(self, text, width)
def _get_help_string(self, action):
""" Call default help string """
return argparse.ArgumentDefaultsHelpFormatter._get_help_string(self, action)
def search_dict(
match_value: object = None, key: str = None, search_list: List[dict] = None
) -> Optional[dict]:
"""
Returns the 1st element in a list containing dictionaries
where the value of key provided matches the value provided.
:param match_value: value to match upon (search for)
:type match_value: object
:param key: dictionary key to use for the match
:type key: str
:param search_list: List containing dictionary objects in which to search
:type search_list: List[dict]
:return: Dictionary object that matches
:rtype: dict
"""
if key is None or search_list is None:
return None
if match_value is None:
return next(
(element for element in search_list if element.get(key) is None), None
)
return next(
(element for element in search_list if element.get(key) == match_value), None
)
def get_current_timestamp():
"""Returns the current timestamp"""
"""Uses ugly global variable, this should die a quick death..."""
"""Preferably, a text output class should be created and the value stored there."""
if display_ts:
return datetime.now().strftime('%Y-%m-%d %H:%M:%S - ')
else:
return ''
def check_latest_release(include_beta):
""" Checks GitHub for latest release """
url = "{url}/repos/{owner}/{repo}/releases".format(
url=GITHUB["URL"], owner=GITHUB["owner"], repo=GITHUB["repo"]
)
if not include_beta:
url = url + "/latest"
try:
releases = requests.get(url)
except requests.exceptions.RequestException as exc:
print(get_current_timestamp() + "Unable to check for latest release: {exc}".format(exc=exc))
return None
release_data = releases.json()
# If we include betas then we would have received a list, thus get 1st
# element as that is the latest release.
if include_beta:
release_data = release_data[0]
return release_data
def get_tesladashcam_folder():
""" Check if there is a drive mounted with the Tesla DashCam folder."""
for partition in disk_partitions(all=False):
if "cdrom" in partition.opts or partition.fstype == "":
continue
teslacamfolder = os.path.join(partition.mountpoint, "TeslaCam")
if os.path.isdir(teslacamfolder):
_LOGGER.debug(f"{get_current_timestamp()}Folder TeslaCam found on partition {partition.mountpoint}.")
return teslacamfolder, partition.mountpoint
_LOGGER.debug(f"{get_current_timestamp()}No TeslaCam folder on partition {partition.mountpoint}.")
return None, None
def get_movie_files(source_folder, exclude_subdirs, video_settings):
""" Find all the clip files within folder (and subfolder if requested) """
folder_list = {}
total_folders = 0
for pathname in source_folder:
if os.path.isdir(pathname):
isfile = False
if exclude_subdirs:
# Retrieve all the video files in current path:
search_path = os.path.join(pathname, "*.mp4")
files = [
filename
for filename in glob(search_path)
if not os.path.basename(filename).startswith(".")
]
print(f"{get_current_timestamp()}Discovered {len(files)} files in {pathname}")
else:
# Search all sub folder.
files = []
for folder, _, filenames in os.walk(pathname, followlinks=True):
total_folders = total_folders + 1
for filename in (
filename
for filename in filenames
if not os.path.basename(filename).startswith(".")
and fnmatch(filename, "*.mp4")
):
files.append(os.path.join(folder, filename))
print(
f"{get_current_timestamp()}Discovered {total_folders} folders containing total of {len(files)} files in {pathname}"
)
else:
files = [pathname]
isfile = True
# Now go through and get timestamps etc..
for file in sorted(files):
# Strip path so that we just have the filename.
movie_folder, movie_filename = os.path.split(file)
# And now get the timestamp of the filename.
filename_timestamp = movie_filename.rsplit("-", 1)[0]
movie_file_list = folder_list.get(movie_folder, {})
# Check if we already processed this timestamp.
if movie_file_list.get(filename_timestamp) is not None:
# Already processed this timestamp, moving on.
continue
_LOGGER.debug(
f"{get_current_timestamp()}Checking camera files in folder {movie_folder} with timestamp {filename_timestamp}"
)
video_info = {
"front_camera": {
"filename": None,
"duration": None,
"timestamp": None,
"include": False,
},
"left_camera": {
"filename": None,
"duration": None,
"timestamp": None,
"include": False,
},
"right_camera": {
"filename": None,
"duration": None,
"timestamp": None,
"include": False,
},
"rear_camera": {
"filename": None,
"duration": None,
"timestamp": None,
"include": False,