Introduction
This is a python module for interacting with Hikvision IP cameras and NVRs. Most rebadged models work as well with full functionality. It provides two ways to talk to a device:
HikCamera- connects to a device's ISAPI event stream and tracks event/sensor state changes in real time (motion, line crossing, tamper, I/O, disk errors, etc.), with callbacks on updates. Also supports snapshots, RTSP stream URLs, motion detection toggling, and recording search/download.ISAPIClient- a synchronous ISAPI client for querying and controlling a device: device info/capabilities, storage devices, streaming channels, cameras, I/O ports, event enable/disable, snapshots, RTSP URLs, holiday mode, and reboot.
Requirements
Optional:- pyDispatcher 2.0.5 - only needed if you want
HikCamerato also broadcast updates viapydispatchsignals; the built-in callback mechanism (add_update_callback) works without it
Installation
pip install pyhik
ISAPIClient is included. (pip install pyhik[isapi] still works, but the extra is no longer needed.)
Usage - Event streaming (HikCamera)
import pyhik.hikvision as hikvision
camera = hikvision.HikCamera('http://X.X.X.X', port=80, usr='admin', pwd='1234')
Register a callback, then start the event stream processing thread
camera.add_update_callback(lambda msg: print('Update:', msg), camera.get_id)
camera.start_stream()
print(camera.get_name, camera.current_event_states)
...when finished
camera.disconnect()
Callbacks
add_update_callback(callback, msg)- register a callback function, called withcam_id.event_type.channelwhenever a tracked event changes state.
Properties
get_id- unique camera/NVR id: the device'sdeviceID, or, when that is missing or 10 characters or fewer, auuid.UUIDderived from its serial number and MAC address, the same at every connection. Placeholder serials (0,N/A, ...) are ignored, and the MAC is read as its 12 hex digits whatever its format. Only a device that reports neither gets a random UUIDget_name- camera/NVR nameget_type- device type (CAMorNVR)auth_failed-Trueif the device answered but rejected the credentials, so a missingget_idcan be told apart from an unreachable devicecurrent_event_states- dictionary of all tracked events and their current statecurrent_motion_detection_state- current motion detection on/off statestream_connected- whether the event stream is currently connectedstream_auth_failed-Truewhile the device refuses the credentials for the event stream (two refusals without a connection in between). Any other failure, such as an offline device, sets it back toFalse. The stream then tries again only every 30 minutes, since attempts at the usual pace with a rejected password can lock the account, and a locked account or a restored password recovers by itself. Registered callbacks are called when it becomesTrueand when it becomesFalseagain
Functions
start_stream()- start the event stream processing threaddisconnect()- close the event stream session and stop the processing threadget_channels()- list available channelsget_motion_detection()/enable_motion_detection()/disable_motion_detection()- read/toggle motion detectionget_snapshot(channel=1)- fetch a JPEG snapshot for a channelget_stream_url(channel=1, protocol='rtsp', stream_type=1)- build an RTSP stream URLfetch_attributes(event, channel)- get the state list for a specific sensor/channelget_recording_days(track_id, start_date, end_date)- list days that have recordingssearch_recordings(track_id, start_time, end_time, max_results=100)- search for recordings in a time rangedownload_recording(playback_uri, output_stream=None, chunk_size=65536)- download a recording found viasearch_recordings
Usage - Device control (ISAPIClient)
from pyhik.isapi import ISAPIClient
with ISAPIClient('X.X.X.X', port=80, username='admin', password='1234') as client:
print(client.get_device_name(), client.get_firmware_version())
print(client.get_capabilities())
snapshot = client.get_snapshot(channel=1)
rtsp_url = client.get_rtsp_url(channel=1)
Functions
get_device_info()/get_device_serial()/get_device_name()/get_device_model()/get_device_type()/get_firmware_version()- device identityget_capabilities()- returns aDeviceCapabilitiessummary of what the device supportsget_storage_devices()- listStorageDeviceentries (HDD/SD status, capacity)get_alarm_server_info()/ configure viarequest()- alarm server settingsget_streaming_channels()- listStreamInfofor available streamsget_cameras()- listCameraInfo(useful on NVRs with multiple channels)get_output_ports()/get_input_ports()- list I/O portsget_output_state(output_id)/set_output_state(output_id, state)- read/set an output relayget_holiday_mode_enabled()/set_holiday_mode_enabled(enabled)- read/set holiday modeget_event_states()/set_event_enabled(...)- read/toggle event detection types (see Detections)get_snapshot(channel=1, stream_type=1, width=None, height=None)- fetch a snapshotget_rtsp_url(channel=1, stream_type=1, include_credentials=True)- build an RTSP stream URLreboot()- reboot the devicecustom_request(...)- issue an arbitrary ISAPI request for endpoints not otherwise wrappedrequest_raw(method, endpoint, body=None)- likecustom_requestbut sends the body unmodified and returns the unparsed response (RawResponse: status code, bytes, case-insensitive headers) without raising on HTTP error statuses (after a 401 the request is retried once with Digest auth)get_image_settings(channel=1, proxy=False)- list the image settings a camera supports (shutter, gain, WDR, BLC, day/night, ...) with their current values (ImageSettingobjects, seepyhik.image)get_image_values(channel=1, proxy=False)- read only the current values as{path: value}; cheap enough to pollset_image_setting(path, value, channel=1, proxy=False)- change one image setting; known conflicts between settings are resolved automaticallyset_image_linked_setting(setting, value, channel=1, proxy=False)- set a select that also controls anenabledflag, such as BLC modeput_image_settings(changes, channel=1, proxy=False)- lower level: write several{path: value}changes in one request, without conflict handlingget_image_channels(proxy=False)- list the channel IDs that have image settings (ImageChannelInfo)
Image settings
Cameras expose their image settings (shutter, gain, WDR, BLC, day/night, supplement light, ...) under /ISAPI/Image/channels/. Which settings exist differs per model, so they are discovered from the device:
client = ISAPIClient("192.168.1.100", username="admin", password="secret")
settings = {s.path: s for s in client.get_image_settings()}
settings["Color/brightnessLevel"].value # '80'
settings["Shutter/ShutterLevel"].options # ['1/3', '1/6', ..., '1/100000']
Reading raises:
ISAPINotSupportedError(a subclass ofISAPINotFoundError) if the device does not offer the endpoint (404, 501 or anotSupportreply)ISAPIAuthErrorfor credential or permission problemsISAPIConnectionErrorif the device cannot be reached
status_code and sub_status, the HTTP status and the device's subStatusCode.
Changing a setting:
result = client.set_image_setting("Shutter/ShutterLevel", "1/500")
result.success, result.sub_status # True, 'ok'
Write Mechanism
- Read-Modify-Write: A write operation reads the full document, changes only the target value as text, and sends the updated document back to the device.
- Non-Atomic Operations: Writes are not atomic—avoid overlapping or concurrent writes to the same device.
Conflict Resolution
Some settings inherently conflict with one another (e.g. enabling WDR while BLC or HLC is active and vice versa). When a conflict occurs:
- Automatic Override: The conflicting setting is automatically switched off first to make room for the new setting.
- Firmware Error Codes: Firmware reporting conflicts as
HLCMutexWDROrDehazeorWDROrDehazeMutexHLC(HTTP 403) is handled identically: - HLC is switched off when WDR or defog is turned on.
- WDR and defog are switched off when HLC is turned on.
- Result Tracking:
ImageWriteResult.also_changedlists the settings that were automatically disabled (e.g.{"HLC/enabled": "false"}).- If a request fails after that, the error raised has the same list in its
also_changedattribute. It also lists the settings of a switch-off request that failed without an answer (a timeout for example), since the device may have applied it. Any other exception raised once a setting is listed is raised as anISAPIError, so that the list is not lost. ImageWriteResult.error_descriptionexplains any conflicts that could not be resolved.
Linked Selects
- A feature with an
enabledflag and a mode is reported as one select that sets both (linked_enabled_path), with an off option (off_value): BLC mode (CLOSE), and image flip (ImageFlip/ImageFlipStyle). The flip direction has no off option on the device, which omits it while flip is off and refuses flip on without it, so pyhik addsOFF(off_value_writtenis false: choosing it writes only the flag). The off option is matched in any letter case, and only the device's own (CLOSE) is written to the mode element.
Fallback Handling (Sub-Endpoints)
notSupportHandling: If a camera rejects writes to the full document with anotSupporterror, the system automatically attempts to use per-feature sub-endpoints (example/ISAPI/Image/channels/1/Shutter).- Condition: This fallback only triggers when all requested changes belong to the same feature (such as
BLC/enabledandBLC/BLCMode).
proxy=True (/ISAPI/ContentMgmt/ImageProxy/channels/) and use the IDs returned by get_image_channels(proxy=True):
for channel in client.get_image_channels(proxy=True):
settings = client.get_image_settings(channel.id, proxy=True)
- The sub-endpoint fallback is not used through the NVR.
- An NVR may list a channel whose camera it cannot proxy; reading it raises
ISAPINotSupportedError.
- A recorder may report
deviceTypeIPC, the type a camera reports; the type alone cannot tell an NVR from a camera. - If the direct listing fails, try
get_image_channels(proxy=True). - An NVR may reject the camera endpoints (
/ISAPI/Image/channels) with HTTP 503serviceUnavailableor 400badXmlContent. pyhik raises a plainISAPIErrorfor these; catching onlyISAPINotSupportedErrorwill not catch them. ISAPINotSupportedErroronly means that the device says it does not offer the endpoint: HTTP 404, 501 or anotSupportreply.- For any other error, check
status_codeandsub_statuson the exception.
Detections
The detections of a video channel can be turned on and off one by one: motionDetection, lineDetection, fieldDetection (intrusion), regionEntrance, regionExiting, tamperDetection, sceneChangeDetection and videoLoss (DETECTIONS).
client.get_detection_enabled("fieldDetection") # True
client.set_detection_enabled("fieldDetection", False) # ImageWriteResult(success=True, ...)
client.get_detection_enabled("lineDetection", channel=2)
- Only the flag right below the document's root is read and written, the camera UI's "Enable" checkbox. The regions and lines inside keep their own flags, and the rest of the document is sent back as it was read. Nothing is sent when it is already so, read as
get_detection_enabled()reads it (TRUEis on). - A write answered with a 2xx is a success, unless its body is a
ResponseStatusthat says otherwise: some devices answer with an empty body or another document. Any other refusal comes back in the result, with the device's sub status. - A detection the device does not have raises
ISAPINotSupportedError: 404, 501,notSupportorinvalidOperation, also when it comes with a 403. Cameras answer 403notSupportfor the detections they lack; that is not about the credentials. - A 401, or another 403, to the read or the write, raises
ISAPIAuthError, whatever comes with it (aResponseStatus, nothing, or a web page).get_event_states()now stops on a 401 instead of trying every other detection with the same credentials; a detection refused with a 403 is left out, and the others are still read.
Checking the ISAPI image settings
python -m pyhik checkisapi tries the image settings code against a real camera or NVR.
TESTING.md has the instructions to use it and can be used to report a
problem.
TODO
- Support IR day/night status and ability to switch between day/night/auto