-
Notifications
You must be signed in to change notification settings - Fork 10
/
cam_config.py
executable file
·2059 lines (1530 loc) · 70.5 KB
/
cam_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
#!/usr/bin/env python3
# coding=utf-8
# ======================= HIKVISION CAM SETUP ======================
# 2023-10-04
# MAIN stream: /h264/ch1/main/av_stream
# SUB stream: /mjpeg/ch1/sub/av_stream
# pip3 install --user pycryptodomex
# pip3 install --user requests
# OR
# /usr/bin/python3 -m pip install --user pycryptodomex
# /usr/bin/python3 -m pip install --user requests
device_name_prefix = 'PP'
time_zone_gmt_offset = '+5:00:00'
new_ntp = '10.10.10.10'
admin_user_name = 'admin'
admin_old_password = 'qwer1234'
# admin_new_password = 'qwer1234'
admin_new_password = admin_old_password
# additional users
# [username, password, permission]
# permission is
# 'n' - no video, no records
# 'v' - video, no records
# 'r' - video + records
# 'a' - all admin's permissions
additional_users = [
['monitoring', 'qwer1234', 'n'],
['video', 'qwer1234', 'v'],
['record', 'qwer1234', 'r'],
['operator', 'qwer1234', 'a'],
]
# 1280,1920,2560,3072,3840,'max'
# 720, 1080,1440,1728,2160,'max'
# 1,2,4,6,8,10,12,15,16,18,20,22,25
# 'h265', 'h264', h265 fallbacks to h264 if not supported
main_stream_width = 'max'
main_stream_height = 'max'
main_stream_framerate = 15
main_stream_codec = 'h265'
main_stream_audio = True
# 320,640,640,704,'max'
# 240,360,480,576,'max'
# 1,2,4,6,8,10,12,15,16,18,20,22,25
# 'h265', 'h264', 'mjpeg', h265 fallbacks to h264 if not supported
sub_stream_width = 640
sub_stream_height = 480
sub_stream_framerate = 10
sub_stream_codec = 'mjpeg'
sub_stream_audio = False
wdr_on = False
wdr_level = 51
primary_dns = '5.5.5.5'
secondary_dns = '8.8.8.8'
sender_email = 'info@example.com'
sender_name_prefix = 'ip-cam-'
smtp_server = 'smtp.example.com'
notification_email1 = 'admin1@example.com'
notification_email2 = 'admin2@example.com'
notification_email3 = ''
reformat_sd_if_it_is_ok = True
photo_capture_interval_minutes = 5
video_ratio_percents = 99
# not less than 15s
DELAY_AFTER_FORMATTING_SECONDS = 20
# =============== DST ===============
# True False
enable_dst = False
# "00:30", "01:00", "01:30", "02:00"
dst_offset = "01:00"
# Start DST period
# 1..12
start_dst_month = 3
# 0 - sun, 1 - mon, ..., 6 - sat
start_dst_day_of_week = 3
# 1,2,3,4 - first, second, third or fourth, 5 - last
start_dst_day_order_number = 4
# 0..23
start_dst_hour = 0
# End DST period
end_dst_month = 9
end_dst_day_of_week = 3
end_dst_day_order_number = 4
end_dst_hour = 0
# ==================================
# ============================= MAIN WORK ===============================
def set_cam_options(auth_type, current_cam_ip, current_password, new_cam_ip):
# UNCOMMENT NEEDED STEPS
set_additional_users(auth_type, current_cam_ip, current_password)
set_ntp(auth_type, current_cam_ip, current_password)
set_time(auth_type, current_cam_ip, current_password)
set_osd(auth_type, current_cam_ip, current_password)
set_off_ip_ban_option(auth_type, current_cam_ip, current_password)
set_video_streams(auth_type, current_cam_ip, current_password)
set_cloud_parameters(auth_type, current_cam_ip, current_password)
disable_unneeded_event_triggers(auth_type, current_cam_ip, current_password)
set_wdr(auth_type, current_cam_ip, current_password)
# =========== for offices - motion detection and so on ===============
set_integration_protocol_enabled(auth_type, current_cam_ip, current_password)
set_basic_auth_method(auth_type, current_cam_ip, current_password)
set_device_name(auth_type, current_cam_ip, current_password, new_cam_ip)
set_email_notification_addresses(auth_type, current_cam_ip, current_password, new_cam_ip)
set_video_photo_ratio(auth_type, current_cam_ip, current_password)
set_motion_detector_parameters(auth_type, current_cam_ip, current_password)
format_storage(auth_type, current_cam_ip, current_password)
set_email_event_triggers(auth_type, current_cam_ip, current_password)
set_recording_by_motion_detector_trigger(auth_type, current_cam_ip, current_password)
set_recording_schedule(auth_type, current_cam_ip, current_password)
set_photo_capturing_parameters(auth_type, current_cam_ip, current_password)
# ====================================================================
print_user_list(auth_type, current_cam_ip, current_password)
set_ip_and_dns(auth_type, current_cam_ip, new_cam_ip, current_password)
set_admin_password(auth_type, current_cam_ip, current_password, admin_new_password)
reboot_cam(auth_type, current_cam_ip)
pass
# ==================================================================
import re
import requests
import base64
import time
import sys
import ipaddress
from sys import stdout
from xml.etree import ElementTree
from requests.auth import HTTPDigestAuth
from requests.auth import HTTPBasicAuth
from Cryptodome.Cipher import AES
from Cryptodome.PublicKey import RSA
from Cryptodome.Cipher import PKCS1_v1_5
from Cryptodome.Cipher.AES import MODE_ECB
# ==================================================================
VIDEO_TRACK_ID = '101'
PHOTO_TRACK_ID = '103'
# ============================= URLS ===============================
password_url = '/ISAPI/Security/users/1'
time_url = '/ISAPI/System/time'
ntp_url = '/ISAPI/System/time/ntpServers'
osd_url = '/ISAPI/System/Video/inputs/channels/1/overlays'
video_url = '/ISAPI/Streaming/channels'
video_capabilities_url = '/ISAPI/Streaming/channels/{}/capabilities'
wdr_url = '/ISAPI/Image/channels/1/WDR'
image_capabilities_url = '/ISAPI/Image/channels/1/capabilities'
ip_url = '/ISAPI/System/Network/interfaces/1/ipAddress'
reboot_url = '/ISAPI/System/reboot'
ip_ban_option_url = '/ISAPI/Security/illegalLoginLock'
network_capabilities_url = '/ISAPI/System/Network/capabilities'
cloud_url = '/ISAPI/System/Network/EZVIZ'
integration_protocol_url = '/ISAPI/System/Network/Integrate'
activation_status_url = '/SDK/activateStatus'
public_key_url = '/ISAPI/Security/challenge'
activation_url = '/ISAPI/System/activate'
users_url = '/ISAPI/Security/users'
permissons_url = '/ISAPI/Security/UserPermission'
device_info_url = '/ISAPI/System/deviceInfo'
email_addresses_url = '/ISAPI/System/Network/mailing/1'
event_diskfull_trigger_url = '/ISAPI/Event/triggers/diskfull/notifications'
event_diskerror_trigger_url = '/ISAPI/Event/triggers/diskerror/notifications'
event_motion_detector_trigger_url = '/ISAPI/Event/triggers/VMD-1/notifications'
event_trigger_base_url = '/ISAPI/Event/triggers/'
motion_detector_parameters_url = '/ISAPI/System/Video/inputs/channels/1/motionDetection'
recording_schedule_url = '/ISAPI/ContentMgmt/record/tracks/'
recording_video_schedule_url = recording_schedule_url + VIDEO_TRACK_ID
recording_photo_schedule_url = recording_schedule_url + PHOTO_TRACK_ID
shapshot_channel_url = '/ISAPI/Snapshot/channels/1'
video_photo_ratio_url = '/ISAPI/ContentMgmt/Storage/quota/1'
storages_status_url = '/ISAPI/ContentMgmt/Storage/hdd'
storage_format_url = '/ISAPI/ContentMgmt/Storage/hdd/1/format'
storage_format_percents_url = '/ISAPI/ContentMgmt/Storage/hdd/1/formatStatus'
security_capabilities_url = '/ISAPI/Security/capabilities'
web_authorization_type_url = '/ISAPI/Security/webCertificate'
# =========================== REQUESTS =============================
user_password_xml = """\
<?xml version="1.0" encoding="UTF-8"?>
<User>
<id>id</id>
<userName>name</userName>
<password>pass</password>
<userLevel>level</userLevel>
<loginPassword>admin_pass</loginPassword>
</User>
"""
add_user_xml = """\
<?xml version="1.0" encoding="UTF-8"?>
<User>
<userName>video</userName>
<userLevel>Viewer</userLevel>
<password>pass</password>
<userLevel>level</userLevel>
<loginPassword>admin_pass</loginPassword>
</User>
"""
time_zone_xml = """\
<?xml version="1.0" encoding="UTF-8"?>
<Time>
<timeMode>NTP</timeMode>
<timeZone>timezone</timeZone>
</Time>
"""
ntp_server_xml = """\
<?xml version="1.0" encoding="UTF-8"?>
<NTPServerList>
<NTPServer>
<id>1</id>
<addressingFormatType>ipaddress</addressingFormatType>
<ipAddress>1.1.1.1</ipAddress>
<portNo>123</portNo>
<synchronizeInterval>60</synchronizeInterval>
</NTPServer>
</NTPServerList>
"""
ip_address_xml = """\
<?xml version="1.0" encoding="UTF-8"?>
<IPAddress>
<ipVersion>dual</ipVersion>
<addressingType>static</addressingType>
<ipAddress>address</ipAddress>
<subnetMask>255.255.255.0</subnetMask>
<ipv6Address>::</ipv6Address>
<bitMask>0</bitMask>
<DefaultGateway>
<ipAddress>gateway</ipAddress>
<ipv6Address>::</ipv6Address>
</DefaultGateway>
<PrimaryDNS>
<ipAddress>8.8.8.8</ipAddress>
</PrimaryDNS>
<SecondaryDNS>
<ipAddress>0.0.0.0</ipAddress>
</SecondaryDNS>
<Ipv6Mode>
<ipV6AddressingType>ra</ipV6AddressingType>
<ipv6AddressList>
<v6Address>
<id>1</id>
<type>manual</type>
<address>::</address>
<bitMask>0</bitMask>
</v6Address>
</ipv6AddressList>
</Ipv6Mode>
</IPAddress>
"""
dhcp_xml = """\
<?xml version="1.0" encoding="UTF-8"?>
<IPAddress>
<ipVersion>dual</ipVersion>
<addressingType>dynamic</addressingType>
<ipAddress></ipAddress>
<subnetMask>255.255.255.0</subnetMask>
<ipv6Address>::</ipv6Address>
<bitMask>0</bitMask>
<Ipv6Mode>
<ipV6AddressingType>ra</ipV6AddressingType>
<ipv6AddressList>
<v6Address>
<id>1</id>
<type>manual</type>
<address>::</address>
<bitMask>0</bitMask>
</v6Address>
</ipv6AddressList>
</Ipv6Mode>
</IPAddress>
"""
cloud_xml = """\
<?xml version="1.0" encoding="UTF-8"?>
<EZVIZ>
<enabled>false</enabled>
</EZVIZ>
"""
integration_protocol_xml = """\
<?xml version="1.0" encoding="UTF-8"?>
<Integrate>
<CGI>
<enable>true</enable>
<certificateType>digest/basic</certificateType>
</CGI>
</Integrate>
"""
osd_xml = """\
<?xml version="1.0" encoding="UTF-8"?>
<VideoOverlay>
<normalizedScreenSize>
<normalizedScreenWidth>704</normalizedScreenWidth>
<normalizedScreenHeight>576</normalizedScreenHeight>
</normalizedScreenSize>
<attribute>
<transparent>false</transparent>
<flashing>false</flashing>
</attribute>
<fontSize>adaptive</fontSize>
<TextOverlayList size="4"></TextOverlayList>
<DateTimeOverlay>
<enabled>true</enabled>
<positionX>0</positionX>
<positionY>544</positionY>
<dateStyle>YYYY-MM-DD</dateStyle>
<timeStyle>24hour</timeStyle>
<displayWeek>false</displayWeek>
</DateTimeOverlay>
<channelNameOverlay>
<enabled>false</enabled>
<positionX>512</positionX>
<positionY>64</positionY>
</channelNameOverlay>
<frontColorMode>auto</frontColorMode>
<frontColor>000000</frontColor>
</VideoOverlay>
"""
ip_ban_option_xml = """\
<?xml version="1.0" encoding="UTF-8"?>
<IllegalLoginLock>
<enabled>false</enabled>
</IllegalLoginLock>
"""
activation_password_xml = """\
<?xml version="1.0" encoding="UTF-8"?>
<ActivateInfo>
<password>pass</password>
</ActivateInfo>
"""
public_key_xml = """\
<PublicKey>
<key>publickey</key>
</PublicKey>
"""
device_info_xml = """\
<DeviceInfo version="2.0">
<deviceName>name</deviceName>
</DeviceInfo>
"""
email_addresses_xml = """\
<mailing version="2.0">
<id>1</id>
<sender>
<emailAddress></emailAddress>
<name></name>
<smtp>
<enableAuthorization>false</enableAuthorization>
<enableSSL>false</enableSSL>
<addressingFormatType>hostname</addressingFormatType>
<hostName></hostName>
<portNo>25</portNo>
<accountName></accountName>
<enableTLS>false</enableTLS>
<startTLS>false</startTLS>
</smtp>
</sender>
<receiverList>
<receiver>
<id>1</id>
<name></name>
<emailAddress></emailAddress>
</receiver>
<receiver>
<id>2</id>
<name></name>
<emailAddress></emailAddress>
</receiver>
<receiver>
<id>3</id>
<name></name>
<emailAddress></emailAddress>
</receiver>
</receiverList>
<attachment>
<snapshot>
<enabled>false</enabled>
<interval>2</interval>
</snapshot>
</attachment>
</mailing>
"""
empty_event_trigger_xml = """\
<EventTriggerNotificationList version="2.0"></EventTriggerNotificationList>
"""
email_event_trigger_xml = """\
<EventTriggerNotificationList version="2.0">
<EventTriggerNotification>
<id>email</id>
<notificationMethod>email</notificationMethod>
<notificationRecurrence>beginning</notificationRecurrence>
</EventTriggerNotification>
</EventTriggerNotificationList>
"""
recording_event_trigger_xml = """\
<EventTriggerNotificationList version="2.0">
<EventTriggerNotification>
<id>record-1</id>
<notificationMethod>record</notificationMethod>
<videoInputID>1</videoInputID>
<notificationRecurrence>beginning</notificationRecurrence>
</EventTriggerNotification>
</EventTriggerNotificationList>
"""
motion_detector_parameters_xml = """\
<MotionDetection version="2.0">
<enabled>true</enabled>
<enableHighlight>true</enableHighlight>
<samplingInterval>2</samplingInterval>
<startTriggerTime>500</startTriggerTime>
<endTriggerTime>500</endTriggerTime>
<regionType>grid</regionType>
<Grid>
<rowGranularity>18</rowGranularity>
<columnGranularity>22</columnGranularity>
</Grid>
<MotionDetectionLayout version="2.0"
xmlns="http://www.std-cgi.com/ver20/XMLSchema">
<sensitivityLevel>20</sensitivityLevel>
<layout>
<gridMap>fffffcfffffcfffffcfffffcfffffcfffffcfffffcfffffcfffffcfffffcfffffcfffffcfffffcfffffcfffffcfffffcfffffcfffffc</gridMap>
</layout>
</MotionDetectionLayout>
</MotionDetection>
"""
recording_schedule_time_xml = """\
<ScheduleBlock ScheduleActionSize="8" >
<ScheduleBlockGUID>{00000000-0000-0000-0000-000000000000}</ScheduleBlockGUID>
<ScheduleBlockType>www.std-cgi.com/racm/schedule/ver10</ScheduleBlockType>
<ScheduleAction>
<id>1</id>
<ScheduleActionStartTime>
<DayOfWeek>Monday</DayOfWeek>
<TimeOfDay>00:00:00</TimeOfDay>
</ScheduleActionStartTime>
<ScheduleActionEndTime>
<DayOfWeek>Monday</DayOfWeek>
<TimeOfDay>24:00:00</TimeOfDay>
</ScheduleActionEndTime>
<ScheduleDSTEnable>false</ScheduleDSTEnable>
<Description>nothing</Description>
<Actions>
<Record>true</Record>
<ActionRecordingMode>MOTION</ActionRecordingMode>
</Actions>
</ScheduleAction>
<ScheduleAction>
<id>1</id>
<ScheduleActionStartTime>
<DayOfWeek>Tuesday</DayOfWeek>
<TimeOfDay>00:00:00</TimeOfDay>
</ScheduleActionStartTime>
<ScheduleActionEndTime>
<DayOfWeek>Tuesday</DayOfWeek>
<TimeOfDay>24:00:00</TimeOfDay>
</ScheduleActionEndTime>
<ScheduleDSTEnable>false</ScheduleDSTEnable>
<Description>nothing</Description>
<Actions>
<Record>true</Record>
<ActionRecordingMode>MOTION</ActionRecordingMode>
</Actions>
</ScheduleAction>
<ScheduleAction>
<id>1</id>
<ScheduleActionStartTime>
<DayOfWeek>Wednesday</DayOfWeek>
<TimeOfDay>00:00:00</TimeOfDay>
</ScheduleActionStartTime>
<ScheduleActionEndTime>
<DayOfWeek>Wednesday</DayOfWeek>
<TimeOfDay>24:00:00</TimeOfDay>
</ScheduleActionEndTime>
<ScheduleDSTEnable>false</ScheduleDSTEnable>
<Description>nothing</Description>
<Actions>
<Record>true</Record>
<ActionRecordingMode>MOTION</ActionRecordingMode>
</Actions>
</ScheduleAction>
<ScheduleAction>
<id>1</id>
<ScheduleActionStartTime>
<DayOfWeek>Thursday</DayOfWeek>
<TimeOfDay>00:00:00</TimeOfDay>
</ScheduleActionStartTime>
<ScheduleActionEndTime>
<DayOfWeek>Thursday</DayOfWeek>
<TimeOfDay>24:00:00</TimeOfDay>
</ScheduleActionEndTime>
<ScheduleDSTEnable>false</ScheduleDSTEnable>
<Description>nothing</Description>
<Actions>
<Record>true</Record>
<ActionRecordingMode>MOTION</ActionRecordingMode>
</Actions>
</ScheduleAction>
<ScheduleAction>
<id>1</id>
<ScheduleActionStartTime>
<DayOfWeek>Friday</DayOfWeek>
<TimeOfDay>00:00:00</TimeOfDay>
</ScheduleActionStartTime>
<ScheduleActionEndTime>
<DayOfWeek>Friday</DayOfWeek>
<TimeOfDay>24:00:00</TimeOfDay>
</ScheduleActionEndTime>
<ScheduleDSTEnable>false</ScheduleDSTEnable>
<Description>nothing</Description>
<Actions>
<Record>true</Record>
<ActionRecordingMode>MOTION</ActionRecordingMode>
</Actions>
</ScheduleAction>
<ScheduleAction>
<id>1</id>
<ScheduleActionStartTime>
<DayOfWeek>Saturday</DayOfWeek>
<TimeOfDay>00:00:00</TimeOfDay>
</ScheduleActionStartTime>
<ScheduleActionEndTime>
<DayOfWeek>Saturday</DayOfWeek>
<TimeOfDay>24:00:00</TimeOfDay>
</ScheduleActionEndTime>
<ScheduleDSTEnable>false</ScheduleDSTEnable>
<Description>nothing</Description>
<Actions>
<Record>true</Record>
<ActionRecordingMode>MOTION</ActionRecordingMode>
</Actions>
</ScheduleAction>
<ScheduleAction>
<id>1</id>
<ScheduleActionStartTime>
<DayOfWeek>Sunday</DayOfWeek>
<TimeOfDay>00:00:00</TimeOfDay>
</ScheduleActionStartTime>
<ScheduleActionEndTime>
<DayOfWeek>Sunday</DayOfWeek>
<TimeOfDay>24:00:00</TimeOfDay>
</ScheduleActionEndTime>
<ScheduleDSTEnable>false</ScheduleDSTEnable>
<Description>nothing</Description>
<Actions>
<Record>true</Record>
<ActionRecordingMode>MOTION</ActionRecordingMode>
</Actions>
</ScheduleAction>
</ScheduleBlock>
"""
recording_schedule_enabling_xml = """\
<CustomExtension>
<CustomExtensionName>www.std-cgi.com/RaCM/trackExt/ver10</CustomExtensionName>
<enableSchedule>true</enableSchedule>
<PreRecordTimeSeconds>5</PreRecordTimeSeconds>
<PostRecordTimeSeconds>5</PostRecordTimeSeconds>
</CustomExtension>
"""
video_photo_ratio_xml = """\
<diskQuota version="2.0">
<id>1</id>
<type>ratio</type>
<videoQuotaRatio>100</videoQuotaRatio>
<pictureQuotaRatio>0</pictureQuotaRatio>
</diskQuota>
"""
# ================================================== UTILS =================================================
class Enum:
@classmethod
def items(cls):
return {f[0]: f[1] for f in cls.__dict__.items() if not f[0].startswith('__') and not callable(f[1]) and not hasattr(f[1], '__func__')}
@classmethod
def values(cls):
return list(cls.items().values())
# ===========================================================================================================
class AuthType:
BASIC = 1,
DIGEST = 2,
UNAUTHORISED = 3
def get_auth_type(cam_ip, password):
request = requests.get(get_service_url(cam_ip, time_url), auth=HTTPBasicAuth(admin_user_name, password))
if request.ok:
return AuthType.BASIC
request = requests.get(get_service_url(cam_ip, time_url), auth=HTTPDigestAuth(admin_user_name, password))
if request.ok:
return AuthType.DIGEST
return AuthType.UNAUTHORISED
def get_auth(auth_type, name, password):
if auth_type == AuthType.BASIC:
return HTTPBasicAuth(name, password)
elif auth_type == AuthType.DIGEST:
return HTTPDigestAuth(name, password)
else:
return None
def get_service_url(cam_ip, relative_url):
return 'http://' + cam_ip + relative_url
# =========================================== NTP =================================================
def set_ntp(auth_type, cam_ip, password):
request = ElementTree.fromstring(ntp_server_xml)
server_element = request.find('NTPServer')
ip_element = server_element.find('ipAddress')
ip_element.text = new_ntp
request_data = ElementTree.tostring(request, encoding='utf8', method='xml')
process_request(auth_type, cam_ip, ntp_url, password, request_data, 'NTP set')
# =========================================== IP & DNS =================================================
def set_ip_and_dns(auth_type, cam_ip, new_ip, password):
if new_ip == DHCP_OPTION:
enable_dhcp(auth_type, cam_ip, password)
return
if new_ip is not None:
request = ElementTree.fromstring(ip_address_xml)
new_ip_address = str(new_ip.ip)
new_netmask = str(new_ip.netmask)
new_gateway = str(next(new_ip.network.hosts()))
ip_element = request.find('ipAddress')
ip_element.text = new_ip_address
net_mask_element = request.find('subnetMask')
net_mask_element.text = new_netmask
request = write_ip_to_xml(request, 'DefaultGateway', new_gateway)
request = add_dns_to_xml(request)
request_data = ElementTree.tostring(request, encoding='utf8', method='xml')
message = 'IP set to %s, netmask %s, gateway %s, dns1 %s, dns2 %s' % (new_ip_address, new_netmask, new_gateway, primary_dns, secondary_dns)
process_request(auth_type, cam_ip, ip_url, password, request_data, message, 'Reboot Required')
else:
print("New IP is not given, IP won't be changed")
set_dns(auth_type, cam_ip, password)
def enable_dhcp(auth_type, cam_ip, password):
process_request(auth_type, cam_ip, ip_url, password, dhcp_xml, 'DHCP enabled', 'Reboot Required')
def set_dns(auth_type, cam_ip, password):
request = requests.get(get_service_url(cam_ip, ip_url), auth=get_auth(auth_type, admin_user_name, password))
answer_text = clear_xml_from_namespaces(request.text)
ip_address_info = ElementTree.fromstring(answer_text)
addressing_type = ip_address_info.find('addressingType')
if addressing_type is not None and addressing_type.text == 'static':
ip_address_info = add_dns_to_xml(ip_address_info)
request_data = ElementTree.tostring(ip_address_info, encoding='utf8', method='xml')
process_request(auth_type, cam_ip, ip_url, password, request_data, 'DNS servers set')
else:
print("IP address is not static (DHCP, APIPA), DNS won't be set")
def add_dns_to_xml(xml):
xml = write_ip_to_xml(xml, 'PrimaryDNS', primary_dns)
xml = write_ip_to_xml(xml, 'SecondaryDNS', secondary_dns)
return xml
def write_ip_to_xml(xml, tag_name, ip_value):
parent_element = xml.find(tag_name)
ip_element = parent_element.find('ipAddress')
ip_element.text = ip_value
return xml
# =========================================== VIDEO =================================================
MAXIMAL_RESOLUTION_OPTION = 'max'
DHCP_OPTION = 'dhcp'
FRAMERATE_MULTIPLIER = 100
class VideoCodecOptions(Enum):
H264 = 'h264'
H265 = 'h265'
MJPEG = 'mjpeg'
class VideoCodec:
H264 = 'H.264'
H265 = 'H.265'
MJPEG = 'MJPEG'
class WDRMode:
ON = 'open'
OFF = 'close'
class VideoMode:
def __init__(self, width, height, framerate):
self.width = width
self.height = height
self.framerate = framerate
class VideoCapabilities:
def __init__(self, width_list, height_list, framerate_list, codec_list):
self.width_list = width_list
self.height_list = height_list
self.framerate_list = framerate_list
self.codec_list = codec_list
def is_mode_supported(self, videomode):
return self.width_list.count(videomode.width) != 0 \
and self.height_list.count(videomode.height) != 0 \
and self.framerate_list.count(videomode.framerate) != 0
def is_codec_supported(self, codec):
return self.codec_list.count(codec) != 0
def get_maximal_resolution_mode(self, framerate):
max_width = self.width_list[-1]
max_height = self.height_list[-1]
return VideoMode(max_width, max_height, framerate)
class ImageCapabilities:
def __init__(self, wdr):
self.wdr = wdr
class WDRCapabilities:
def __init__(self, wdr_modes, wdr_level_range):
self.wdr_modes = wdr_modes
self.wdr_level_range = wdr_level_range
def is_mode_supported(self, mode, level):
(min_level, max_level) = self.wdr_level_range
return self.wdr_modes.count(mode) != 0 and min_level <= level <= max_level
class VideoChannel:
def __init__(self, name, stream_mode, codec, initial_video_xml_element, stream_audio):
self.name = name
self.stream_mode = stream_mode
self.codec = codec
self.initial_video_xml_element = initial_video_xml_element
self.stream_audio = stream_audio
def get_video_element(self):
video_element = self.fill_video_element(self.initial_video_xml_element, self.stream_mode, self.codec)
return video_element
def fill_video_element(self, element, videomode, codec):
width_element = element.find('videoResolutionWidth')
width_element.text = str(videomode.width)
height_element = element.find('videoResolutionHeight')
height_element.text = str(videomode.height)
frame_rate_element = element.find('maxFrameRate')
frame_rate_element.text = str(videomode.framerate)
codec_element = element.find('videoCodecType')
codec_element.text = codec
return element
def set_video_streams(auth_type, cam_ip, password):
request = requests.get(get_service_url(cam_ip, video_url), auth=get_auth(auth_type, admin_user_name, password))
answer_text = clear_xml_from_namespaces(request.text)
channel_list = ElementTree.fromstring(answer_text)
channels = channel_list.findall('StreamingChannel')
is_mode_supported = True
for channel in channels:
channel_id = channel.find('id').text
capabilities = get_video_capabilities(channel_id, auth_type, cam_ip, password)
channel_video = channel.find('Video')
if channel_id[-1:] == '1':
video_mode = calculate_video_mode(main_stream_width, main_stream_height, main_stream_framerate, capabilities)
codec = option_to_videocodec(main_stream_codec, capabilities)
video_channel = VideoChannel('MAIN', video_mode, codec, channel_video, main_stream_audio)
else:
video_mode = calculate_video_mode(sub_stream_width, sub_stream_height, sub_stream_framerate, capabilities)
codec = option_to_videocodec(sub_stream_codec, capabilities)
video_channel = VideoChannel('SUB', video_mode, codec, channel_video, sub_stream_audio)
audio_element = channel.find('Audio')
if audio_element is not None:
enabled_element = audio_element.find('enabled')
enabled_element.text = 'true' if video_channel.stream_audio else 'false'
print_video_mode_info(video_channel)
if capabilities.is_mode_supported(video_channel.stream_mode):
replace_subelement_with(channel, video_channel.get_video_element())
else:
is_mode_supported = False
break
if is_mode_supported:
request_data = ElementTree.tostring(channel_list, encoding='utf8', method='xml')
process_request(auth_type, cam_ip, video_url, password, request_data, 'Video streams set')
else:
print('VIDEO MODE IS NOT SUPPORTED BY CAMERA!')
def get_video_capabilities(channel_id, auth_type, cam_ip, password):
request_url = video_capabilities_url.format(channel_id)
request = requests.get(get_service_url(cam_ip, request_url), auth=get_auth(auth_type, admin_user_name, password))
answer_text = clear_xml_from_namespaces(request.text)
channel_capabilities = ElementTree.fromstring(answer_text)
video_capabilities = channel_capabilities.find('Video')
width_list = get_int_options_list(video_capabilities, 'videoResolutionWidth')
height_list = get_int_options_list(video_capabilities, 'videoResolutionHeight')
frame_rate_list = get_int_options_list(video_capabilities, 'maxFrameRate')
codec_list = get_str_options_list(video_capabilities, 'videoCodecType')
return VideoCapabilities(width_list, height_list, frame_rate_list, codec_list)
def calculate_video_mode(width, height, framerate, capabilities):
if width == MAXIMAL_RESOLUTION_OPTION or height == MAXIMAL_RESOLUTION_OPTION:
mode = capabilities.get_maximal_resolution_mode(framerate * FRAMERATE_MULTIPLIER)
else:
mode = VideoMode(width, height, framerate * FRAMERATE_MULTIPLIER)
return mode
def get_str_options_list(element, tag):
inner_element = element.find(tag)
options_text = inner_element.attrib['opt']
options = options_text.split(',')
return options
def get_int_options_range(element, tag):
inner_element = element.find(tag)
min_value = inner_element.attrib['min']
max_value = inner_element.attrib['max']
return int(min_value), int(max_value)
def get_int_options_list(element, tag):
options = get_str_options_list(element, tag)
return list(map(int, options))
def option_to_videocodec(option, capabilities):
if option == VideoCodecOptions.MJPEG:
return VideoCodec.MJPEG
if option == VideoCodecOptions.H265 and capabilities.is_codec_supported(VideoCodec.H265):
return VideoCodec.H265
return VideoCodec.H264
def print_video_mode_info(video_channel):
mode = video_channel.stream_mode
framerate = int(mode.framerate / FRAMERATE_MULTIPLIER)
audio = 'AUDIO' if video_channel.stream_audio else 'NO AUDIO'
print('Video stream: {} - {}/{} - {}x{}x{}'.format(video_channel.name, video_channel.codec, audio, mode.width, mode.height, framerate))
def set_wdr(auth_type, current_cam_ip, current_password):
image_capabilities = get_image_capabilities(auth_type, current_cam_ip, current_password)
if image_capabilities.wdr is None:
print("WDR isn't available in this camera")
return
capabilities = image_capabilities.wdr
wdr_mode = WDRMode.ON if wdr_on else WDRMode.OFF
if not capabilities.is_mode_supported(wdr_mode, wdr_level):
print('WDR SETTINGS (mode = {}, level = {}) ARE NOT SUPPORTED BY CAMERA!'.format(wdr_mode, wdr_level))
return
request = requests.get(get_service_url(current_cam_ip, wdr_url), auth=get_auth(auth_type, admin_user_name, current_password))
answer_text = clear_xml_from_namespaces(request.text)
wdr_element = ElementTree.fromstring(answer_text)
wdr_mode_element = wdr_element.find('mode')
wdr_mode_element.text = wdr_mode
wdr_level_element = wdr_element.find('WDRLevel')
wdr_level_element.text = str(wdr_level)
request_data = ElementTree.tostring(wdr_element, encoding='utf8', method='xml')
process_request(auth_type, current_cam_ip, wdr_url, current_password, request_data, 'WDR parameters set')
def get_image_capabilities(auth_type, cam_ip, password):
request = requests.get(get_service_url(cam_ip, image_capabilities_url), auth=get_auth(auth_type, admin_user_name, password))
answer_text = clear_xml_from_namespaces(request.text)
image_capabilities_element = ElementTree.fromstring(answer_text)
wdr_capabilities_element = image_capabilities_element.find('WDR')
if wdr_capabilities_element is not None:
wdr_modes = get_str_options_list(wdr_capabilities_element, 'mode')
wdr_level_range = get_int_options_range(wdr_capabilities_element, 'WDRLevel')
wdr_capabilities = WDRCapabilities(wdr_modes, wdr_level_range)
else:
wdr_capabilities = None
return ImageCapabilities(wdr_capabilities)
# =========================================== REBOOT =================================================
def reboot_cam(auth_type, cam_ip):
request = requests.put(get_service_url(cam_ip, reboot_url), auth=get_auth(auth_type, admin_user_name, admin_new_password), data=[])
answer_text = request.text
print_answer_status('Reboot', answer_text, 'OK')
# =========================================== OSD =================================================
def set_osd(auth_type, cam_ip, password):
process_request(auth_type, cam_ip, osd_url, password, osd_xml, 'OSD set')
# =========================================== IP BAN =================================================