dahua icon indicating copy to clipboard operation
dahua copied to clipboard

Problem with Dahua Integration on NVR4104 – HTTPS & Event Handling Fix

Open HomeAuser opened this issue 1 year ago • 22 comments

Hi all,

I’m currently using Home Assistant version 2025.9.4 with the Dahua integration version 0.9.72.

I’m connecting to a Dahua DHI-NVR4104-P-4KS2, which has two cameras connected via PoE. I can successfully view the camera streams from both cameras in Home Assistant.

but I have the following Issue: Events are not being received in Home Assistant My goal is to use motion and other events from the NVR to trigger automations in Home Assistant.

Is there anyone who has successfully integrated a Dahua NVR Dahua DHI-NVR4104-P-4KS2 with Home Assistant using the Dahua integration?

I'm especially interested in: -How you got event streaming (like motion detection) to work? -Any configuration changes you had to make -Whether you had to modify the Dahua integration to support Digest Auth or multipart event streams

I’ve managed to get the camera streams working, and the NVR does send events (confirmed via browser), but Home Assistant throws a 500 error when trying to attach to the event stream.

Would love to hear from anyone who got this working — or has ideas on how to patch it. Thanks in advance!

Below is the information on what I have done so far.

Although the video streams work, no events are being received, and I see a persistent error in the logs:

Deze fout is ontstaan door een aangepaste integratie.

Logger: custom_components.dahua Bron: custom_components/dahua/client.py:741 integratie: Dahua (documentatie, problemen)

500, message='Internal Server Error', url='https://192.xxx.178.xxx/cgi-bin/eventManager.cgi?action=attach&codes=%5BVideoMotion,CrossLineDetection,AlarmLocal,VideoLoss,VideoBlind,AudioMutation,CrossRegionDetection,SmartMotionHuman,SmartMotionVehicle%5D&heartbeat=5'
Traceback (most recent call last):
  File "/config/custom_components/dahua/client.py", line 741, in stream_events
    response.raise_for_status()
    ~~~~~~~~~~~~~~~~~~~~~~~~~^^
  File "/usr/local/lib/python3.13/site-packages/aiohttp/client_reqrep.py", line 629, in raise_for_status
    raise ClientResponseError(
    ...<5 lines>...
)
aiohttp.client_exceptions.ClientResponseError: 500, message='Internal Server Error', url='https://192.xxx.178.xxx/cgi-bin/eventManager.cgi?action=attach&codes=%5BVideoMotion,CrossLineDetection,AlarmLocal,VideoLoss,VideoBlind,AudioMutation,CrossRegionDetection,SmartMotionHuman,SmartMotionVehicle%5D&heartbeat=5'

What I’ve tested so far

  1. Accessing the NVR directly via browser, I confirmed that the event stream endpoint works correctly:

    https:///cgi-bin/eventManager.cgi?action=attach&codes=[VideoMotion,...]&heartbeat=5

    I receive a multipart stream with actual event data, e.g.:

    Code=VideoMotion;action=Stop;index=1;data={

    "Id": [0], "LocaleTime": "2025-10-03 13:05:40", "MachineName": "xxxxxxAC427", "Name": "Achter", "RegionName": ["Region1"], "SmartMotionEnable": true, "UTC": 1759493140.0 }

This means that the NVR uses:

  • Digest authentication
  • Heartbeat mechanism (heartbeat=5)
  • multipart/x-mixed-replace content type with --myboundary separating blocks
  • JSON data + periodic heartbeats (Content-Length: 9) to keep the stream alive

🧠 Conclusions so far

  • ✅ The NVR accepts the request with Digest Auth and returns valid multipart data
  • ✅ The stream contains real events and heartbeats, just like what you'd see in the browser
  • ❌ The Home Assistant Dahua integration (aiohttp/client.py) throws a 500 error — indicating it is not parsing the multipart stream correctly

💡 Suggested solution (based on testing + AI analysis):

The Home Assistant Dahua integration should be updated to:

  • Use Digest Auth properly
  • Handle the multipart/x-mixed-replace stream correctly: -Separate boundary blocks
    • Parse JSON data
    • Ignore heartbeats
    • Pass events to Home Assistant

Once that’s implemented, the 500 Internal Server Error should disappear, and events should be visible in HA just as they are in the terminal or browser.


🛠️ Current status

I’ve already tried modifying parts of client.py to account for this, but I’ve run into issues.

