-
Notifications
You must be signed in to change notification settings - Fork 102
/
pi-timolo.py
executable file
·3080 lines (2930 loc) · 120 KB
/
pi-timolo.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
#!/usr/bin/env python3
"""
pi-timolo - Raspberry Pi Long Duration Timelapse, Motion Tracking,
with Low Light Capability
written by Claude Pageau Jul-2017 (release 7.x)
This release uses OpenCV to do Motion Tracking.
It requires updated config.py
Oct 2020 Added panoramic pantilt option plus other improvements.
"""
from __future__ import print_function
PROG_VER = "ver 12.65" # Requires Latest 12.5 release of config.py
__version__ = PROG_VER # May test for version number at a future time
import os
WARN_ON = False # Add short delay to review warning messages
MY_PATH = os.path.abspath(__file__) # Find the full path of this python script
# get the path location only (excluding script name)
BASE_DIR = os.path.dirname(MY_PATH)
BASE_FILENAME = os.path.splitext(os.path.basename(MY_PATH))[0]
PROG_NAME = os.path.basename(__file__)
LOG_FILE_PATH = os.path.join(BASE_DIR, BASE_FILENAME + ".log")
HORIZ_LINE = "-------------------------------------------------------"
print(HORIZ_LINE)
print("%s %s written by Claude Pageau" % (PROG_NAME, PROG_VER))
print(HORIZ_LINE)
print("Loading Wait ....")
# import python library modules
import datetime
import logging
import sys
import subprocess
import shutil
import glob
import time
import math
from threading import Thread
from fractions import Fraction
import numpy as np
from PIL import Image
from PIL import ImageFont
from PIL import ImageDraw
# Attempt to import dateutil
try:
from dateutil.parser import parse
except ImportError:
print("WARN : Could Not Import dateutil.parser")
print(" Disabling TIMELAPSE_START_AT, MOTION_START_AT and VideoStartAt")
print(
" See https://github.com/pageauc/pi-timolo/wiki/Basic-Trouble-Shooting#problems-with-python-pip-install-on-wheezy"
)
WARN_ON = True
# Disable get_sched_start if import fails for Raspbian wheezy or Jessie
TIMELAPSE_START_AT = ""
MOTION_START_AT = ""
VIDEO_START_AT = ""
# Attempt to import pyexiv2. Note python3 can be a problem
try:
# pyexiv2 Transfers image exif data to writeTextToImage
# For python3 install of pyexiv2 lib
# See https://github.com/pageauc/pi-timolo/issues/79
# Bypass pyexiv2 if library Not Found
import pyexiv2
except ImportError:
print("WARN : Could Not Import pyexiv2. Required for Saving Image EXIF meta data")
print(
" If Running under python3 then Install pyexiv2 library for python3 per"
)
print(" cd ~/pi-timolo")
print(" ./install-py3exiv2.sh")
WARN_ON = True
except OSError as err:
print("WARN : Could Not import python3 pyexiv2 due to an Operating System Error")
print(" %s" % err)
print(" Camera images will be missing exif meta data")
WARN_ON = True
"""
This is a dictionary of the default settings for pi-timolo.py
If you don't want to use a config.py file these will create the required
variables with default values. Change dictionary values if you want different
variable default values.
A message will be displayed if a variable is Not imported from config.py.
Note: plugins can override default and config.py values if plugins are
enabled. This happens after config.py variables are initialized
"""
default_settings = {
"CONFIG_FILENAME": "default_settings",
"CONFIG_TITLE": "No config.py so using internal dictionary settings",
"PLUGIN_ON": False,
"PLUGIN_NAME": "shopcam",
"VERBOSE_ON": True,
"LOG_TO_FILE_ON": False,
"DEBUG_ON": False,
"IMAGE_NAME_PREFIX": "cam1-",
"IMAGE_WIDTH": 1920,
"IMAGE_HEIGHT": 1080,
"IMAGE_FORMAT": ".jpg",
"IMAGE_JPG_QUAL": 95,
"IMAGE_ROTATION": 0,
"IMAGE_VFLIP": True,
"IMAGE_HFLIP": True,
"IMAGE_GRAYSCALE": False,
"IMAGE_PREVIEW": False,
"IMAGE_PIX_AVE_TIMER_SEC": 15,
"IMAGE_NO_NIGHT_SHOTS": False,
"IMAGE_NO_DAY_SHOTS": False,
"IMAGE_SHOW_STREAM": False,
"STREAM_WIDTH": 320,
"STREAM_HEIGHT": 240,
"STREAM_FPS": 20,
"STREAM_STOP_SEC": 0.7,
"SHOW_DATE_ON_IMAGE": True,
"SHOW_TEXT_FONT_SIZE": 18,
"SHOW_TEXT_BOTTOM": True,
"SHOW_TEXT_WHITE": True,
"SHOW_TEXT_WHITE_NIGHT": True,
"NIGHT_TWILIGHT_MODE_ON": True,
"NIGHT_TWILIGHT_THRESHOLD": 90,
"NIGHT_DARK_THRESHOLD": 50,
"NIGHT_BLACK_THRESHOLD": 4,
"NIGHT_SLEEP_SEC": 30,
"NIGHT_MAX_SHUT_SEC": 5.9,
"NIGHT_MAX_ISO": 800,
"NIGHT_DARK_ADJUST": 4.7,
"TIMELAPSE_ON": True,
"TIMELAPSE_DIR": "media/timelapse",
"TIMELAPSE_PREFIX": "tl-",
"TIMELAPSE_START_AT": "",
"TIMELAPSE_TIMER_SEC": 300,
"TIMELAPSE_CAM_SLEEP_SEC": 4.0,
"TIMELAPSE_NUM_ON": True,
"TIMELAPSE_NUM_RECYCLE_ON": True,
"TIMELAPSE_NUM_START": 1000,
"TIMELAPSE_NUM_MAX": 2000,
"TIMELAPSE_EXIT_SEC": 0,
"TIMELAPSE_MAX_FILES": 0,
"TIMELAPSE_SUBDIR_MAX_FILES": 0,
"TIMELAPSE_SUBDIR_MAX_HOURS": 0,
"TIMELAPSE_RECENT_MAX": 40,
"TIMELAPSE_RECENT_DIR": "media/recent/timelapse",
"MOTION_TRACK_ON": True,
"MOTION_TRACK_QUICK_PIC_ON": False,
"MOTION_TRACK_INFO_ON": True,
"MOTION_TRACK_TIMEOUT_SEC": 0.3,
"MOTION_TRACK_TRIG_LEN": 75,
"MOTION_TRACK_MIN_AREA": 100,
"MOTION_TRACK_QUICK_PIC_BIGGER": 3.0,
"MOTION_DIR": "media/motion",
"MOTION_PREFIX": "mo-",
"MOTION_START_AT": "",
"MOTION_VIDEO_ON": False,
"MOTION_VIDEO_FPS": 15,
"MOTION_VIDEO_WIDTH": 640,
"MOTION_VIDEO_HEIGHT": 480,
"MOTION_VIDEO_TIMER_SEC": 10,
"MOTION_TRACK_MINI_TL_ON": False,
"MOTION_TRACK_MINI_TL_SEQ_SEC": 20,
"MOTION_TRACK_MINI_TL_TIMER_SEC": 4,
"MOTION_TRACK_PANTILT_SEQ_ON": False,
"MOTION_FORCE_SEC": 3600,
"MOTION_NUM_ON": True,
"MOTION_NUM_RECYCLE_ON": True,
"MOTION_NUM_START": 1000,
"MOTION_NUM_MAX": 500,
"MOTION_SUBDIR_MAX_FILES": 0,
"MOTION_SUBDIR_MAX_HOURS": 0,
"MOTION_RECENT_MAX": 40,
"MOTION_RECENT_DIR": "media/recent/motion",
"MOTION_DOTS_ON": False,
"MOTION_DOTS_MAX": 100,
"MOTION_CAM_SLEEP": 0.7,
"CREATE_LOCKFILE": False,
"VIDEO_REPEAT_ON": False,
"VIDEO_REPEAT_WIDTH": 1280,
"VIDEO_REPEAT_HEIGHT": 720,
"VIDEO_DIR": "media/videos",
"VIDEO_PREFIX": "vid-",
"VIDEO_START_AT": "",
"VIDEO_FILE_SEC": 120,
"VIDEO_SESSION_MIN": 60,
"VIDEO_FPS": 30,
"VIDEO_NUM_ON": False,
"VIDEO_NUM_RECYCLE_ON": False,
"VIDEO_NUM_START": 100,
"VIDEO_NUM_MAX": 20,
"PANTILT_ON": False,
"PANTILT_IS_PIMORONI": False,
"PANTILT_HOME": (0, -10),
"PANTILT_SPEED": 0.5,
"PANTILT_SEQ_ON": False,
"PANTILT_SEQ_TIMER_SEC": 600,
"PANTILT_SEQ_IMAGES_DIR": "media/pantilt_seq",
"PANTILT_SEQ_IMAGE_PREFIX": "seq-",
"PANTILT_SEQ_DAYONLY_ON": True,
"PANTILT_SEQ_RECENT_DIR": "media/recent/pt-seq",
"PANTILT_SEQ_NUM_MAX": 200,
"PANTILT_SEQ_NUM_ON": True,
"PANTILT_SEQ_NUM_START": 1000,
"PANTILT_SEQ_NUM_RECYCLE_ON": True,
"PANTILT_SEQ_NUM_MAX": 200,
"PANTILT_SEQ_STOPS": [
(90, 10),
(45, 10),
(0, 10),
(-45, 10),
(-90, 10),
],
"PANO_ON": False,
"PANO_DAYONLY_ON": True,
"PANO_TIMER_SEC": 160,
"PANO_IMAGE_PREFIX": "pano-",
"PANO_NUM_START": 1000,
"PANO_NUM_MAX": 10,
"PANO_NUM_RECYCLE": True,
"PANO_PROG_PATH": "./image-stitching",
"PANO_IMAGES_DIR": "./media/pano/images",
"PANO_DIR": "./media/pano/panos",
"PANO_CAM_STOPS": [
(36, 10),
(0, 10),
(-36, 10),
],
"SPACE_TIMER_HOURS": 0,
"SPACE_TARGET_MB": 500,
"SPACE_MEDIA_DIR": "/home/pi/pi-timolo/media",
"SPACE_TARGET_EXT": "jpg",
"web_server_port": 8080,
"web_server_root": "media",
"web_page_title": "PI-TIMOLO Media",
"web_page_refresh_on": True,
"web_page_refresh_sec": "900",
"web_page_blank": False,
"web_image_height": "768",
"web_iframe_width_usage": "70%",
"web_iframe_width": "100%",
"web_iframe_height": "100%",
"web_max_list_entries": 0,
"web_list_height": "768",
"web_list_by_datetime": True,
"web_list_sort_descending": True,
}
# Check for config.py variable file to import and error out if not found.
CONFIG_FILE_PATH = os.path.join(BASE_DIR, "config.py")
if os.path.isfile(CONFIG_FILE_PATH):
try:
from config import CONFIG_TITLE
except ImportError:
print("\n --- WARNING ---\n")
print("pi-timolo.py ver 12.0 or greater requires an updated config.py")
print("copy new config.py per commands below.\n")
print(" cp config.py config.py.bak")
print(" cp config.py.new config.py\n")
print("config.py.bak will contain your previous settings")
print("The NEW config.py has renamed variable names. If required")
print("you will need to review previous settings and change")
print("the appropriate NEW variable names using nano.\n")
print(
"Note: ver 12.0 has added a pantilthat panoramic image stitching feature\n"
)
print(" Press Ctrl-c to Exit and update config.py")
print(" or")
text = raw_input(" Press Enter and Default Settings will be used.")
try:
# Read Configuration variables from config.py file
from config import *
except ImportError:
print("WARN : Problem Importing Variables from %s" % CONFIG_FILE_PATH)
WARN_ON = True
else:
print(
"WARN : %s File Not Found. Cannot Import Configuration Variables."
% CONFIG_FILE_PATH
)
print(" Run Console Command Below to Download File from GitHub Repo")
print(
" wget -O config.py https://raw.github.com/pageauc/pi-timolo/master/source/config.py"
)
print(" or cp config.py.new config.py")
print(" Will now use default_settings dictionary variable values.")
WARN_ON = True
"""
Check if variables were imported from config.py. If not create variable using
the values in the default_settings dictionary above.
"""
for key, val in default_settings.items():
try:
exec(key)
except NameError:
print("WARN : config.py Variable Not Found. Setting " + key + " = " + str(val))
exec(key + "=val")
WARN_ON = True
if PANTILT_ON:
pan_x, tilt_y = PANTILT_HOME
if PANTILT_IS_PIMORONI:
try:
import pantilthat
except ImportError:
print("ERROR : Import Pimoroni PanTiltHat Python Library per")
print(" sudo apt install pantilthat")
print(" Enable I2C support using sudo raspi-config")
sys.exit()
try:
pantilthat.pan(pan_x)
except IOError:
print("ERROR: pimoroni pantilthat hardware problem")
print(" if pimoroni pantilt installed check that I2C enabled in raspi-config.")
print("if waveshare or conpatible pantilt installed perform the following")
print("nano edit config.py per below")
print(" nano config.py")
print("Change value of variable per below. ctrl-x y to save and exit")
print(" PANTILT_IS_PIMORONI = False")
sys.exit()
pantilt_is = "Pimoroni"
else:
try:
# import pantilthat
from waveshare.pantilthat import PanTilt
except ImportError:
print("ERROR : Install Waveshare PanTiltHat Python Library per")
print(
" curl -L https://raw.githubusercontent.com/pageauc/waveshare.pantilthat/main/install.sh | bash"
)
sys.exit()
try:
pantilthat = PanTilt()
pantilthat.pan(pan_x)
except IOError:
print("ERROR: pantilthat hardware problem")
print("nano edit config.py per below")
print(" nano config.py")
print("Change value of variable per below. ctrl-x y to save and exit")
print(" PANTILT_IS_PIMORONI = True")
sys.exit()
pantilt_is = "Waveshare"
# Setup Logging now that variables are imported from config.py/plugin
if LOG_TO_FILE_ON:
logging.basicConfig(
level=logging.DEBUG,
format="%(asctime)s %(levelname)-8s %(funcName)-10s %(message)s",
datefmt="%Y-%m-%d %H:%M:%S",
filename=LOG_FILE_PATH,
filemode="w",
)
elif VERBOSE_ON:
logging.basicConfig(
level=logging.DEBUG,
format="%(asctime)s %(levelname)-8s %(funcName)-10s %(message)s",
datefmt="%Y-%m-%d %H:%M:%S",
)
else:
logging.basicConfig(
level=logging.CRITICAL,
format="%(asctime)s %(levelname)-8s %(funcName)-10s %(message)s",
datefmt="%Y-%m-%d %H:%M:%S",
)
# Check for user_motion_code.py file to import and error out if not found.
userMotionFilePath = os.path.join(BASE_DIR, "user_motion_code.py")
if not os.path.isfile(userMotionFilePath):
print(
"WARN : %s File Not Found. Cannot Import user_motion_code functions."
% userMotionFilePath
)
WARN_ON = True
else:
# Read Configuration variables from config.py file
try:
motionCode = True
import user_motion_code
except ImportError:
print("WARN : Failed Import of File user_motion_code.py Investigate Problem")
motionCode = False
WARN_ON = True
# Give some time to read any warnings
if WARN_ON and VERBOSE_ON:
print("")
print("Please Review Warnings Wait 10 sec ...")
time.sleep(10)
print("Loading Wait ....")
try:
import cv2
except ImportError:
if sys.version_info > (2, 9):
logging.error("Failed to import cv2 opencv for python3")
logging.error("Try installing opencv for python3")
logging.error("See https://github.com/pageauc/opencv3-setup")
else:
logging.error("Failed to import cv2 for python2")
logging.error("Try reinstalling per command")
logging.error("sudo apt-get install python-opencv")
logging.error("Exiting %s Due to Error", PROG_NAME)
sys.exit(1)
try:
from picamera import PiCamera
except ImportError:
logging.error("Problem importing picamera module")
logging.error("Try command below to import module")
if sys.version_info > (2, 9):
logging.error("sudo apt-get install python3-picamera")
else:
logging.error("sudo apt-get install python-picamera")
logging.error("Exiting %s Due to Error", PROG_NAME)
sys.exit(1)
from picamera.array import PiRGBArray
import picamera.array
# Check that pi camera module is installed and enabled
logging.info("Checking Pi Camera Module using command - vcgencmd get_camera")
camResult = subprocess.check_output("vcgencmd get_camera", shell=True)
camResult = camResult.decode("utf-8")
camResult = camResult.replace("\n", "")
params = camResult.split()
for x in range(0,2):
if params[x].find("0") >= 0:
logging.error("Detected picamera issue per %s", params[x])
logging.error(" if supported=0 Enable Camera per command sudo raspi-config")
logging.error(" Bullseye and later enable Legacy picamera support.")
logging.error(" if detected=0 Check Pi Camera Module and cable is Installed Correctly.")
logging.error("%s %s Exiting Due to Error", PROG_NAME, PROG_VER)
sys.exit(1)
else:
logging.info("Success Pi Camera %s", camResult)
# use raspistill to check maximum image resolution of attached camera module
logging.info("Checking Pi Camera Module Version Wait ...")
import picamera
with picamera.PiCamera() as camera:
CAM_MAX_RESOLUTION = camera.MAX_RESOLUTION
logging.info("PiCamera Max resolution is %s", CAM_MAX_RESOLUTION)
CAM_MAX_WIDTH, CAM_MAX_HEIGHT = CAM_MAX_RESOLUTION.width, CAM_MAX_RESOLUTION.height
if CAM_MAX_WIDTH == "3280":
picameraVer = "2"
else:
picameraVer = "1"
logging.info("PiCamera Module Hardware is Ver %s", picameraVer)
if PLUGIN_ON: # Check and verify plugin and load variable overlay
pluginDir = os.path.join(BASE_DIR, "plugins")
# Check if there is a .py at the end of PLUGIN_NAME variable
if PLUGIN_NAME.endswith(".py"):
PLUGIN_NAME = PLUGIN_NAME[:-3] # Remove .py extensiion
pluginPath = os.path.join(pluginDir, PLUGIN_NAME + ".py")
logging.info("pluginEnabled - loading PLUGIN_NAME %s", pluginPath)
if not os.path.isdir(pluginDir):
logging.error("plugin Directory Not Found at %s", pluginDir)
logging.error("Rerun github curl install script to install plugins")
logging.error(
"https://github.com/pageauc/pi-timolo/wiki/"
"How-to-Install-or-Upgrade#quick-install"
)
logging.error("Exiting %s Due to Error", PROG_NAME)
sys.exit(1)
elif not os.path.isfile(pluginPath):
logging.error("File Not Found PLUGIN_NAME %s", pluginPath)
logging.error("Check Spelling of PLUGIN_NAME Value in %s", CONFIG_FILE_PATH)
logging.error("------- Valid Names -------")
validPlugin = glob.glob(pluginDir + "/*py")
validPlugin.sort()
for entry in validPlugin:
pluginFile = os.path.basename(entry)
plugin = pluginFile.rsplit(".", 1)[0]
if not ((plugin == "__init__") or (plugin == "current")):
logging.error(" %s", plugin)
logging.error("------- End of List -------")
logging.error("Note: PLUGIN_NAME Should Not have .py Ending.")
logging.error("or Rerun github curl install command. See github wiki")
logging.error(
"https://github.com/pageauc/pi-timolo/wiki/"
"How-to-Install-or-Upgrade#quick-install"
)
logging.error("Exiting %s Due to Error", PROG_NAME)
sys.exit(1)
else:
pluginCurrent = os.path.join(pluginDir, "current.py")
try: # Copy image file to recent folder
logging.info("Copy %s to %s", pluginPath, pluginCurrent)
shutil.copy(pluginPath, pluginCurrent)
except OSError as err:
logging.error(
"Copy Failed from %s to %s - %s", pluginPath, pluginCurrent, err
)
logging.error("Check permissions, disk space, Etc.")
logging.error("Exiting %s Due to Error", PROG_NAME)
sys.exit(1)
logging.info("Import Plugin %s", pluginPath)
sys.path.insert(0, pluginDir) # add plugin directory to program PATH
from plugins.current import *
try:
if os.path.isfile(pluginCurrent):
os.remove(pluginCurrent)
pluginCurrentpyc = os.path.join(pluginDir, "current.pyc")
if os.path.isfile(pluginCurrentpyc):
os.remove(pluginCurrentpyc)
except OSError as err:
logging.warning("Failed Removal of %s - %s", pluginCurrentpyc, err)
time.sleep(5)
else:
logging.info("No Plugin Enabled per PLUGIN_ON=%s", PLUGIN_ON)
# Turn on VERBOSE_ON when DEBUG_ON mode is enabled
if DEBUG_ON:
VERBOSE_ON = True
# Make sure image format extention starts with a dot
if not IMAGE_FORMAT.startswith(".", 0, 1):
IMAGE_FORMAT = "." + IMAGE_FORMAT
# ==================================
# System Variables
# Should Not need to be customized
# ==================================
SECONDS2MICRO = 1000000 # Used to convert from seconds to microseconds
NIGHT_MAX_SHUTTER = int(NIGHT_MAX_SHUT_SEC * SECONDS2MICRO)
# default=5 seconds IMPORTANT- 6 seconds works sometimes
# but occasionally locks RPI and HARD reboot required to clear
darkAdjust = int((SECONDS2MICRO / 5.0) * NIGHT_DARK_ADJUST)
daymode = False # default should always be False.
MOTION_PATH = os.path.join(BASE_DIR, MOTION_DIR) # Store Motion images
# motion dat file to save currentCount
# Setup filepath's for storing image numbering data
DATA_DIR = "./data"
NUM_PATH_MOTION = os.path.join(DATA_DIR, MOTION_PREFIX + BASE_FILENAME + ".dat")
NUM_PATH_TIMELAPSE = os.path.join(DATA_DIR, TIMELAPSE_PREFIX + BASE_FILENAME + ".dat")
NUM_PATH_PANO = os.path.join(DATA_DIR, PANO_IMAGE_PREFIX + BASE_FILENAME + ".dat")
NUM_PATH_PANTILT_SEQ = os.path.join(
DATA_DIR, PANTILT_SEQ_IMAGE_PREFIX + BASE_FILENAME + ".dat"
)
TIMELAPSE_PATH = os.path.join(BASE_DIR, TIMELAPSE_DIR) # Store Time Lapse images
# timelapse dat file to save currentCount
LOCK_FILEPATH = os.path.join(BASE_DIR, BASE_FILENAME + ".sync")
# Colors for drawing lines
cvWhite = (255, 255, 255)
cvBlack = (0, 0, 0)
cvBlue = (255, 0, 0)
cvGreen = (0, 255, 0)
cvRed = (0, 0, 255)
LINE_THICKNESS = 1 # Thickness of opencv drawing lines
LINE_COLOR = cvWhite # color of lines to highlight motion stream area
# Round image resolution to avoid picamera errors
if picameraVer == "2":
imageWidthMax = 3280
imageHeightMax = 2464
else:
imageWidthMax = 2592
imageHeightMax = 1944
logging.info(
"picamera ver %s Max Resolution is %i x %i",
picameraVer,
imageWidthMax,
imageHeightMax,
)
# Round image resolution to avoid picamera errors
image_width = (IMAGE_WIDTH + 31) // 32 * 32
if image_width > imageWidthMax:
image_width = imageWidthMax
image_height = (IMAGE_HEIGHT + 15) // 16 * 16
if image_height > imageHeightMax:
image_height = imageHeightMax
stream_width = (STREAM_WIDTH + 31) // 32 * 32
if stream_width > imageWidthMax:
stream_width = imageWidthMax
stream_height = (STREAM_HEIGHT + 15) // 16 * 16
if stream_height > imageHeightMax:
stream_height = imageHeightMax
stream_framerate = STREAM_FPS # camera framerate
# If camera being used inside where there is no twilight
# Reduce night threshold settings to reduce overexposures.
if not NIGHT_TWILIGHT_MODE_ON:
NIGHT_TWILIGHT_THRESHOLD = 20
NIGHT_DARK_THRESHOLD = 10
NIGHT_BLACK_THRESHOLD = 4
# increase size of MOTION_TRACK_QUICK_PIC_ON image
bigImage = MOTION_TRACK_QUICK_PIC_BIGGER
bigImageWidth = int(stream_width * bigImage)
bigImageHeight = int(stream_height * bigImage)
TRACK_TRIG_LEN = MOTION_TRACK_TRIG_LEN # Pixels moved to trigger motion photo
# Don't track progress until this Len reached.
TRACK_TRIG_LEN_MIN = int(MOTION_TRACK_TRIG_LEN / 6)
# Set max overshoot triglen allowed half cam height
TRACK_TRIG_LEN_MAX = int(stream_height / 2)
# Timeout seconds Stops motion tracking when no activity
TRACK_TIMEOUT = MOTION_TRACK_TIMEOUT_SEC
# OpenCV Contour sq px area must be greater than this.
MIN_AREA = MOTION_TRACK_MIN_AREA
BLUR_SIZE = 10 # OpenCV setting for Gaussian difference image blur
THRESHOLD_SENSITIVITY = 20 # OpenCV setting for difference image threshold
# Fix range Errors Use zero to set default quality to 85
if IMAGE_JPG_QUAL < 1:
IMAGE_JPG_QUAL = 85
elif IMAGE_JPG_QUAL > 100:
IMAGE_JPG_QUAL = 100
# ------------------------------------------------------------------------------
class PiVideoStream:
"""
Create a picamera in memory video stream and
return a frame when update called
"""
def __init__(
self,
resolution=(stream_width, stream_height),
framerate=stream_framerate,
rotation=0,
hflip=False,
vflip=False,
):
# initialize the camera and stream
try:
self.camera = PiCamera()
except:
logging.error("PiCamera Already in Use by Another Process")
logging.error("Exiting %s Due to Error", PROG_NAME)
exit(1)
self.camera.resolution = resolution
self.camera.framerate = framerate
self.camera.hflip = hflip
self.camera.vflip = vflip
self.camera.rotation = rotation
self.rawCapture = PiRGBArray(self.camera, size=resolution)
self.stream = self.camera.capture_continuous(
self.rawCapture, format="bgr", use_video_port=True
)
# initialize the frame and the variable used to indicate
# if the thread should be stopped
self.thread = None # Initialize thread
self.frame = None
self.stopped = False
def start(self):
"""start the thread to read frames from the video stream"""
self.thread = Thread(target=self.update, args=())
self.thread.daemon = True
self.thread.start()
return self
def update(self):
"""keep looping infinitely until the thread is stopped"""
for f in self.stream:
# grab the frame from the stream and clear the stream in
# preparation for the next frame
self.frame = f.array
self.rawCapture.truncate(0)
# if the thread indicator variable is set, stop the thread
# and release camera resources
if self.stopped:
self.stream.close()
self.rawCapture.close()
self.camera.close()
return
def read(self):
"""return the frame most recently read"""
return self.frame
def stop(self):
"""indicate that the thread should be stopped"""
self.stopped = True
if self.thread is not None:
self.thread.join()
# ------------------------------------------------------------------------------
def shut2sec(shutspeed):
"""Convert camera shutter speed setting to string"""
shutspeedSec = shutspeed / float(SECONDS2MICRO)
shutstring = str("%.4f") % (shutspeedSec)
return shutstring
# ------------------------------------------------------------------------------
def showTime():
"""Show current date time in text format"""
rightNow = datetime.datetime.now()
currentTime = "%04d-%02d-%02d %02d:%02d:%02d" % (
rightNow.year,
rightNow.month,
rightNow.day,
rightNow.hour,
rightNow.minute,
rightNow.second,
)
return currentTime
# ------------------------------------------------------------------------------
def showDots(dotcnt):
"""
If motionShowDots=True then display a progress
dot for each cycle. If MOTION_TRACK_ON then this would
normally be too fast and should be turned off
"""
if MOTION_DOTS_ON:
if MOTION_TRACK_ON and VERBOSE_ON:
dotcnt += 1
if dotcnt > MOTION_DOTS_MAX + 2:
print("")
dotcnt = 0
elif dotcnt > MOTION_DOTS_MAX:
print("")
stime = showTime() + " ."
sys.stdout.write(stime)
sys.stdout.flush()
dotcnt = 0
else:
sys.stdout.write(".")
sys.stdout.flush()
return dotcnt
# ------------------------------------------------------------------------------
def checkConfig():
"""
Check if both User disabled everything
in config.py. At least one option needs to be enabled
"""
if not MOTION_TRACK_ON and not TIMELAPSE_ON and not PANTILT_SEQ_ON and not PANO_ON and not VIDEO_REPEAT_ON:
errorText = (
"You need to have Motion, Timelapse, PanTilt Seq, Pano or Video Repeat turned ON\n"
"MOTION_TRACK_ON=%s TIMELAPSE_ON=%s PANTILT_SEQ_ON=%s PANO_ON=%s VIDEO_REPEAT_ON=%s"
% (MOTION_TRACK_ON, TIMELAPSE_ON, PANTILT_SEQ_ON, PANO_ON, VIDEO_REPEAT_ON)
)
if VERBOSE_ON:
logging.error(errorText)
else:
sys.stdout.write(errorText)
sys.exit(1)
# ------------------------------------------------------------------------------
def displayInfo(motioncount, timelapsecount):
"""Display variable settings with plugin overlays if required"""
if VERBOSE_ON:
print(
"----------------------------------- Settings "
"-----------------------------------"
)
print(
"Config File .. CONFIG_FILENAME=%s CONFIG_TITLE=%s"
% (CONFIG_FILENAME, CONFIG_TITLE)
)
if PLUGIN_ON:
print(
" Plugin .. PLUGIN_ON=%s PLUGIN_NAME=%s"
" (Overlays %s Variable Settings)"
% (PLUGIN_ON, PLUGIN_NAME, CONFIG_FILENAME)
)
else:
print(" Plugin .. PLUGIN_ON=%s" % PLUGIN_ON)
print("")
print(
"Image Info ... Size=%ix%i ext=%s Prefix=%s"
" VFlip=%s HFlip=%s Rotation=%i"
% (
image_width,
image_height,
IMAGE_FORMAT,
IMAGE_NAME_PREFIX,
IMAGE_VFLIP,
IMAGE_HFLIP,
IMAGE_ROTATION,
)
)
print(
" IMAGE_GRAYSCALE=%s Preview=%s"
% (IMAGE_GRAYSCALE, IMAGE_PREVIEW)
)
if IMAGE_FORMAT == ".jpg" or IMAGE_FORMAT == ".jpeg":
print(
" JpegQuality=%i where 1=Low 100=High" % (IMAGE_JPG_QUAL)
)
print(
" Low Light.. NIGHT_TWILIGHT_MODE_ON=%s NIGHT_TWILIGHT_THRESHOLD=%i"
" NIGHT_DARK_THRESHOLD=%i NIGHT_BLACK_THRESHOLD=%i"
% (
NIGHT_TWILIGHT_MODE_ON,
NIGHT_TWILIGHT_THRESHOLD,
NIGHT_DARK_THRESHOLD,
NIGHT_BLACK_THRESHOLD,
)
)
print(
" NIGHT_MAX_SHUT_SEC=%.2f NIGHT_MAX_ISO=%i"
" NIGHT_DARK_ADJUST=%.2f NIGHT_SLEEP_SEC=%i"
% (NIGHT_MAX_SHUT_SEC, NIGHT_MAX_ISO, NIGHT_DARK_ADJUST, NIGHT_SLEEP_SEC)
)
print(
" No Shots .. IMAGE_NO_NIGHT_SHOTS=%s IMAGE_NO_DAY_SHOTS=%s"
% (IMAGE_NO_NIGHT_SHOTS, IMAGE_NO_DAY_SHOTS)
)
if SHOW_DATE_ON_IMAGE:
print(
" Img Text .. On=%s Bottom=%s (False=Top) WhiteText=%s (False=Black)"
% (SHOW_DATE_ON_IMAGE, SHOW_TEXT_BOTTOM, SHOW_TEXT_WHITE)
)
print(
" SHOW_TEXT_WHITE_NIGHT=%s SHOW_TEXT_FONT_SIZE=%i px height"
% (SHOW_TEXT_WHITE_NIGHT, SHOW_TEXT_FONT_SIZE)
)
else:
print(
" No Text .. SHOW_DATE_ON_IMAGE=%s Text on Image is Disabled"
% (SHOW_DATE_ON_IMAGE)
)
print("")
if MOTION_TRACK_ON:
print(
"Motion Track.. On=%s Prefix=%s MinArea=%i sqpx"
" TrigLen=%i-%i px TimeOut=%i sec"
% (
MOTION_TRACK_ON,
MOTION_PREFIX,
MOTION_TRACK_MIN_AREA,
MOTION_TRACK_TRIG_LEN,
TRACK_TRIG_LEN_MAX,
MOTION_TRACK_TIMEOUT_SEC,
)
)
print(
" MOTION_TRACK_INFO_ON=%s MOTION_DOTS_ON=%s IMAGE_SHOW_STREAM=%s"
% (MOTION_TRACK_INFO_ON, MOTION_DOTS_ON, IMAGE_SHOW_STREAM)
)
print(
" Stream .... size=%ix%i framerate=%i fps"
" STREAM_STOP_SEC=%.2f QuickPic=%s"
% (
stream_width,
stream_height,
STREAM_FPS,
STREAM_STOP_SEC,
MOTION_TRACK_QUICK_PIC_ON,
)
)
print(
" Img Path .. MOTION_PATH=%s MOTION_CAM_SLEEP=%.2f sec"
% (MOTION_PATH, MOTION_CAM_SLEEP)
)
print(
" Sched ..... MOTION_START_AT %s blank=Off or"
" Set Valid Date and/or Time to Start Sequence" % MOTION_START_AT
)
print(
" Force ..... MOTION_FORCE_SEC=%i min (If No Motion)"
% (MOTION_FORCE_SEC / 60)
)
print(
" Lockfile .. On=%s Path=%s NOTE: For Motion Images Only."
% (CREATE_LOCKFILE, LOCK_FILEPATH)
)
if MOTION_NUM_ON:
print(
" Num Seq ... MOTION_NUM_ON=%s numRecycle=%s"
" numStart=%i numMax=%i current=%s"
% (
MOTION_NUM_ON,
MOTION_NUM_RECYCLE_ON,
MOTION_NUM_START,
MOTION_NUM_MAX,
motioncount,
)
)
print(" Num Path .. NUM_PATH_MOTION=%s " % (NUM_PATH_MOTION))
else:
print(
" Date-Time.. MOTION_NUM_ON=%s Image Numbering is Disabled"
% (MOTION_NUM_ON)
)
if MOTION_TRACK_MINI_TL_ON:
print(
" Quick TL .. MOTION_TRACK_MINI_TL_ON=%s MOTION_TRACK_MINI_TL_SEQ_SEC=%i"
" sec MOTION_TRACK_MINI_TL_TIMER_SEC=%i sec (0=fastest)"
% (
MOTION_TRACK_MINI_TL_ON,
MOTION_TRACK_MINI_TL_SEQ_SEC,
MOTION_TRACK_MINI_TL_TIMER_SEC,
)
)
else:
print(
" Quick TL .. MOTION_TRACK_MINI_TL_ON=%s Quick Time Lapse Disabled"
% MOTION_TRACK_MINI_TL_ON
)
if MOTION_VIDEO_ON:
print(
" Video ..... MOTION_VIDEO_ON=%s MOTION_VIDEO_TIMER_SEC=%i"
" sec MOTION_VIDEO_FPS=%i (superseded by QuickTL)"
% (MOTION_VIDEO_ON, MOTION_VIDEO_TIMER_SEC, MOTION_VIDEO_FPS)
)
else:
print(
" Video ..... MOTION_VIDEO_ON=%s Motion Video is Disabled"
% MOTION_VIDEO_ON
)
print(
" Sub-Dir ... MOTION_SUBDIR_MAX_HOURS=%i (0-off)"
" MOTION_SUBDIR_MAX_FILES=%i (0=off)"
% (MOTION_SUBDIR_MAX_HOURS, MOTION_SUBDIR_MAX_FILES)
)
print(
" Recent .... MOTION_RECENT_MAX=%i (0=off) MOTION_RECENT_DIR=%s"
% (MOTION_RECENT_MAX, MOTION_RECENT_DIR)
)
else:
print(
"Motion ....... MOTION_TRACK_ON=%s Motion Tracking is Disabled)"
% MOTION_TRACK_ON
)
print("")
if TIMELAPSE_ON:
print(
"Time Lapse ... On=%s Prefix=%s Timer=%i sec"
" TIMELAPSE_EXIT_SEC=%i (0=Continuous)"
% (
TIMELAPSE_ON,
TIMELAPSE_PREFIX,
TIMELAPSE_TIMER_SEC,
TIMELAPSE_EXIT_SEC,
)
)
print(" TIMELAPSE_MAX_FILES=%i" % (TIMELAPSE_MAX_FILES))
print(
" Img Path .. TIMELAPSE_PATH=%s TIMELAPSE_CAM_SLEEP_SEC=%.2f sec"
% (TIMELAPSE_PATH, TIMELAPSE_CAM_SLEEP_SEC)
)
print(
" Sched ..... TIMELAPSE_START_AT %s blank=Off or"
" Set Valid Date and/or Time to Start Sequence" % TIMELAPSE_START_AT
)
if TIMELAPSE_NUM_ON:
print(
" Num Seq ... On=%s numRecycle=%s numStart=%i numMax=%i current=%s"
% (
TIMELAPSE_NUM_ON,
TIMELAPSE_NUM_RECYCLE_ON,
TIMELAPSE_NUM_START,
TIMELAPSE_NUM_MAX,
timelapsecount,
)
)
print(" Num Path .. numPath=%s" % (NUM_PATH_TIMELAPSE))
else:
print(
" Date-Time.. MOTION_NUM_ON=%s Numbering Disabled"
% TIMELAPSE_NUM_ON
)
print(
" Sub-Dir ... TIMELAPSE_SUBDIR_MAX_HOURS=%i (0=off)"
" TIMELAPSE_SUBDIR_MAX_FILES=%i (0=off)"
% (TIMELAPSE_SUBDIR_MAX_HOURS, TIMELAPSE_SUBDIR_MAX_FILES)
)
print(
" Recent .... TIMELAPSE_RECENT_MAX=%i (0=off) TIMELAPSE_RECENT_DIR=%s"
% (TIMELAPSE_RECENT_MAX, TIMELAPSE_RECENT_DIR)
)
else:
print(
"Time Lapse ... TIMELAPSE_ON=%s Timelapse is Disabled" % TIMELAPSE_ON
)
print("")
if SPACE_TIMER_HOURS > 0: # Check if disk mgmnt is enabled
print(
"Disk Space .. Enabled - Manage Target Free Disk Space."
" Delete Oldest %s Files if Required" % (SPACE_TARGET_EXT)
)
print(
" Check Every SPACE_TIMER_HOURS=%i (0=off)"
" Target SPACE_TARGET_MB=%i (min=100 MB) SPACE_TARGET_EXT=%s"
% (SPACE_TIMER_HOURS, SPACE_TARGET_MB, SPACE_TARGET_EXT)
)
print(
" Delete Oldest SPACE_TARGET_EXT=%s SPACE_MEDIA_DIR=%s"
% (SPACE_TARGET_EXT, SPACE_MEDIA_DIR)
)
else:
print(
"Disk Space .. SPACE_TIMER_HOURS=%i "
"(Disabled) - Manage Target Free Disk Space. Delete Oldest %s Files"
% (SPACE_TIMER_HOURS, SPACE_TARGET_EXT)
)
print(
" .. Check Every SPACE_TIMER_HOURS=%i (0=Off)"
" Target SPACE_TARGET_MB=%i (min=100 MB)"
% (SPACE_TIMER_HOURS, SPACE_TARGET_MB)
)
print("")
print("Logging ...... VERBOSE_ON=%s (True=Enabled False=Disabled)" % VERBOSE_ON)
print(
" Log Path .. LOG_TO_FILE_ON=%s LOG_FILE_PATH=%s"
% (LOG_TO_FILE_ON, LOG_FILE_PATH)
)
print(