Skip to content

Add module checkisapi on a real device - #154

Open
baylanger wants to merge 10 commits into
mezz64:masterfrom
baylanger:tool-live_image_check
Open

baylanger wants to merge 10 commits into
mezz64:masterfrom
baylanger:tool-live_image_check

Conversation

@baylanger

@baylanger baylanger commented Nov 7, 2026 •

Copy link
Copy Markdown
Contributor

Add python -m pyhik checkisapi

A check to run by hand against a real camera or NVR. Unit tests have to run
without hardware. This is for people with a device who want to try the
image settings code or report a problem.

python -m pyhik <command> is a small dispatcher (pyhik/__main__.py) that imports a
command only when it is asked for. checkisapi is the first command, so others (for example
dump) can be added later.

Run

export CAMERA_HOST=192.168.1.100
export CAMERA_USERNAME=admin
export CAMERA_PASSWORD='passwd123'
python -m pyhik checkisapi

Optional: CAMERA_PORT (80, or 443 with HTTPS), CAMERA_SSL=1, CAMERA_VERIFY_SSL=0 for a
self-signed certificate. --host, --port, --username, --ssl and --no-verify do the same as
CAMERA_HOST, CAMERA_PORT, CAMERA_USERNAME, CAMERA_SSL=1 and CAMERA_VERIFY_SSL=0, and win over
them. The password is read only from the environment, never from the command line, and never printed.

What it does

Command Effect
python -m pyhik checkisapi Read-only. Lists channels and every image setting with its path and value.
... --write Changes Color/brightnessLevel by one step, reads it back, restores it.
... --write --path Color/contrastLevel Same, for the setting you choose: take its path from the read-only list. A number moves one step, a switch flips (true to false or false to true) and a select takes the first option that is not the current one. --path is only used with --write.
... --conflicts WDR / HLC / BLC / defog conflict matrix.
... --bad-password A wrong password, tried through ISAPIClient and HikCamera: at least two failed logins.
... --all All of the above.
... -v Also shows pyhik's debug log (the retries).

A plain --write ends by naming a few switch and select paths to try with --path. If a change
switches another setting off to make room (WDR, BLC, HLC and defog exclude each other), that setting
is put back too and listed.

One channel is checked per run (the first listed unless --channel is
given). On an NVR or DVR the attached camera is used through the ImageProxy
endpoints:

python -m pyhik checkisapi --channel 3 --write --path Color/contrastLevel
python -m pyhik checkisapi --channel 1 --write --path enableImageLossDetection

The NVR is detected from the device type. That is not enough on its own: some NVRs report
IPC, and the device information may not be readable at all. When the camera image endpoints fail
and the NVR ones work, the NVR endpoints are used, and it prints which it chose and why.
--proxy / --no-proxy override the detection.

The device information is asked once per run, whether it answers or not. When it fails, the device
line shows the error with its HTTP status (for example
model=? (ISAPIError: Request failed with status 503)) and the run goes on.

Safety

  • Everything that changes a value puts the original back afterwards, even
    after an error, and prints NOT RESTORED, set it back by hand if it
    could not.
  • It stops at the first authentication error, since repeated failures can
    lock an account. --bad-password makes at least two failed logins (one per
    client, more if a client retries); do not use it on an account that is close
    to being locked.

Tested

Unit tests (test/test_check.py) cover the NVR detection, the write path (number, switch, select, a conflict, a failed restore), the connection options (host, port, username, HTTPS, certificate check) and the python -m pyhik dispatch, with fake devices.
On real camera DS-2CD2385G1
On a DS-7608NI-EV2/8P NVR (V3.4.96): 8 channels listed, a read, and a write of a switch
(enableImageLossDetection) through ImageProxy with the read back and the restore both
checked.

Dependencies

[ ] Requires #151 (PR4 List image channels and support NVR-attached cameras through ImageProxy) to be merged first.

@baylanger
baylanger force-pushed the tool-live_image_check branch from 24d641d to c6b1967 Compare November 7, 2026 19:07
@baylanger baylanger changed the title Add tools/live_image_check.py to check image settings on a real device Add module check image settings on a real device Nov 11, 2026

@mezz64 mezz64 left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm onboard with adding this, but considering the ISAPI functionality is only a subset of what pyHik can do, I don't know that the path should be simply called "check" as i'd expect that to check the basic event stream functionality. I think this is better suited as "checkiaspi" or something similar so a separate module can be added later to perform the same function on the base event stream monitoring code.