I would like to Ask if someone could help me implement proper multipart stream parsing in the Dahua integration. Or, if the developer(s) could consider updating the integration to support NVR devices like the NVR4104, which use this event streaming format

HomeAuser avatar Oct 03 '25 11:10 HomeAuser

It would be great if rroller would further develop its Dahua integration and solve current problems, and I would love that too, but based on the last two years or so, I think that's unfortunately not going to happen.

I don't use the Dahua integration anymore because, in conjunction with my Dahua NVR2108-I, for example, it spams the NVR log with login/logoff messages every second. Therefore, I switched to the HA Onvif integration a while ago, which almost completely supports the Dahua NVR and works quite smoothly. Only the AI ​​features of my NVR (person and vehicle detection) are not supported by the HA Onvif integration. However, the other detection types (IVS, line detection, motion, etc.) are supported without any problems.

Image

So, if you don't absolutely need or want person and vehicle detection, I recommend integrating your NVR with HA via the HA Onvif integration, if you haven't already done so.

Note: Currently, the HA Onvif integration still has the issue that the sensors are all listed under the same name after the initial setup and don't have a channel number. https://github.com/home-assistant/core/issues/142400 This means that you currently have to manually adjust the sensor names yourself, but this issue should likely be resolved in the foreseeable future. https://github.com/home-assistant/core/pull/153505

Once again: If rroller were to further develop its integration, that might be a reason for me to use it again, and I would very much welcome it.

JimGermany avatar Oct 03 '25 14:10 JimGermany

Speaking of missing features, the ONVIF integration misses switch entities for the output relays. It should be possible to add support for that though.

felipecrs avatar Oct 04 '25 17:10 felipecrs

I don't use the Dahua integration anymore because, in conjunction with my Dahua NVR2108-I, for example, it spams the NVR log with login/logoff messages every second. Therefore, I switched to the HA Onvif integration a while ago, which almost completely supports the Dahua NVR and works quite smoothly.

How did you configure the integration to work with the NVR? If I try the camera addresses via the NVR, i.e. http://nvr.local:10080 for the first camera the integration says it can't connect and if I try the NVR itself, http://nvr.local, it says there are no H.264 streams available. It's a 4108 so essentially the same as yours.

fencepost-error avatar Nov 01 '25 10:11 fencepost-error

Answering my own question, it looks like the ONVIF integration can't work with H.265 streams, but if you set at least one substream to H.264 it'll see them. Now to figure out how to edit the camera names via the integration so I don't just have a string of identical sensor names...

fencepost-error avatar Nov 01 '25 11:11 fencepost-error

it looks like the ONVIF integration can't work with H.265 streams,

That's right, and for compatibility reasons I only use H.264 here anyway, and I don't need 4k streams under HA, which would then be compressed better/more strongly via H.265. :-) But of course, it also depends on which Dahua camera model you're using and how many and what kind of substreams that camera model offers.

Dahua SD49225XA-HNR (3 Streams and Sub-Stream 2 with H.264 and max. 1920x1080) Image

Imou Cruiser Dual (only 2 Stream and Sub-Stream 1 with H.264 and only max 640x480)

Image

JimGermany avatar Nov 01 '25 11:11 JimGermany

Now to figure out how to edit the camera names via the integration so I don't just have a string of identical sensor names...

I fixed that, try the Home Assistant 2025.11 beta.

felipecrs avatar Nov 01 '25 14:11 felipecrs

That's right, and for compatibility reasons I only use H.264 here anyway

Out of curiosity, what compatibility reason exactly are you concerned about?

felipecrs avatar Nov 01 '25 14:11 felipecrs

Answering my own question, it looks like the ONVIF integration can't work with H.265 streams, but if you set at least one substream to H.264 it'll see them.

That sounds like a bug. I'd recommend filling a bug report in HA core.

felipecrs avatar Nov 01 '25 14:11 felipecrs

Hi :-)

That sounds like a bug.

No it's not a bug is's a "feature". :-))

This integration will add entities for all compatible profiles with the video encoding set to H.264.

https://www.home-assistant.io/integrations/onvif/#configuration-notes

Edit: I haven't tried this in a long time, but so far it has been the case that H.265 streams are not recognized by the Onvif integration and therefore not displayed.

JimGermany avatar Nov 01 '25 14:11 JimGermany

Oh. 😅

felipecrs avatar Nov 01 '25 14:11 felipecrs

Hi :-)

