Repository navigation
Expand file tree
/
Copy pathaxis_batch_programmer.py
More file actions
1869 lines (1540 loc) · 91.6 KB
/
Copy pathaxis_batch_programmer.py
File metadata and controls
1869 lines (1540 loc) · 91.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
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
"""
Axis Camera Batch Programmer
Discovers factory-fresh Axis P3267-LV cameras via DHCP/ARP and configures them based on CSV data.
Automates initial setup (password, EULA) and batch configuration.
"""
import csv
import socket
import requests
import time
import ipaddress
import os
from datetime import datetime
from typing import Dict, List, Optional
from requests.auth import HTTPDigestAuth
import logging
import psutil
from concurrent.futures import ThreadPoolExecutor, as_completed
import subprocess
import re
from urllib.parse import quote
# Configure logging with UTF-8 encoding for Windows compatibility
import sys
if sys.platform == 'win32':
import codecs
sys.stdout = codecs.getwriter('utf-8')(sys.stdout.buffer, 'strict')
sys.stderr = codecs.getwriter('utf-8')(sys.stderr.buffer, 'strict')
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s',
handlers=[
logging.FileHandler('axis_programmer.log', encoding='utf-8'),
logging.StreamHandler()
]
)
logger = logging.getLogger(__name__)
# Constants
DEFAULT_IP = "192.168.0.90" # Older models only - P3267-LV uses DHCP
DEFAULT_USER = "root" # Most Axis cameras use "root" (including P3267-LV)
DEFAULT_PASS = "" # Factory default has no password
FACTORY_INITIAL_PASSWORD = "pass" # Temporary password to set on factory-fresh cameras during discovery
# NOTE: P3267-LV and newer models require:
# 1. Accepting EULA/terms checkbox on first boot
# 2. Setting "root" password via the initial setup form
# The setup_initial_password() method handles both automatically
VAPIX_TIMEOUT = 30 # For managed switches with rate limiting, increase to 30-60 seconds
NETWORK_CONFIG_TIMEOUT = 60 # Longer timeout for network changes (important for VLANs)
NETWORK_VERIFY_TIMEOUT = 45 # Timeout for verifying network changes
DISCOVERY_TIMEOUT = 5
# Timezone mapping: Common timezone names to POSIX format
TIMEZONE_MAP = {
# US Timezones
"America/New_York": "EST5EDT,M3.2.0,M11.1.0",
"Eastern": "EST5EDT,M3.2.0,M11.1.0",
"America/Chicago": "CST6CDT,M3.2.0,M11.1.0",
"Central": "CST6CDT,M3.2.0,M11.1.0",
"America/Denver": "MST7MDT,M3.2.0,M11.1.0",
"Mountain": "MST7MDT,M3.2.0,M11.1.0",
"America/Phoenix": "MST7", # Arizona (no DST)
"America/Los_Angeles": "PST8PDT,M3.2.0,M11.1.0",
"Pacific": "PST8PDT,M3.2.0,M11.1.0",
"America/Anchorage": "AKST9AKDT,M3.2.0,M11.1.0",
"Alaska": "AKST9AKDT,M3.2.0,M11.1.0",
"Pacific/Honolulu": "HST10", # Hawaii (no DST)
# European Timezones
"Europe/London": "GMT0BST,M3.5.0/1,M10.5.0",
"Europe/Paris": "CET-1CEST,M3.5.0,M10.5.0/3",
"Europe/Berlin": "CET-1CEST,M3.5.0,M10.5.0/3",
"Europe/Rome": "CET-1CEST,M3.5.0,M10.5.0/3",
# Asian Timezones
"Asia/Tokyo": "JST-9",
"Asia/Shanghai": "CST-8",
"Asia/Singapore": "SGT-8",
"Asia/Dubai": "GST-4",
# Australian Timezones
"Australia/Sydney": "AEST-10AEDT,M10.1.0,M4.1.0/3",
"Australia/Perth": "AWST-8",
}
def normalize_mac_address(mac: str) -> str:
"""Normalize MAC address to consistent format with colons.
Handles multiple input formats:
- B8:A4:4F:FF:2E:D7 (colon format)
- B8-A4-4F-FF-2E-D7 (dash format)
- B8A44FFF2ED7 (no separator)
- b8:a4:4f:ff:2e:d7 (lowercase)
Returns:
MAC in uppercase colon format: "B8:A4:4F:FF:2E:D7"
"""
# Remove all separators and convert to uppercase
clean_mac = mac.upper().replace(':', '').replace('-', '').replace('.', '')
# Validate length
if len(clean_mac) != 12:
raise ValueError(f"Invalid MAC address length: {mac}")
# Insert colons every 2 characters
formatted_mac = ':'.join(clean_mac[i:i+2] for i in range(0, 12, 2))
return formatted_mac
def convert_timezone(tz_name: str) -> str:
"""Convert common timezone name to POSIX format.
Args:
tz_name: Timezone name (e.g., "America/New_York", "Eastern", "America/Denver (GMT -6)")
Returns:
POSIX timezone string (e.g., "EST5EDT,M3.2.0,M11.1.0")
If not found in map, returns input as-is (assumes already POSIX format)
"""
# Strip any GMT offset information in parentheses (e.g., "America/Denver (GMT -6)" -> "America/Denver")
tz_name_clean = re.sub(r'\s*\([^)]*\)\s*', '', tz_name).strip()
return TIMEZONE_MAP.get(tz_name_clean, tz_name_clean)
class AxisCamera:
"""Represents an Axis camera with configuration methods."""
def __init__(self, ip: str, mac: str, username: str = DEFAULT_USER, password: str = DEFAULT_PASS):
self.ip = ip
self.mac = normalize_mac_address(mac) # Handles all MAC formats
self.username = username
self.password = password
self.session = requests.Session()
self.session.auth = HTTPDigestAuth(username, password)
# CRITICAL FIX: Disable proxy for direct camera connections
# Corporate laptops often have proxy settings that break direct IP connections
self.session.trust_env = False # Ignore system proxy settings
self.session.proxies = {
'http': None,
'https': None
}
def test_connection(self) -> bool:
"""Test if we can connect to the camera."""
try:
# Try multiple endpoints for compatibility with different firmware versions
endpoints = [
"/axis-cgi/param.cgi?action=list&group=Network", # Most compatible
"/axis-cgi/basicdeviceinfo.cgi",
"/axis-cgi/serverreport.cgi"
]
for endpoint in endpoints:
try:
url = f"http://{self.ip}{endpoint}"
response = self.session.get(url, timeout=VAPIX_TIMEOUT)
if response.status_code == 200:
logger.debug(f"Connection successful to {self.ip} via {endpoint}")
return True
except:
continue
logger.debug(f"All connection tests failed for {self.ip}")
return False
except Exception as e:
logger.debug(f"Connection test failed for {self.ip}: {e}")
return False
def get_mac_address(self) -> Optional[str]:
"""Retrieve the camera's MAC address."""
try:
url = f"http://{self.ip}/axis-cgi/param.cgi?action=list&group=Network.eth0"
response = self.session.get(url, timeout=VAPIX_TIMEOUT)
if response.status_code == 200:
for line in response.text.split('\n'):
if 'MACAddress' in line:
mac = line.split('=')[1].strip().upper()
return mac
logger.warning(f"No MAC address found in response from {self.ip}")
elif response.status_code == 401:
logger.warning(f"Authentication failed at {self.ip} (401 Unauthorized) - Wrong credentials?")
elif response.status_code == 403:
logger.warning(f"Access forbidden at {self.ip} (403 Forbidden) - Check user permissions")
else:
logger.warning(f"Unexpected response from {self.ip}: {response.status_code}")
except requests.exceptions.ConnectTimeout:
logger.warning(f"Connection timeout to {self.ip} - Camera may be slow or unreachable")
except requests.exceptions.ConnectionError as e:
logger.warning(f"Connection error to {self.ip}: {str(e)[:100]}")
except Exception as e:
logger.warning(f"Failed to get MAC from {self.ip}: {type(e).__name__}: {str(e)[:100]}")
return None
def setup_initial_password(self, password: str = "pass") -> bool:
"""Set initial admin password on factory-fresh camera.
Factory-reset cameras require accepting EULA/terms and setting the admin password
via the web setup before API access is allowed. This automates that initial setup.
P3267-LV shows "root" username on initial setup page and requires EULA acceptance.
Returns:
True if setup was attempted (camera was in setup mode)
False if camera not in setup mode (already configured)
"""
try:
# Try multiple URLs - different firmware versions use different paths
# P3225: http://IP/ redirects to setup
# P3267: http://IP/camera/index.html is the setup page
setup_check_urls = [
f"http://{self.ip}/camera/index.html", # P3267 and newer
f"http://{self.ip}/", # P3225 and older
]
response = None
for check_url in setup_check_urls:
try:
logger.info(f" Trying setup URL: {check_url}")
response = requests.get(check_url, timeout=10, proxies={'http': None, 'https': None}, allow_redirects=True)
logger.info(f" Response: status={response.status_code}, length={len(response.text)} bytes, final_url={response.url}")
if response.status_code == 200 and len(response.text) > 200: # Must be substantial content
logger.info(f" ✓ Found substantial content at {check_url}")
break
else:
logger.info(f" ✗ Response too small or wrong status, trying next URL...")
except Exception as e:
logger.info(f" ✗ Request failed: {e}")
continue
if not response or response.status_code != 200:
logger.info(f" ✗ Could not access any initial setup page for {self.ip}")
return False
# P3267 firmware uses a JavaScript SPA (single-page app) for setup
# The /camera/index.html returns only ~861 bytes of skeleton HTML
# All content (passwords, EULA, etc.) is rendered by JavaScript after page load
# We can't parse the content, so we detect setup mode by:
# 1. If we got /camera/index.html with status 200 and small size, attempt setup
# 2. If we got / and it contains setup indicators, attempt setup
response_text = response.text.lower()
is_spa_setup_page = False
is_traditional_setup_page = False
# Check if this is P3267-style SPA setup page (small HTML skeleton)
if '/camera/index.html' in response.url and len(response.text) < 2000:
logger.info(f" Detected P3267 JavaScript SPA setup page (skeleton size: {len(response.text)} bytes)")
is_spa_setup_page = True
# Check if this is traditional setup page with content indicators
indicators = {
'set a password': 'set a password' in response_text,
'pwdroot in URL': 'pwdroot' in response.url.lower(),
'setpassword in URL': 'setpassword' in response.url.lower(),
'add user': 'add user' in response_text,
'EULA': 'end user license agreement' in response_text,
}
if any(indicators.values()):
logger.info(f" Detected traditional setup page with content indicators: {indicators}")
is_traditional_setup_page = True
is_setup_page = is_spa_setup_page or is_traditional_setup_page
if not is_setup_page:
# Camera not in initial setup mode - already configured
logger.info(f" ✗ Camera at {self.ip} not in initial setup mode")
return False
logger.info(f"Camera at {self.ip} IS in initial setup mode - attempting automation...")
# P3267 firmware 10.12.240+ uses pwdgrp.cgi with GET method and Digest auth
# Discovery via browser DevTools: GET /axis-cgi/pwdgrp.cgi?action=add&user=root&pwd={password}&grp=root&sgrp=admin:operator:viewer:ptz
username = 'root'
logger.info(f" Setting up initial user '{username}' with password...")
# Create a temporary session with the NEW password for Digest auth
# P3267 accepts Digest auth with the password being set during initial setup
temp_session = requests.Session()
temp_session.auth = HTTPDigestAuth(username, password)
temp_session.trust_env = False
temp_session.proxies = {'http': None, 'https': None}
# Build the pwdgrp.cgi URL with parameters
# action=add: Create new user
# user=root: Username
# pwd={password}: Password to set
# grp=root: Primary group
# sgrp=admin:operator:viewer:ptz: Secondary groups (full permissions)
setup_url = (
f"http://{self.ip}/axis-cgi/pwdgrp.cgi?"
f"action=add&user={username}&pwd={password}&grp=root&sgrp=admin:operator:viewer:ptz"
)
try:
logger.info(f" GET request to: {setup_url.replace(f'pwd={password}', 'pwd=****')}")
response = temp_session.get(setup_url, timeout=15, allow_redirects=False)
logger.info(f" Response: status={response.status_code}, Content-Type={response.headers.get('Content-Type', 'unknown')}")
logger.info(f" Response body: {response.text[:200]}")
# Success indicators: 200 OK, or response contains "OK" or "Created account"
if response.status_code == 200 and ('ok' in response.text.lower() or 'created' in response.text.lower() or len(response.text.strip()) == 0):
logger.info(f" ✓ Password set successfully for {self.ip} (username: {username})")
# Update our session with the new credentials
self.username = username
self.password = password
self.session.auth = HTTPDigestAuth(username, password)
return True
else:
logger.warning(f" ✗ Setup request returned unexpected response")
logger.warning(f" Status: {response.status_code}, Body: {response.text[:500]}")
except Exception as e:
logger.warning(f" ✗ Setup request failed: {e}")
# If we got here, all setup attempts failed
logger.warning(f"All initial setup attempts failed for {self.ip}")
logger.warning(f"Camera requires MANUAL web setup: http://{self.ip}/")
return True # Setup was needed but automation failed
except Exception as e:
logger.warning(f"Error during initial password setup check: {e}")
return False # Couldn't determine setup status
def set_network_config(self, new_ip: str, subnet_mask: str = "255.255.255.0", gateway: str = None) -> bool:
"""Configure camera's network settings."""
try:
old_ip = self.ip
# Step 1: Disable DHCP and set to static (none)
url = f"http://{self.ip}/axis-cgi/param.cgi"
param_string = f"action=update&root.Network.BootProto=none"
response = self.session.get(url + "?" + param_string, timeout=VAPIX_TIMEOUT)
if response.status_code != 200:
logger.error(f"Failed to disable DHCP: {response.status_code}")
return False
logger.info(f"DHCP disabled for {self.mac}")
time.sleep(1)
# Step 2: Set IP, subnet, and gateway using root.Network (not eth0 specific)
param_string = f"action=update&root.Network.IPAddress={new_ip}&root.Network.SubnetMask={subnet_mask}"
# Add gateway if provided
if gateway:
param_string += f"&root.Network.DefaultRouter={gateway}"
logger.info(f"Setting gateway to {gateway} for {self.mac}")
# Use GET request - Axis VAPIX often works better with GET for param updates
try:
response = self.session.get(url + "?" + param_string, timeout=NETWORK_CONFIG_TIMEOUT)
# Note: 401 response with "OK" text often means the change was applied
# but the connection was interrupted due to network change
if response.status_code == 200 or (response.status_code == 401 and response.text.strip() == "OK"):
logger.info(f"Network config set for {self.mac}: {new_ip}")
# Update our IP for further communication
self.ip = new_ip
time.sleep(5) # Wait longer for camera to apply network settings
return True
else:
logger.error(f"Failed to set network config: {response.status_code}")
logger.debug(f"Response: {response.text[:200]}")
return False
except (requests.exceptions.ConnectionError, requests.exceptions.ReadTimeout, ConnectionResetError) as conn_err:
# Connection dropped or timed out during IP change - this is NORMAL!
# Camera closes connection while reconfiguring network or times out before responding
logger.info(f"Connection interrupted during IP change (expected) - waiting for camera to reconfigure...")
logger.debug(f"Connection error details: {conn_err}")
# Update our IP to the new one and wait for camera to come back online
self.ip = new_ip
# For VLAN environments, give extra time for routing table updates
logger.info("Waiting 15 seconds for network changes and routing updates...")
time.sleep(15)
# Try multiple times to verify the new IP is reachable (important for VLANs)
max_verify_attempts = 5
verify_delay = 5 # seconds between attempts
for attempt in range(1, max_verify_attempts + 1):
try:
logger.info(f"Verification attempt {attempt}/{max_verify_attempts}: Checking camera at {new_ip}...")
test_url = f"http://{new_ip}/axis-cgi/param.cgi?action=list&group=Network.eth0"
test_response = self.session.get(test_url, timeout=NETWORK_VERIFY_TIMEOUT)
if test_response.status_code == 200:
logger.info(f"✓ Camera successfully reconfigured and online at {new_ip}")
return True
else:
logger.warning(f"Camera responded at {new_ip} but with status {test_response.status_code}")
if attempt < max_verify_attempts:
logger.info(f"Retrying in {verify_delay} seconds...")
time.sleep(verify_delay)
else:
# Last attempt - accept any response as success
logger.info("Camera responding - assuming network change succeeded")
return True
except Exception as verify_err:
if attempt < max_verify_attempts:
logger.warning(f"Verification attempt {attempt} failed: {verify_err}")
logger.info(f"Retrying in {verify_delay} seconds...")
time.sleep(verify_delay)
else:
logger.error(f"Could not verify new IP {new_ip} after {max_verify_attempts} attempts")
logger.error(f"Last error: {verify_err}")
logger.warning("Network change may have failed - searching for camera...")
# Try to find camera at old IP, default IP, or by MAC in ARP table
search_ips = [old_ip, '192.168.0.90']
found_ip = None
# First, try the known IPs
for search_ip in search_ips:
if search_ip == new_ip:
continue # Already tried this
try:
logger.info(f"Checking if camera is at {search_ip}...")
# Update session to point to search IP temporarily
test_url = f"http://{search_ip}/axis-cgi/param.cgi?action=list&group=Brand"
test_session = requests.Session()
test_session.auth = HTTPDigestAuth(self.username, self.password)
test_response = test_session.get(test_url, timeout=10)
if test_response.status_code == 200:
logger.info(f"✓ Found camera at {search_ip}!")
found_ip = search_ip
self.ip = search_ip
self.session = test_session
break
except Exception as search_err:
logger.debug(f"Camera not at {search_ip}: {search_err}")
continue
# If not found at known IPs, search ARP table by MAC address
if not found_ip:
logger.info(f"Searching ARP table for camera {self.mac}...")
arp_table = get_arp_table()
if self.mac in arp_table:
arp_ip = arp_table[self.mac]
if arp_ip != new_ip: # Don't retry the IP we already failed at
logger.info(f"Found camera at {arp_ip} via ARP table (MAC: {self.mac})")
try:
# Verify it's really our camera
test_url = f"http://{arp_ip}/axis-cgi/param.cgi?action=list&group=Brand"
test_session = requests.Session()
test_session.auth = HTTPDigestAuth(self.username, self.password)
test_response = test_session.get(test_url, timeout=10)
if test_response.status_code == 200:
logger.info(f"✓ Confirmed camera at {arp_ip} via HTTP")
found_ip = arp_ip
self.ip = arp_ip
self.session = test_session
except Exception as arp_verify_err:
logger.warning(f"Could not verify camera at ARP IP {arp_ip}: {arp_verify_err}")
else:
logger.warning(f"Camera MAC {self.mac} not found in ARP table")
if found_ip:
logger.info(f"Camera found at {found_ip}, retrying network configuration to {new_ip}...")
logger.info("Waiting 5 seconds before retry...")
time.sleep(5)
# Retry the network configuration
try:
param_string = f"action=update&root.Network.IPAddress={new_ip}&root.Network.SubnetMask={subnet_mask}"
if gateway:
param_string += f"&root.Network.DefaultRouter={gateway}"
url = f"http://{self.ip}/axis-cgi/param.cgi"
retry_response = self.session.get(url + "?" + param_string, timeout=NETWORK_CONFIG_TIMEOUT)
logger.info(f"Retry network config sent, waiting 15 seconds...")
self.ip = new_ip
time.sleep(15)
# Verify after retry
test_url = f"http://{new_ip}/axis-cgi/param.cgi?action=list&group=Network.eth0"
final_test = self.session.get(test_url, timeout=NETWORK_VERIFY_TIMEOUT)
if final_test.status_code == 200:
logger.info(f"✓ RETRY SUCCESSFUL: Camera now at {new_ip}")
return True
else:
logger.warning(f"Retry verification returned status {final_test.status_code}")
logger.warning(f"Camera may still be at {found_ip} - check manually")
return False
except Exception as retry_err:
logger.error(f"Retry failed: {retry_err}")
logger.error(f"Camera may still be at {found_ip}")
return False
else:
logger.error(f"Could not find camera {self.mac} at any IP")
logger.error("Checked: new IP, old IP, 192.168.0.90, and ARP table")
logger.error("Manual intervention may be required")
return False
except Exception as e:
logger.error(f"Unexpected error setting network config: {e}")
return False
def set_credentials(self, new_username: str, new_password: str) -> bool:
"""Set new administrator credentials."""
try:
url = f"http://{self.ip}/axis-cgi/pwdgrp.cgi"
# If keeping root username, just update the password
if new_username == 'root':
# Update root password
param_string = f"action=update&user=root&pwd={new_password}"
response = self.session.get(url + "?" + param_string, timeout=VAPIX_TIMEOUT)
if response.status_code == 200 and ("OK" in response.text or "Modified account" in response.text):
# Update session auth
self.password = new_password
self.session.auth = HTTPDigestAuth(new_username, new_password)
logger.info(f"Root password updated for {self.mac}")
return True
else:
logger.error(f"Failed to update root password: {response.status_code} - {response.text[:100]}")
return False
else:
# First, update root password to secure it
logger.info(f"Updating root password first for {self.mac}...")
param_string = f"action=update&user=root&pwd={new_password}"
response = self.session.get(url + "?" + param_string, timeout=VAPIX_TIMEOUT)
if response.status_code == 200 and ("OK" in response.text or "Modified account" in response.text):
logger.info(f"Root password updated for {self.mac}")
# Update session to use new root password immediately
self.password = new_password
self.session.auth = HTTPDigestAuth('root', new_password)
else:
logger.warning(f"Root password update had issues: {response.status_code} - {response.text[:100]}")
# Still update auth in case it worked but response was unexpected
self.password = new_password
self.session.auth = HTTPDigestAuth('root', new_password)
# Try to update user first (in case user already exists)
logger.info(f"Checking if user '{new_username}' exists for {self.mac}...")
param_string = f"action=update&user={new_username}&pwd={new_password}"
response = self.session.get(url + "?" + param_string, timeout=VAPIX_TIMEOUT)
user_updated = False
if response.status_code == 200 and ("OK" in response.text or "Modified account" in response.text):
logger.info(f"User '{new_username}' password updated for {self.mac}")
user_updated = True
else:
# User doesn't exist, try to create it
logger.info(f"User doesn't exist, creating new user '{new_username}' for {self.mac}...")
param_string = f"action=add&user={new_username}&pwd={new_password}&grp=admin&sgrp=admin:operator:viewer"
response = self.session.get(url + "?" + param_string, timeout=VAPIX_TIMEOUT)
if response.status_code == 200 and ("OK" in response.text or "Created account" in response.text):
logger.info(f"New user '{new_username}' created for {self.mac}")
user_updated = True
else:
logger.error(f"Failed to create user: {response.status_code} - {response.text[:100]}")
return False
if user_updated:
# Update session auth to new user
self.username = new_username
self.password = new_password
self.session.auth = HTTPDigestAuth(new_username, new_password)
# Optionally remove root user (commented out for safety)
# self._remove_user(DEFAULT_USER)
return True
else:
return False
except Exception as e:
logger.error(f"Error setting credentials: {e}")
return False
def _remove_user(self, username: str) -> bool:
"""Remove a user account."""
try:
url = f"http://{self.ip}/axis-cgi/pwdgrp.cgi"
params = {'action': 'remove', 'user': username}
response = self.session.post(url, data=params, timeout=VAPIX_TIMEOUT)
return response.status_code == 200
except Exception as e:
logger.debug(f"Error removing user {username}: {e}")
return False
def set_camera_name(self, name: str) -> bool:
"""Set the camera's system name."""
try:
# Try multiple possible name parameters
url = f"http://{self.ip}/axis-cgi/param.cgi"
# Some cameras use System.HostName, others use Network.HostName
param_string = f"action=update&root.System.HostName={name}&root.Network.HostName={name}"
response = self.session.get(url + "?" + param_string, timeout=VAPIX_TIMEOUT)
if response.status_code == 200:
logger.info(f"Camera name set to '{name}' for {self.mac}")
return True
else:
logger.error(f"Failed to set camera name: {response.status_code}")
return False
except Exception as e:
logger.error(f"Error setting camera name: {e}")
return False
def set_date_time(self, timezone: str = "America/New_York", use_ntp: bool = True, ntp_server: str = "pool.ntp.org") -> bool:
"""Configure date, time, and timezone settings.
Args:
timezone: Timezone name (e.g., "America/New_York", "Central") or POSIX format
Common names are automatically converted to POSIX format
use_ntp: Enable NTP time synchronization
ntp_server: NTP server address
"""
try:
url = f"http://{self.ip}/axis-cgi/param.cgi"
# Convert timezone name to POSIX format
posix_tz = convert_timezone(timezone)
logger.info(f"Setting timezone '{timezone}' (POSIX: {posix_tz}) for {self.mac}")
# Set POSIX timezone - URL encode the timezone string to handle special characters
posix_tz_encoded = quote(posix_tz, safe='')
param_string = f"action=update&root.Time.POSIXTimeZone={posix_tz_encoded}"
response = self.session.get(url + "?" + param_string, timeout=VAPIX_TIMEOUT)
if response.status_code != 200 or "Error" in response.text:
logger.warning(f"Timezone setting had issues: {response.text[:100]}")
# Don't fail - timezone may already be correct
else:
logger.info(f"Timezone configured successfully for {self.mac}")
# Configure NTP
if use_ntp:
# Enable NTP and set NTP server
param_string = f"action=update&root.Time.SyncSource=NTP&root.Time.NTP.Server={ntp_server}"
response = self.session.get(url + "?" + param_string, timeout=VAPIX_TIMEOUT)
if response.status_code == 200 and "Error" not in response.text:
logger.info(f"NTP enabled with server '{ntp_server}' for {self.mac}")
else:
logger.warning(f"NTP configuration had issues: {response.text[:100]}")
return True
except Exception as e:
logger.warning(f"Error setting date/time: {e}")
return True # Don't fail the whole process for time config
def zoom_out_fully(self) -> bool:
"""Zoom out camera to minimum zoom level."""
try:
# Check if camera has PTZ capabilities
url = f"http://{self.ip}/axis-cgi/param.cgi?action=list&group=PTZ"
response = self.session.get(url, timeout=VAPIX_TIMEOUT)
if response.status_code == 200 and 'PTZ' in response.text:
# PTZ camera - use PTZ command
zoom_url = f"http://{self.ip}/axis-cgi/com/ptz.cgi?zoom=1"
zoom_response = self.session.get(zoom_url, timeout=VAPIX_TIMEOUT)
if zoom_response.status_code == 200:
logger.info(f"Zoom set to minimum for {self.mac}")
return True
else:
# Fixed camera or no PTZ - try digital zoom settings
url = f"http://{self.ip}/axis-cgi/param.cgi"
params = {
'action': 'update',
'Image.I0.Appearance.Zoom': '1' # Minimum zoom
}
response = self.session.post(url, data=params, timeout=VAPIX_TIMEOUT)
if response.status_code == 200:
logger.info(f"Digital zoom adjusted for {self.mac}")
return True
logger.warning(f"No zoom control available for {self.mac}")
return True # Not a failure, just not applicable
except Exception as e:
logger.warning(f"Could not adjust zoom for {self.mac}: {e}")
return True # Don't fail the whole process for zoom
def set_resolution(self, width: int = 1024, height: int = 768) -> bool:
"""Set camera resolution.
Args:
width: Resolution width in pixels (default: 1024)
height: Resolution height in pixels (default: 768)
Note: Some cameras may briefly disconnect when resolution changes.
This function handles connection errors gracefully and won't fail the configuration.
"""
try:
url = f"http://{self.ip}/axis-cgi/param.cgi"
# Try multiple possible parameter names for resolution
# Different Axis camera models/firmware use different parameters
# P3267-LV confirmed working: root.Image.I0.Appearance.Resolution
resolution_params = [
f"root.Image.I0.Appearance.Resolution={width}x{height}", # P3267-LV, P3225 (most common)
f"root.Image.I0.Stream.1.Resolution={width}x{height}", # Stream-specific
f"root.Properties.Image.Resolution={width}x{height}", # Global properties
f"root.ImageSource.I0.Sensor.Resolution={width}x{height}", # Sensor resolution
]
for param in resolution_params:
try:
param_string = f"action=update&{param}"
logger.info(f"Trying resolution parameter: {param.split('=')[0]}")
response = self.session.get(url + "?" + param_string, timeout=VAPIX_TIMEOUT)
# Success is indicated by HTTP 200 with "OK" response (not containing "Error")
if response.status_code == 200:
response_text = response.text.strip()
if response_text == "OK" or (response_text and "error" not in response_text.lower()):
logger.info(f"✓ Resolution set to {width}x{height} for {self.mac}")
logger.info(f" Used parameter: {param.split('=')[0]}")
# Some cameras may briefly disconnect after resolution change
# Wait a moment and recreate session if needed
time.sleep(2)
return True
else:
logger.debug(f" Response: {response_text[:100]}")
else:
logger.debug(f" HTTP {response.status_code}")
except requests.exceptions.ConnectionError as conn_err:
# Camera may have briefly disconnected due to resolution change
logger.info(f" Connection interrupted (camera may be adjusting resolution)")
logger.info(f" Waiting for camera to stabilize...")
time.sleep(3)
# Try to reconnect with a fresh session
try:
self.session = requests.Session()
self.session.auth = HTTPDigestAuth(self.username, self.password)
# Test reconnection
test_response = self.session.get(f"http://{self.ip}/axis-cgi/param.cgi?action=list&group=Brand", timeout=10)
if test_response.status_code == 200:
logger.info(f" ✓ Reconnected successfully")
# Resolution may have been set despite connection error
return True
else:
logger.warning(f" Reconnection returned status {test_response.status_code}")
except Exception as reconnect_err:
logger.warning(f" Reconnection failed: {reconnect_err}")
# Continue trying other parameters
continue
except Exception as param_err:
logger.debug(f" Error with this parameter: {param_err}")
continue
# If none worked, log warning but don't fail
logger.warning(f"Could not confirm resolution set to {width}x{height} - may not be supported or camera disconnected")
logger.warning(f"Resolution remains at camera default")
return True # Don't fail - may not be supported on all models
except Exception as e:
logger.warning(f"Error setting resolution for {self.mac}: {e}")
logger.warning(f"Continuing with configuration...")
return True # Don't fail the whole process for resolution
def verify_configuration(self, expected_ip: str, expected_name: str = None) -> bool:
"""Verify that configuration was applied correctly."""
try:
# Test connection with new IP
url = f"http://{self.ip}/axis-cgi/param.cgi?action=list&group=Network.eth0"
response = self.session.get(url, timeout=VAPIX_TIMEOUT)
if response.status_code != 200:
logger.error(f"Cannot verify config - connection failed")
return False
# Check IP address
config_text = response.text
if f"Network.eth0.IPAddress={expected_ip}" not in config_text:
logger.error(f"IP verification failed. Expected {expected_ip}")
return False
# Check name if provided
if expected_name:
url = f"http://{self.ip}/axis-cgi/param.cgi?action=list&group=System"
response = self.session.get(url, timeout=VAPIX_TIMEOUT)
if f"System.HostName={expected_name}" not in response.text:
logger.warning(f"Name verification failed. Expected '{expected_name}'")
# Don't fail for name mismatch, just warn
logger.info(f"Configuration verified for {self.mac}")
return True
except Exception as e:
logger.error(f"Error verifying configuration: {e}")
return False
def get_firmware_version(self) -> Optional[str]:
"""Get current firmware version.
Returns:
Firmware version string (e.g., "10.12.240") or None if unable to retrieve
"""
try:
url = f"http://{self.ip}/axis-cgi/param.cgi?action=list&group=root.Properties.Firmware"
response = self.session.get(url, timeout=VAPIX_TIMEOUT)
if response.status_code == 200:
for line in response.text.split('\n'):
if 'Version' in line:
version = line.split('=')[1].strip()
logger.info(f"Current firmware version: {version}")
return version
logger.warning(f"Could not retrieve firmware version from {self.ip}")
return None
except Exception as e:
logger.error(f"Error getting firmware version: {e}")
return None
def upgrade_firmware(self, firmware_path: str, progress_callback=None) -> bool:
"""Upload and install firmware update.
Args:
firmware_path: Path to .bin firmware file
progress_callback: Optional callback function(stage, message) for progress updates
Returns:
True if upgrade successful, False otherwise
"""
try:
if not os.path.exists(firmware_path):
logger.error(f"Firmware file not found: {firmware_path}")
return False
firmware_filename = os.path.basename(firmware_path)
logger.info(f"Starting firmware upgrade for {self.mac} using {firmware_filename}")
if progress_callback:
progress_callback("validating", "Checking current firmware...")
current_version = self.get_firmware_version()
if current_version:
logger.info(f"Current firmware: {current_version}")
# Step 1: Upload firmware file
if progress_callback:
progress_callback("uploading", "Uploading firmware file...")
logger.info(f"Uploading firmware file ({os.path.getsize(firmware_path) / 1024 / 1024:.1f} MB)...")
# Try simple binary POST first (works on many Axis cameras)
url = f"http://{self.ip}/axis-cgi/firmwaremanagement.cgi?method=upgrade"
with open(firmware_path, 'rb') as f:
# Send raw binary file as request body
headers = {'Content-Type': 'application/octet-stream'}
response = self.session.post(url, data=f, headers=headers, timeout=600)
logger.info(f"Firmware upload response: HTTP {response.status_code}")
logger.info(f"Response content: {response.text[:500]}") # Changed to INFO to always see it
if response.status_code == 200:
logger.info("Firmware upload successful")
# Check if response contains JSON error (even with 200 status)
has_json_error = False
try:
response_json = response.json()
if 'error' in response_json:
logger.warning(f"Upload returned error in JSON: {response_json['error'].get('message', 'Unknown error')}")
has_json_error = True
except ValueError:
# Not JSON, continue with normal processing
pass
if not has_json_error:
if progress_callback:
progress_callback("installing", "Installing firmware (camera will reboot)...")
# Check response for success indicators
response_text = response.text.lower()
# VAPIX 3 returns JSON with data field on success
try:
response_json = response.json()
if 'data' in response_json and 'firmwareVersion' in response_json.get('data', {}):
new_fw_version = response_json['data']['firmwareVersion']
logger.info(f"Firmware upgrade accepted! Target version: {new_fw_version}")
logger.info("Camera will reboot - this may take 5-10 minutes")
if progress_callback:
progress_callback("rebooting", "Waiting for camera to reboot (5-10 minutes)...")
# Wait for camera to reboot
logger.info("Waiting 2 minutes before checking camera status...")
time.sleep(120)
# NOTE: Firmware upgrade may change camera IP!
# Camera temporarily enables DHCP during upgrade, gets new IP,
# then converts DHCP address to static. We need to find it by MAC.
original_ip = self.ip
camera_found = False
# Poll for camera to come back online (up to 10 minutes)
max_attempts = 60
for attempt in range(max_attempts):
try:
# Try original IP first
test_response = self.session.get(
f"http://{self.ip}/axis-cgi/param.cgi?action=list&group=root.Properties.Firmware",
timeout=10
)
if test_response.status_code == 200:
camera_found = True
break
except:
# Camera not at original IP - it may have moved during firmware upgrade
if attempt % 6 == 0: # Every minute
logger.info(f"Camera not responding at {self.ip}, scanning for new IP...")
# Scan ARP table for camera by MAC address
try:
import subprocess
result = subprocess.run(['arp', '-a'], capture_output=True, text=True, timeout=5)
# Look for our MAC in ARP table
target_mac_formats = [
self.mac.replace(':', '-').lower(), # Windows format
self.mac.lower(), # Colon format
]
for line in result.stdout.split('\n'):
for mac_format in target_mac_formats:
if mac_format in line.lower():
# Extract IP from line
parts = line.split()
if len(parts) >= 1:
potential_ip = parts[0].strip()
if potential_ip != self.ip and '.' in potential_ip:
logger.info(f"Found camera at new IP: {potential_ip} (was {self.ip})")
self.ip = potential_ip
break
except:
pass
if attempt % 6 == 0: # Log every minute
logger.info(f"Still waiting for camera to come online... ({attempt * 10}s elapsed)")
time.sleep(10)
if camera_found:
# Camera is back online - verify new firmware
new_version = self.get_firmware_version()
if progress_callback:
progress_callback("complete", f"Firmware upgrade complete: {new_version}")
logger.info(f"✓ Firmware upgrade successful!")
logger.info(f" Old version: {current_version}")
logger.info(f" New version: {new_version}")
if self.ip != original_ip:
logger.warning(f" Camera IP changed during upgrade: {original_ip} → {self.ip}")
return True
else:
logger.error("Timeout waiting for camera to come back online after firmware upgrade")
logger.warning("Camera may still be upgrading - check manually after a few minutes")
return False
except ValueError:
pass # Not JSON, continue checking text
# Fallback: Check for text-based success indicators
if 'ok' in response_text or 'success' in response_text:
logger.info("Firmware upgrade initiated - camera will reboot")
logger.info("This may take 5-10 minutes. Camera will be unavailable during upgrade.")