Also, the readme changes need cleaned up now that #151 is merged and I'd prefer you split out the xmldict change into a separate PR.

Otherwise a review flagged a couple small issues:

  • An error during the restore step in check_write can hide the original error, and the restore keeps sending requests after an auth error.
  • The restore writes back every value that changed, not just the ones in result.also_changed.
  • TESTING.md says cd pyhik; it should be cd pyHik.

@baylanger
baylanger force-pushed the tool-live_image_check branch from 07943e0 to 083ec2a Compare November 12, 2026 13:11
@baylanger baylanger changed the title Add module check image settings on a real device Add module checkisapi on a real device Nov 12, 2026
@baylanger

baylanger commented Nov 12, 2026 •

Copy link
Copy Markdown
Contributor Author

Made all the changes you requested. It was trouble to fix conflicts, I started over and ended up w/ a single commit :/

Putting here below the actual changes per your comments, made since your previous review.

check to checkisapi

Rename done.

An error during the restore step in check_write can hide the original error, and the restore keeps sending requests after an auth error.

     """Change one setting (number, switch or select), read it back, put it back."""
     out("4. change a setting and put it back")
@@ -277,6 +311,8 @@ def check_write(client, report, channel, proxy, settings, path, out):
     original = target.value
     before = client.get_image_values(channel, proxy=proxy)
     out("   %s (%s): %s -> %s" % (target.path, target.type.value, original, new))
+    result = None
+    stop = False
     try:
         result = client.set_image_setting(target.path, new, channel, proxy=proxy)
         out("   result: %s" % result)
@@ -286,24 +322,19 @@ def check_write(client, report, channel, proxy, settings, path, out):
         ok = result.success and got == new
         report.add("write", "PASS" if ok else "FAIL",
                    "read back OK" if ok else "read back %s" % got)
+    except ISAPIAuthError:
+        stop = True  # more requests would only add failed logins
+        raise
     finally:
-        result = client.set_image_setting(target.path, original, channel, proxy=proxy)
-        after = client.get_image_values(channel, proxy=proxy)
-        restored = result.success and after.get(target.path) == original
-        out("   restore %s -> %s: %s" % (
-            target.path, original, "restored" if restored else "NOT RESTORED, set it back by hand"))
-        if not restored:
-            report.add("restore of " + target.path, "FAIL", "set it back to %s by hand" % original)
-        # Settings the write switched off to make room are put back as well.
-        for other, value in before.items():
-            if other != target.path and after.get(other) != value:
-                back = client.set_image_setting(other, value, channel, proxy=proxy)
-                now = client.get_image_values(channel, proxy=proxy).get(other)
-                done = back.success and now == value
-                out("   restore %s -> %s: %s" % (
-                    other, value, "restored" if done else "NOT RESTORED, set it back by hand"))
-                if not done:
-                    report.add("restore of " + other, "FAIL", "set it back to %s by hand" % value)
+        # The setting under test, then the settings the write itself reported switching
+        # off to make room (WDR, BLC, HLC and defog exclude each other).
+        changes = [(target.path, original)]
+        for other in getattr(result, "also_changed", None) or {}:
+            if other != target.path:
+                changes.append((other, before.get(other)))
+        auth_error = put_back(client, report, channel, proxy, changes, out, skip=stop)
+    if auth_error:
+        raise auth_error
     if not path:
         suggest_paths(settings, out)

The restore writes back every value that changed, not just the ones in result.also_changed.

Added put_back function.

TESTING.md says cd pyhik; it should be cd pyHik.

Done.

@baylanger

Copy link
Copy Markdown
Contributor Author

Omg... I thought I'd create the first PR for Home-Assistant (core and docs) and ended up creating them as Draft. I think I'm starting a headache :D I'll revisit them later.

@mezz64

mezz64 commented Nov 13, 2026

Copy link
Copy Markdown
Owner

Thanks for working through all of that, and no worries about the single commit. The rename and the put_back helper look good.