That sounds like a bug.

No it's not a bug is's a "feature". :-))

This integration will add entities for all compatible profiles with the video encoding set to H.264.

I've just submitted a PR to make this more explicit in the docs, it's obvious in hindsight when things fail to work and after you've spent awhile suspecting network problems and the like, but not immediately obvious from a first read that it has to be H.264 and only H.264.

fencepost-error avatar Nov 02 '25 10:11 fencepost-error

Now to figure out how to edit the camera names via the integration so I don't just have a string of identical sensor names...

I fixed that, try the Home Assistant 2025.11 beta.

Thanks! Is that fixed as part of HA (so it'll also fix the problem in the ONVIF integration, which is what I'm using since I couldn't get the Dahua one to work) or in the Dahua integration? And if it's in HA, is it the Naming entities on your dashboard or something else?

fencepost-error avatar Nov 02 '25 11:11 fencepost-error

  • https://github.com/home-assistant/core/pull/153505

felipecrs avatar Nov 02 '25 11:11 felipecrs

Nice, thanks!

fencepost-error avatar Nov 02 '25 11:11 fencepost-error

I’ve made some progress and managed to get the integration working for the NVR4101.

🧩 Dahua NVR HTTPS & Event Handling Fix

Summary

The Dahua integration failed to control or retrieve data from my NVR (Dahua NVR4101) when HTTPS was enabled. When using port 443, every request returned a 500 Internal Server Error. Using port 80 (HTTP) worked, but HTTPS is preferred for secure communication.


Root Cause

The Dahua integration uses a custom DigestAuth class for authentication. However, the internal HTTP client (aiohttp) verified SSL certificates by default.

Most Dahua NVRs and cameras use self-signed SSL certificates, which fail this verification, resulting in all HTTPS API calls (like /cgi-bin/configManager.cgi) returning 500 or 403 errors.


Fix Implemented

In the file:

custom_components/dahua/digest.py

inside the request() method of the DigestAuth class, we modified the aiohttp request to ignore SSL certificate validation:

response = await self.session.request(
    method,
    url,
    headers=headers,
    ssl=False,  # <--- added line to allow self-signed certificates
    **kwargs
)

✅ Result: This change allows the Dahua integration to successfully connect and authenticate with NVRs that have HTTPS enabled but use self-signed SSL certificates.

After this fix:

  • Home Assistant connects to the NVR over HTTPS
  • Camera feeds load normally
  • All standard event types (motion, crossline, video blind, etc.) are working

Smart Event Handling Extension

I have also extended the event processing logic to add support for advanced AI-based event types such as SmartMotionHuman and SmartMotionVehicle.

Added logic inside the event loop (before the main Dahua event processing):

# --- Extra ChatGPT sensor logic ---
try:
    data = event.get("data", {})
    code = event.get("Code", "")
    action = event.get("action", "")

    # SmartMotionHuman / SmartMotionVehicle
    if code == "VideoMotion" and data.get("SmartMotionEnable", False):
        key = self.get_event_key("extra_chatgpt_smart_motion_alarm")
        listener = self._dahua_event_listeners.get(key)
        if listener:
            if action == "Start":
                self._dahua_event_timestamp[key] = int(time.time())
            elif action == "Stop":
                self._dahua_event_timestamp[key] = 0
            listener()

    # CrossLineDetection (Human / Vehicle)
    elif code == "CrossLineDetection":
        obj_type = data.get("Object", {}).get("ObjectType", "").lower()
        ...

This adds additional event sensors:

  • extra_chatgpt_smart_motion_alarm
  • extra_chatgpt_crossline_alarm_human
  • extra_chatgpt_crossline_alarm_vehicle

Why SmartMotionHuman and SmartMotionVehicle Don’t Trigger

After investigation, the NVR does not forward separate SmartMotionHuman or SmartMotionVehicle codes via the eventManager.cgi stream. Instead, these detections are wrapped inside the regular VideoMotion event with an internal flag:

{
  "Code": "VideoMotion",
  "action": "Start",
  "data": {
    "SmartMotionEnable": true
  }
}

The ObjectType (“human” or “vehicle”) field only appears in IVS event types such as CrossLineDetection or Intrusion. Therefore:

  • Human and Vehicle detection can be distinguished for IVS events.
  • SmartMotion events only expose a generic motion trigger.

Final Results

✅ Integration now works over HTTPS ✅ Live video streams load correctly ✅ All standard events (motion, IVS, video blind) work ⚠️ SmartMotionHuman/Vehicle don’t send distinct events — this is a firmware limitation


Recommendation

If HTTPS must remain enabled on the NVR:

  • Keep the ssl=False change in digest.py
  • Use port 443
  • Optionally, create a proper SSL certificate to avoid skipping verification

Can these adjustments be incorporated into the integration so that they are included by default in a future version, and I no longer have to correct them manually?

HomeAuser avatar Nov 07 '25 10:11 HomeAuser

First off: I think it's great that you're continuing to explore this topic and what you've discovered!

However, I'm not sure about the following point.

Why SmartMotionHuman and SmartMotionVehicle Don’t Trigger

After investigation, the NVR does not forward separate SmartMotionHuman or SmartMotionVehicle codes via the eventManager.cgi stream. Instead, these detections are wrapped inside the regular VideoMotion event with an internal flag:

{ "Code": "VideoMotion", "action": "Start", "data": { "SmartMotionEnable": true } } The ObjectType (“human” or “vehicle”) field only appears in IVS event types such as CrossLineDetection or Intrusion. Therefore:

* Human and Vehicle detection can be distinguished for IVS events.

* SmartMotion events only expose a generic motion trigger.

Because: Yes, SMD only works in conjunction with and with MD activated, but the alarm object is still "Person".

Image Image

This means the alarm type is Motion Detection, but the alarm object is "Person". But you've certainly delved into this much more deeply than I have, so this post is just meant as information.

I also can't rule out the possibility that this might be different with a different NVR running a different firmware version. My NVR2108-I has been end-of-life for quite some time, and the last available firmware version for it dates back to July 2024.

Image

Thanks again for addressing these issues, and I hope rroller takes a look at this and then incorporates any necessary changes into his code.

JimGermany avatar Nov 07 '25 15:11 JimGermany

You're absolutely right — the Dahua NVR UI does show whether an object is a person or vehicle, since the NVR performs full AI classification internally.

However, the information that the integration (and Home Assistant) receives comes from the event stream API:

/cgi-bin/eventManager.cgi?action=attach&codes=[All] This stream is limited in what it reports. For Smart Motion Detection, the NVR only emits a generic event like:

{ "Code": "VideoMotion", "action": "Start", "data": { "SmartMotionEnable": true } } It does not include the ObjectType field (e.g. "human" or "vehicle") that you can see in the NVR’s on-screen logs or via the Smart Plan AI overlays.

The detailed AI classification (human/vehicle) is available only in the IVS event types, such as:

CrossLineDetection

Intrusion

RegionEntrance

etc.

These IVS events do include ObjectType, for example:

{ "Code": "CrossLineDetection", "data": { "Object": { "ObjectType": "Human" } } } So while the NVR UI has access to the complete detection context, the HTTP event stream that Home Assistant subscribes to simply doesn’t expose that metadata for Smart Motion events.

HomeAuser avatar Nov 09 '25 12:11 HomeAuser

So while the NVR UI has access to the complete detection context, the HTTP event stream that Home Assistant subscribes to simply doesn’t expose that metadata for Smart Motion events.

Yes, that's what I thought too. :-) BTW: Also the playback behavior of AI recordings differs on my NVR between SMD and IVS AI recordings and was apparently not implemented uniform by Dahua.

One more question: With your NVR and the Dahua integration, do you also have the problem that login and logout events are recorded in the NVR log almost every second? I've had this problem for a very long time, and it's the reason why I no longer use the Dahua integration.

JimGermany avatar Nov 09 '25 12:11 JimGermany

So while the NVR UI has access to the complete detection context, the HTTP event stream that Home Assistant subscribes to simply doesn’t expose that metadata for Smart Motion events.

Yes, that's what I thought too. :-) BTW: Also the playback behavior of AI recordings differs on my NVR between SMD and IVS AI recordings and was apparently not implemented uniform by Dahua.

One more question: With your NVR and the Dahua integration, do you also have the problem that login and logout events are recorded in the NVR log almost every second? I've had this problem for a very long time, and it's the reason why I no longer use the Dahua integration.

HomeAuser avatar Mar 25 '26 19:03 HomeAuser

Sorry for The late reaction. Yes i have that also, i did not noticed that earlier. I dont know of thats a problem for The NVR of HA. Can someone answer that question?

HomeAuser avatar Mar 25 '26 19:03 HomeAuser