Another pass turned up a few more things, mostly in the restore paths. I'd like these fixed before merging, since they can leave a camera with changed settings or add failed logins:

  1. check_write can miss a blocker when the write raises. Restoring only result.also_changed was the right call, but if set_image_setting raises after pyhik has already switched a blocker off, result is still None and that blocker never gets restored. For example, with --write --path WDR/mode and HLC on, pyhik turns HLC off, then the retry raises ISAPIConnectionError, and HLC stays off with no report. When result is None, it should also restore anything that differs from before.

  2. Linked settings lose their mode on restore. check_write restores BLC with a plain set_image_setting("BLC/enabled", "true"), so the BLC mode isn't written back. The device then either refuses or turns BLC on with a default mode. The conflicts check already restores these through the linked setter, and check_write should do the same.

  3. The conflicts check keeps going after an auth error. The finally in check_conflicts still runs every off(), restore_on() and read() after an ISAPIAuthError. That's up to 2N+1 more failed logins, and the first one raises a new auth error that replaces the original and skips the "NOT RESTORED" report. The same skip-after-auth-error handling you added in put_back would work here.

  4. detect_proxy and _device_line swallow auth errors. Both catch everything, including ISAPIAuthError, and then send more requests. With a wrong password, a plain read-only run makes about 3 to 6 failed logins instead of stopping at the first, as the docs say it does. Letting ISAPIAuthError through there should fix it.

There are also some smaller things (a TESTING.md note about port 443, -v hiding pyhik debug output during --conflicts, a couple of message and cleanup nits) that can wait for a follow-up.

A rejected login or a missing permission (401 or 403) is not carried on from:
the run stops at that request and prevents a wrong password to be tried again.
put_back now reads the device first and only writes what differs from
before. When the write raised, that is everything that differs, not just
the setting under test. If the device cannot be read at that point, the
run fails and says to compare WDR, HLC, BLC and defog by hand.

Reading first also means nothing is written when the device refused the
change and nothing differs.
The restore now goes through put_back, as --write does. Nothing is sent
after an authentication error and every setting is reported as NOT TRIED
with its old value; any other error is reported for that setting and the
rest are still put back. Only the settings the last case left different
are written, instead of every feature twice.
The conflicts check only restored the settings it had built a table for.

Now after a restore, any other setting that differs from before is listed
in a "note:" line and left alone. The check did not change it (a device
can reset a level when its feature is switched), it;s not written,
but it is no longer left unmentioned.
The table only knew HLC as a plain switch and BLC as a mode linked to its
enabled flag. Firmware that has it the other way round (HLC/HLCMode linked
to HLC/enabled, or a BLC mode list without an off option) lost that row
without notice, and with fewer than two rows the check was skipped.

Both are now built the same way: a linked select if pyhik reports one,
otherwise the enabled switch.

From Hikvision NVR dev guide:

HLC with a mode:
- One HLC block has <enabled> plus <HLCMode opt="close,open,auto"> and <HLCLevel>.
  That is the linked-select form pyHik folds into one setting, with “close” as
  the off value.
- HLC as a plain switch: Another HLC block has only <enabled> and <HLCLevel>,
  with no mode. That matches a DS-2CD2385G1. The guide documents both forms,
  which is why this patch builds HLC as a linked select when pyHik reports one
  and as a plain switch otherwise.
- BLC: <BLCMode opt="UP,DOWN,LEFT,RIGHT,CENTER,MULTI-AREA,Region,AUTO"> has no
  “close”. pyHik won’t fold it, so BLC stays a plain switch with a separate mode
  That is the plain-switch BLC form that is now handle.
get_image_settings also lists what the capabilities offer but the current
document leaves out, with the default as its value (example, the levels of
a noise reduction mode that is not selected). --write --path on one
of those failed with pathNotFound and then reported a failed restore.

- Such a path is a SKIP that says why.
- A number is not moved outside its range
- The paths suggested after a plain --write are ones that can be changed.
- TESTING.md said port 443 enables HTTPS. It does not: CAMERA_SSL=1 or
  --ssl does, and then 443 is the default port.
- -v no longer loses pyhik's debug log during --conflicts. The check
  lowered the logger to INFO to collect the conflict codes even when it
  was already at DEBUG.
- A failed write says whether the device refused it (with the reason) or
  accepted it and read back something else.
- A conflict case whose starting point could not be set up is marked "?"
  instead of being tried anyway, the summary counts those, and a table
  with no case tried is a SKIP, not a PASS.
- --path without --write is an error instead of being ignored.
- The client is closed at the end of the run.
- Removed the check for a pyhik without HikCamera.auth_failed, and an
  except clause that named a subclass next to its base class.
- Tests for --bad-password, which had none.
@baylanger

Copy link
Copy Markdown
Contributor Author

If I had to start over, conflict resolution and perhaps even checkisapi would not exist :) it has honestly turned into a massive beast.

To tackle this cleanly, I fed the Hikvision NVR developer guide into Claude to cross-reference everything, trying to make sure we hit every edge case, fix any other possible bugs and tie up loose ends from your last review. It did find quite a lot. It found quite a lot more than I would have expended. I did multiple commit, will make your life easier. If you find there's too many changes, please blame Claude ;)

That said, I had to reinstall MacOS and doing that nuked my VPN configuration :( I'm away from home since 2 days, I can't test anything until I return sometimes next week or weekend.

If you have time to test, great... otherwise perhaps we wait before merging this PR and just move ahead with a release? As you wish, I don't mind.

@mezz64

mezz64 commented Nov 17, 2026

Copy link
Copy Markdown
Owner

Thanks for working through all of those. Every item from my last comment is addressed, and the extra tests (including the first ones for --bad-password) are appreciated. No blame needed, Claude or otherwise. Separate commits made it much easier to review.

I ran it against a camera on my local network, a DS-2CD3132-I on firmware V5.2.5:

  • Read-only: PASS (1 channel, 26 settings, 30 values)
  • --write on a number (brightness), a switch (Exposure/OverexposeSuppress/enabled) and a select (WDR/mode): all PASS and restored
  • --conflicts: skipped cleanly. The camera only offers WDR, so nothing was changed.
  • --bad-password: PASS for both clients

What I couldn't check is the BLC/HLC side: the conflicts table, the linked BLC restore, and recovery after a failed write. This camera has no HLC or defog. Its firmware also lists BLC/enabled with the options ture/false (a Hikvision typo), so pyhik treats it as a select and BLC is left out. That's a library quirk rather than something in this PR.

Since that's where most of the new restore logic lives, I'll cut the release without this one. Once you're back and can run --write and --conflicts on your DS-2CD2385G1, let me know how it goes and we'll merge it in. No rush, and good luck getting the VPN sorted.

@baylanger

baylanger commented Nov 18, 2026 •

Copy link
Copy Markdown
Contributor Author

@mezz64 @ptarjan thank you both for taking the time to make this happen! I see 0.5.0 is released and I agree the current PR (154) can be merged later. I'm not sure yet when I'll be home to test w/ my camera. I'll update once I have done that.

I admit I was a bit depressed with all the PRs to open with HA core and the docs. I took a Claude subscription and ask to create the docs and assemble all the core PRs. I was still unhappy to have to open all those PRs... so I ask Claude to write a script, open the documentation PRs, use the create PR and include it in the core PR (documentation link), etc.

I just ran the script but I won't have time to check them all tonight. I hope Claude did everything good ;)

Documentations :

01-50766-verify-ssl - Review ready
02-50767-reauth
03-50768-switches
04-50769-numbers
05-50770-selects
06-50771-sensors
08-50772-logbook
09-50773-nvr
10-50775-reconfigure
11-50945-stream-availability-log

Core pyHik 0.5.0:

00-193189-bump-pyhik - Merged
01-193190-verify-ssl - Review ready
02-193191-reauth
03-193192-switches
04-193193-numbers
05-193194-selects
06-193195-sensors
07-193196-diagnostics
08-193197-logbook
09-193198-nvr
10-193199-reconfigure ; replaces core-178112
16-193685-quality-scale-bronze
17-193686-stream-availability-log
18-193948-share-snapshot

pyHik 0.5.1+:

01-158-stream-auth-failed - Review ready
02-159-error-also-changed - Review ready
03-160-stable-device-id - Review ready
04-161-image-flip - Review ready
05-162-detection-switches - Review ready
06-163-alarm-inputs-outputs-holiday - Review ready

Core pyHik 0.5.1+:

19-193297-bump-pyhik-0-5-1
20-193298-stream-credentials
21-193299-write-error-blockers
22-193300-request-lock
23-193359-image-retry
24-194073-detection-switches
25-194077-alarm-inputs-outputs-holiday

@baylanger

Copy link
Copy Markdown
Contributor Author

I'm using this PR to update you on the latest.

First ... I have a 3-4 months trip abroad leaving in ~ 2-4 weeks, haven't decided of the date yet. I will have my computer with me but won't be on it often. I feel rushed to open PRs to get things done before I leave :( The HA integration on my side was running just fine but yesterday Claude identified a lot of things (not sure if I should cry or laugh!).

If you have time to review any PR / leave comments, please go ahead. I do plan to review and tests all changes myself whenever I get back home.

  • HA core PRs identified improvements, there are 2 new PRs for pyHik.
  • Changes per the comments in the HA core PRs opened last night were pushed just earlier.
  • New PRs below created per comments left in HA core PRs:

hikvision-core-11-bump-pyhik-0-5-1
hikvision-core-12-stream-credentials
hikvision-core-13-write-error-blockers
hikvision-core-14-request-lock

I'm editing the list in previous comments to add those.

I should have time to check the updated and new core PRs before my 2 appointments but might not have time to fix anything :/

@baylanger

Copy link
Copy Markdown
Contributor Author

I forgot 1 thing... since I have plenty of Claude token, I ask to check HA Hikvision code and it came with a long list of things. I won't create those PRs, I think we have plenty now but before losing them, I'll create the branch in my repo and you could consult them and decide if anything should be prioritized. I'll let you know once this is done.

@baylanger

baylanger commented Nov 22, 2026 •

Copy link
Copy Markdown
Contributor Author

@mezz64 @ptarjan

Unless you flag any changes, I'm done with all of the Draft or Open PRs in pyHik, HA core & home-assistant.io

I wasn't expecting Copilot to find so many things that Claude didn't get right at first. Copilot being a MS product and Github owned by MS probably explains why it found so many little things. Obviously MS likely trained Copilot using Github repos, PR descriptions, etc. Copilot isn't perfect either, sometimes it would flag a change in a PR but the code was implemented in a previous PR (stackable) and ... new things to resolve would popup. If I knew it would have taken many days to go over all the Copilot comments, maybe I'd never started this work. I'll admit at some point I gave up on validating any changes and relied purely on Anthropic and Copilot to agree on the changes.

After all Copilot comments on all PRs were all resolved, I went ahead and ask Anthropic to check edge cases for all HA changes based on the pyHik changes from 0.4.8 to 0.5.1. Here's the report and all 3 changes were pushed minutes ago:

The HA patches (193190 to 193686) already handle every odd answer pyHik can pass back, so nothing needs to change in HA. The gaps I found are inside pyHik itself, and I fixed them in a pyHik patch.

What the HA patches handle:

- 401: asks you to sign in again (reauth). After a refusal, the password isn't sent again.
- 403: shows "not allowed" and doesn't retry.
- 404, 501, or notSupport: treated as "this device doesn't have it". It isn't retried, and on discovery it checks whether the device is really an NVR.
- 5xx and connection errors: retried later. Anything else isn't retried.
- Bad XML from the camera: pyHik turns it into a normal error that HA already catches.
- Writes the camera refuses (403 conflicts, missing codes, odd bodies) show a clear message. Settings the camera switched off before an error are still shown.
- Empty or strange values (missing setting, "nan", reversed ranges) show as unknown and don't crash.
- Snapshot failures show no image instead of an error.
- Event stream refusing the password: covered by stream_auth_failed.

What I fixed in pyHik, in 0001-Raise-ISAPIError-not-ParseError-for-odd-device-answer.patch:

- Garbled document while fixing a setting conflict: pyHik raised a raw XML error that HA doesn't catch. In HA, the action ended with "Unknown error" and lost the list of settings already switched off.
- Device info returned 200 with HTML instead of XML (a login page or a proxy): the setup crashed and was never retried. pyHik now treats it like any other "cannot connect".
- Three device-info requests had no timeout: they're the ones sent after switching to Digest and to the backup URL. A camera that stalls could keep the setup waiting forever.

Each fix has a test that fails without it. All 298 pyHik tests pass. The patch is committed on your stable-fallback-id branch, so it goes into 0.5.1 before you release.

Not caused by our PRs, and I left them alone:

- NVR channel list fails at startup: the NVR comes up with no channel cameras until a reload, because pyHik returns an empty list.
- The one doorbell model with a broken event stream (DS-KV8113-WME1(B)): pyHik skips its stream on purpose, so its entities, including the camera, always show unavailable. That's how HA works today.
- An NVR camera that's offline at startup: I couldn't find which HTTP code NVRs return for it. If it's a 403, its image settings won't come back until a reload. If you've seen what your NVR returns for an offline camera, tell me and I'll check it.

Updated PRs list in this comment below.

I now need to take care of my family and might not have time to test anything this coming week as I need to prep my long trip.

@baylanger

Copy link
Copy Markdown
Contributor Author

I figured I'd ask Claude "Go over all HA changes we made, make sure tests cover everything so that if some logic is broken, any test will tell us" - it's not over yet but from the output, more tests are coming and perhaps fixes as well. Will update later, need to run errands.

@baylanger

Copy link
Copy Markdown
Contributor Author

I figured I'd ask Claude "Go over all HA changes we made, make sure tests cover everything so that if some logic is broken, any test will tell us" - it's not over yet but from the output, more tests are coming and perhaps fixes as well. Will update later, need to run errands.

After reading the below report, I feel more confident things might still be working :)

FYI coverage sits now at a whopping 99% of lines and branches!

Tests that catch broken logic

Every condition, call and return in the code the stack changed was broken on purpose
(mutation testing: about 1,000 changes) to see whether a test fails. Gaps were fixed
in the PR that owns the code, and carried up the stack.

What changed

  • 193191 13 new tests for the repair: the entry busy or not loaded, a choice
    removed during the unload, an issue without its data, labels and defaults, what
    stays on the current device. Simpler code: _async_changes no longer re-checks
    answers that were just validated; two "removed meanwhile" guards that could never
    run are gone; two redundant lines in __init__ removed.
  • 193192 Dead _rejection_pending removed (written, never read). 6 tests:
    a write shows its value before the next poll, a refused write shows what was
    switched off, a 5xx without a code is not "not allowed", an unload's recovery
    called off meanwhile. A test that passed for the wrong reason fixed.
  • 193194 2 cases: a 501 "not supported" and a non-camera error are not retried.
  • 193195 1 test: an unknown single-choice setting gets no sensor.
  • 193198 Simpler code: the device-type check, the unused child-device lookup
    and a duplicate close removed. 7 tests: a 403 on one camera, a 401 on one camera's
    poll, a request queued behind a rejected discovery, triggers of an NVR with events.
  • 193199 2 tests: reauth of a made-up ID still checks a device's own ID;
    the reconfigure form keeps what was typed after an error.
  • **193298 ** 2 tests: refusals heard together, a write waiting on the lock.
  • **193300 ** 2 tests: the re-ask timer stops once used, and with the entry.
  • **193359 ** 6 tests on the retry (a lasting error, one still running, read
    once per retry, NVR lists, a reload meanwhile). 7 retry tests now wait for the
    background task, without which they could pass for nothing.

Kept on purpose (no test can tell them apart): thread-race guards, shutdown of
coordinators with no listener, isinstance(..., ISAPIAuthError) next to a 401 check.


The above list of PRs have been updated; that said, we still need to test everything manually :/

@baylanger

baylanger commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor Author

I woke up early this morning and figured I should test and eat my own dogfood :)

I installed hikksion w/ PR 193190 to 193199 coming w/ pyHik 0.5.0 ; nothing is broken, I'm amazed everything works as it should except so far 1 bug need to be addressed, likely in pyHik.

There's a zip file here you can download and unzip in /config:
https://github.com/baylanger/home-assistant-core/releases/tag/2026%2F11%2F23

Test w/ camera DS-2CD2385G1-I

  • Sensors : working fine, they are updated whenever something triggers them.

  • Events : working as well, shows last time it was triggered.

  • Number setting : change of Brightness in hikvision is pushed to the camera; change in the camera UI reflects in hikvisiion.

  • Select setting : change of Day/Night mode works both ways like Number setting change.

  • Switch setting : change of Smart supplement light works both ways

  • Locked account : hikvision stops trying to connect until re-authentication

  • Repair showed up -> changed password -> repair cleared up

  • Re-authentifcation : worked and integration automatically started to connect to the camera

  • Didn't test the "reconfigure flow" but the window shows up fine.

Bug

  • Turning on "Image flip" in hikvision fails w/ badXmlContent; it fails because enabling "Image flip" requires at the same time to provide a setting for the "Flip direction" (example : Left-right). IF "Mirror" is set to "Left/right" in the UI, "Image flip" turns on and "Flip direction" reflects what is set for the camera - and the integration and change the Flip direction settings. It can also disable the "Image flip" but once that's done, it can re-enable.

I propose we fix this in pyHik PR #161 ; this is cleaner for every pyHik user but for this bug to be closed requires a new pyHik release.
@mezz64 Should we get v0.5.1 out and bump hikvision to use that release?

Investigate

  • Iris (fixed) : not shown but the camera has fixed iris -> need to test w/ non-fixed iris

Note : I didn't test every single number, select, and switch but I did most of them.

Findings

  • "Spatial noise reduction level" and "Temporal noise reduction level" : shown but both are "unknown", can't change value => works fine only if "Noise reduction" is set to "Advanced".
  • Video Standard (select NTSC/PAL) in the UI is reported in hikvision as "Power line frequency 50hz/60hz" ... PAL being 50hz and NTSC 60hz.
  • Scheduled Image Settings lives in /ISAPI/System/Video/inputs/channels/1/motionDetectionExt - pyHik doesn't have it, so it's not exposed by hikvison.
  • Rotate (switch on/off) : not shown because it was missing in hikvision.

New PR

  • core : When enabling both Main and Substream , one of the "snapshot" was getting a 503; so on the camera device's page either the Main or Substream was showing the snapshot. PR 193948 share the same snapshot for both.
  • pyHik 161-image-flip

Changes to open core PRs following tests and reading the logs

  • When authentification fails, the log has been change to clearly state there's no more request going to the camera until re-authentication has been completed.
  • Added more DEBUG log; originally setting changes returning 200 weren't logging anything.
  • The camera can refuse the password on the event connection before setup ends. Setup now checks for that and asks you to log in again instead of sending the bad password; tests also added (found by Claude).
  • If the camera is being unloaded when it's time to ask you to log in again, it waits. If the unload fails, it still asks. The test is split in two (found by Claude).
  • "Spatial noise reduction level" and "Temporal noise reduction level" shows as Unavailable, previously Unknown, when Noise reduction isn't set to "Advanced".
  • "Video standard select PAL/NTSC" replaces "Power line frequency select 50hz/60hz".
  • Rotate (reported as corridor by the camera) is now supported.

Copilot

With the above new/change PRs, it raised a few comments; everything has been addressed... Copilot is a great coworker for Claude :D

@baylanger

Copy link
Copy Markdown
Contributor Author

@mezz64 @ptarjan officially done w/ testing , I just updated the comment of the tests I did with what I found and pushed last changes.

NVR tests might reveal possible issues ; otherwise if you guys are happy, this is likely ready to go out.

@baylanger

Copy link
Copy Markdown
Contributor Author

Took many breaks from prepping my long trip, and came up with missing items to add.

  1. Detection controls (enable/disable) - patches are ready and already tested on my camera.
  2. NVR "Holiday Mode" & "Alarm Input/Output" - patches ready but can't test.

Once the PRs are open I'll add them to the list in this comment.

@ptarjan

ptarjan commented Nov 24, 2026

Copy link
Copy Markdown
Contributor

@baylanger since the NVR parts can't be tested on your side, a reference that might help: the custom integration maciej-or/hikvision_next has been running on real NVRs for a while. Reading it at f6dac0da, three spots where it does something different from #163 / #162, offered as questions rather than blockers (mezz64's call):

  1. Holiday mode (NVR Read and set alarm inputs, outputs and holiday mode safely #163 set_holiday_enabled, pyhik/isapi.py at ad24caf, "only its enabled flag is changed"). hikvision_next, when enabling, also sets holidayMode=date with a date range and drops holidayWeek/holidayMonth (isapi/isapi.py:567-576). Its DS-7732NI-M4 fixture shows the factory default is holidayMode=month with start and end both 1/1 (tests/fixtures/devices/DS-7732NI-M4.json:452-477). Would flipping only enabled on a default NVR leave holiday mode effectively off outside Jan 1? It also gates on SysCap.isSupportHolidy (isapi.py:106).
  2. Alarm inputs on an NVR (NVR Read and set alarm inputs, outputs and holiday mode safely #163 uses /ISAPI/System/IO/inputs only, isapi.py:47 at ad24caf). hikvision_next uses /ISAPI/ContentMgmt/IOProxy/inputs/{id} for proxied inputs found via dynInputIOPortID in Event/triggers (isapi.py:262-266, 344-347). Its issue #206 reports a DS-7616NI-K2 returning 403 on System/IO/inputs/101 while the web UI uses the IOProxy path. Port counts come from SysCap.IOCap (isapi.py:113-114).
  3. Detections for cameras behind an NVR (Turn detections on and off without rewriting their settings #162 EVENT_ENDPOINTS, isapi.py:60-67 at 13a902e, always System/Video/inputs/channels/{channel}/...). hikvision_next uses /ISAPI/ContentMgmt/InputProxy/channels/{ch}/video/{slug} for proxied channels (isapi.py:337-350), and calls POST /ISAPI/System/mutexFunction?format=json before enabling when isSupportGetmutexFuncErrMsg is set (isapi.py:491).

Note that hikvision_next has no license file (its issue #384), so endpoints and quirks are fair to learn from, but the code shouldn't be copied.

@baylanger

Copy link
Copy Markdown
Contributor Author

@ptarjan indeed hikvision_next has no license, so I didn't peak at the code.

Getting XML output from a NVR would help code everything the right way. If #162 & #163 aren't complete, we can address them later. As I don't even have a NVR, honestly I don't need them :) but if we completed them, it might give me a reason to get a NVR ;)

@baylanger

Copy link
Copy Markdown
Contributor Author

@ptarjan I just realized I have the NVR developer guide ... PDF file. Claude could probably analyze it and figure it all out but I'm almost out of token for the rest of the week, currently at 95% :( Will have to wait 'til Saturday.

@baylanger

Copy link
Copy Markdown
Contributor Author

@ptarjan On the NVR parts... I uploaded to Claude a while ago the NVR developer guide, gotta wonder why he didn't look at it while writing the NVR code. Any good engineers would have done that ;)

Here's Claude response after asking to refer to the dev. guide and if we missed anything :) and I'm at 96% ... so I just ask Claude to work on the PRs.

Yes, I still have it: the NVR guide is in your uploads, along with the core protocol guide, and I checked both. The basics we built match the documented formats:

  • Output list, state and trigger: /ISAPI/System/IO/outputs, …//status (ioState active/inactive) and PUT …//trigger with high|low. The namespace we send matches too.
  • Input on/off: the enabled flag in /ISAPI/System/IO/inputs/, changed with only that value touched.
  • Port names: is read, which is the field the guide uses.

What we're missing, most important first:

  • Holiday mode isn't really a mode. In ISAPI, a holiday is a dated schedule entry (/ISAPI/System/Holidays/) with a name, a type (date, week or month) and a start and end. Recording and arming schedules use it through their holiday blocks. There's no device-wide "holiday mode": our switch only enables the first holiday, which does nothing outside its dates. The better shape is one switch per holiday, named after it (holidayName), with its dates shown on the entity. Also, the guide only documents reading a single holiday, so writing the whole list (what the old pyHik did, and what we kept) isn't documented here. I'd write each holiday through its own address.
  • The alarm I/O of cameras behind the NVR isn't handled. The guide says a camera's input ID on the NVR is channel × 100 + port (channel 2, input 3 is 203). Their outputs have IOType digitalChannel and come with their own endpoints (/ISAPI/ContentMgmt/IOProxy/inputs|outputs|status). Right now those would show up on the NVR's device as "Alarm input 203". They should be "Alarm input 3" on channel 2's device, read through the IOProxy endpoints.
  • Polling could be one request. GET /ISAPI/System/IO/status returns every input and output state in one list (and IOProxy/status does the same for the cameras). We currently send one request per port each minute.
  • No current input state. …/inputs//status (or the combined status above) gives each input's live state. That would make a proper "Alarm input N" binary sensor. Today you only get the event-stream "I/O alarm" sensor, which depends on the arming schedule and on the device reporting the event.

Things we could add but I'd leave out for now:

  • the input's normally-open/normally-closed setting (triggering high/low);
  • an output trigger with a duration in seconds;
  • pulse length and default state;
  • input arming schedules (/ISAPI/Event/schedules/inputs) and what each input triggers (/ISAPI/Event/triggers/IO-);
  • checking IOCap in /ISAPI/System/capabilities before asking for ports.

@baylanger baylanger closed this Nov 24, 2026
@baylanger baylanger reopened this Nov 24, 2026
@baylanger

Copy link
Copy Markdown
Contributor Author

If this can make your life easier I made a new release ; it includes all hikvision and pyHik PRs. In the release notes you will find the list of the included files as well as for the PRs.

I installed it earlier and did a few tests; everything seems to work just fine with a camera.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants