Hikvision Doorbell / Videointercom integration

I use this:

  - service: shell_command.asterisk_abort_call
    data_template:
      extension: XXXX
      ami_password: !secret ami_password

Shell:

asterisk_abort_call: python3 /config/python_scripts/hangup_call.py {{extension}} {{ami_password}}

and script:

import sys
import telnetlib
import re

if len(sys.argv) == 2:
   sys.exit("ERROR: No Asterisk Extension Number passed in as argument and/or AMI password  Terminating.")

host = "localhost" 				#IP Address of Asterisk Server
port = 5038 						#Port of Asterisk Server.  AMI default port is 5038.
user = "admin" 				#username for Asterisk AMI as configured in /etc/asterisk/manager_additional.conf
#password = "xxx" #password for Asterisk AMI as configured in /etc/asterisk/manager_additional.conf
password = sys.argv[2]

debug = 0					#Set default debug mode.

actionindex = 1						#ActionID index required by Asterisk AMI protocol.  Always starts at 1 and increments with each command.



extension = sys.argv[1]

print("Trying to hangup Extension ",str(extension))

#Connect to Asterisk AMI
tn = telnetlib.Telnet(host,port)

#Wait till asterisk responds
out = tn.read_until('Asterisk Call Manager'.encode('ascii'),2)
if debug: print("RECEIVED:",out)

#Send Login Info
message = "Action: Login\nActionID: " + str(actionindex) + "\nUsername: " + user + "\nSecret: " + password + "\nEvents: off\n\n"
if debug: print("SENT:\n",message)
tn.write(message.encode('ascii'))
actionindex = actionindex + 1

#Wait till AMI responds
out = tn.read_until(b"Message: Authentication accepted",2)
if debug: print("RECEIVED:\n",out)

#Send Status Request
message = "Action: Status\nActionID: " + str(actionindex) + "\n\n"
if debug: print("SENT:\n",message)
tn.write(message.encode('ascii'))
actionindex = actionindex + 1

#Wait till AMI responds
out = tn.read_until(b"Event: StatusComplete",2)
if debug: print("RECEIVED:",out)

#Search for a SIP channel matching the extension we are looking for
matchtext = 'Channel: PJSIP/' + str(extension) + '-........'
match = re.search(matchtext.encode('ascii'), out)
if match:
   result = match.group()
   #channel = result.lstrip('Channel: ')
   channel = result.lstrip(b'Channel: ')
   print("Extension ",str(extension)," is active. Found Channel ",channel)
   message = "Action: Hangup\nChannel: " + str(channel.decode()) + "\nActionID: " + str(actionindex) + "\n\n"
   #message = "Action: Hangup\nChannel: " + channel + "\nActionID: " + str(actionindex) + "\n\n"
   if debug: print("SENT:\n",message)
   tn.write(message.encode('ascii'))
   actionindex = actionindex + 1
   out = tn.read_until(b"Hungup",2)
   if debug: print("RECEIVED:",out)
else:
   print("No active Asterisk Channel for Extension ",str(extension)," was found")	

#Logoff
message = "Action: Logoff\nActionID: " + str(actionindex) + "\n\n"
if debug: print("SENT:\n",message)
tn.write(message.encode('ascii'))

#Wait till AMI responds
out = tn.read_until(b"fish",2)
if debug: print("RECEIVED:",out)
print("Done. Terminating.")

How can I use an external MQTT-Service? I have one, but not on the same Host as HA.

Hey, can you try to add this config below the doorbell config?

# Define the following options to enable the MQTT integration
# mqtt:
#   host: localhost
#   port: 1883
#   # Optionals settings:
#   ssl: <boolean>  # Set to true to enable SSL
#   username: <user>
#   password: <password>
1 Like

Hi! Thanks for this great work!
I have an DS-KV6113-WPE1(B) and installed the latest BETA in Homeassistant.

After installing, configuring and rebooting the log is showing this:

2023-03-14 13:05:22.038 | DEBUG    | config:mqtt_config_from_supervisor:36 - Requesting MQTT service configuration to supervisor
2023-03-14 13:05:22.051 | DEBUG    | __main__:main:26 - Importing Hikvision SDK
2023-03-14 13:05:22.054 | INFO     | sdk.utils:loadSDK:44 - Using OS: Linux with architecture: x86_64
2023-03-14 13:05:22.054 | DEBUG    | sdk.utils:loadSDK:57 - Loading library from lib-amd64/libhcnetsdk.so
2023-03-14 13:05:22.064 | DEBUG    | __main__:main:30 - Hikvision SDK loaded
2023-03-14 13:05:22.064 | DEBUG    | sdk.utils:setupSDK:86 - Initializing SDK
loop[2] find 2 mac and 0 ip
2023-03-14 13:05:22.120 | DEBUG    | sdk.utils:setupSDK:100 - SDK initialized
2023-03-14 13:05:22.121 | DEBUG    | doorbell:__init__:41 - Setting up doorbell: Deurbel
2023-03-14 13:05:22.121 | DEBUG    | doorbell:authenticate:48 - Logging into doorbell
2023-03-14 13:05:22.205 | ERROR    | __main__:<module>:96 - Error while logging into Deurbel: The IP is be locked. Error code:153

The config looks like:

- name: Deurbel
  ip: 192.168.0.104
  username: *
  password: *

I rebooted the doorbell and waited more then 30min.

What could be the cause of the Error code:153 ?

Locked, probaly means you are not passing correct credentials with user “admin” / ???

The “watchdog” service is default enabled on the addon, so when the addon stops cause of failed credentials it will restart again and again and is hammering your device

So if you test, best to disable the watchdog service

Thanks!
I changed the password and then back to the original password. Then the error dissapeared.

Looks like the user-DB on the doorbell needed a kick.

1 Like

I could just build 1 automation for each doorbell

Have you considered a single automation defining multiple triggers in it? You could for instance identify each device with separate trigger_ids, and act accordingly on each. I had a quick glance at the docs and found some template functions about devices, maybe they could be used to extract additional attributes for your use case?
I made a quick test and found out the following when templating {{ trigger }} inside an automation:

  trigger:
    id: "1"
    idx: "1"
    alias: null
    platform: mqtt
    topic: hmd/device_automation/Outdoor-unit/motion_detection/state
    payload: ""
    qos: 0
    description: mqtt topic hmd/device_automation/Outdoor-unit/motion_detection/state

From the add-on configuration

The name in the add-on are used internally to identify the various entities and associate them to the correct device. I think that changing it may cause separate entities to be generated in HA. In case you have old sensors showing up as unavailable, I suggest deleting the device from the HA UI (from HA UI, in the Device info page → three dots menu → Delete), then restarting the add-on to re-create the new device + sensors with the correct names.

1 Like

Спасибо за интеграцию. DoorBell Beta. Очень классная интеграция все работает. Но все же как заставить DS-KH6320 показывать встроенные датчики и сцены сигнализации?

Thanks for the integration. Doorbell Beta. Very cool integration everything works. But still, how to make DS-KH6320 show built-in sensors and alarm scenes?

But still, how to make DS-KH6320 show built-in sensors and alarm scenes?

Are you referring to the alarm inputs? From the Hikvision technical page I see this for your device:

Alarm Input
8-ch alarm inputs

I suppose they should already be visible in HA as device triggers, if the device generates some type of events for them. Have you tried triggering any of the alarm inputs and see in the add-on logs if anything pops up?

How can I install it and the MQTT? I’m using Scrypted to export my Hikvision doorbell to HomeKit, but Scrypted doesn’t detect the button status or change from ringing to idle (necessary to two-way audio works).

Is it possible the MQTT trigger a webhook from Scrypted to change the doorbell status to ring? And what you guys could do to stop ringing when you answer somewhere than on HikConnect?

Hey, since the MQTT is out, the names of sensors have been changed, also previously the state was like on or off for the binary…

For callsensor, as example: sensor.ds_kd8003_call_state , it’s now idle/ringing/dismissed … So you need to build your automations on that state now… As you can see, it’s still a sensor

Normally if you answer ln Hikconnect, it should stop ringing other devices, I think that’s a bug on your hardware, this addon can’t help wit that… Cause if you would send a reject, it would also drop your call on Hikconnect… I have read this issue before on other forums

See last reply here, maybe that’s your issue too?

1 Like

Как мне посмотреть как устройство выдает device trigger s?

How can I see if the device emits device trigger s?


Может есть какаято инструкция?

Maybe there is some instruction?

In the last tab “logs”, there you can see what has been triggered

I have a strange new Problem. I had to reinstall the Plugin but now i get these strange Error:

2023-03-15 15:44:45.788 ERROR (MainThread) [homeassistant.components.hassio] Failed to to call /addons/aff2db71_hikvision_doorbell_beta/install - Can't install ghcr.io/pergolafabio/hikvision-doorbell:3.0.0-beta.13: 500 Server Error for http+docker://localhost/v1.41/images/create?tag=3.0.0-beta.13&fromImage=ghcr.io%2Fpergolafabio%2Fhikvision-doorbell&platform=linux%2Famd64: Internal Server Error ("Head "https://ghcr.io/v2/pergolafabio/hikvision-doorbell/manifests/3.0.0-beta.13": received unexpected HTTP status: 503 Service Unavailable")

Вот что показывает журнал если замкнутый третий тревожный выход.

This is what the log shows if the third alarm output is closed

[2023-03-15 18:30:53.016][DBG] Alarm chan [0] recv timeout[2]!
2023-03-15 18:31:21.714 | DEBUG | event:_handle_callback:192 - Callback invoked from SDK
2023-03-15 18:31:21.715 | DEBUG | event:_invoke_handlers:166 - Invoking 2 handlers
2023-03-15 18:31:21.716 | INFO | event:video_intercom_alarm:109 - Video intercom alarm from DoorStation
Task exception was never retrieved
future: <Task finished name=‘MQTT’ coro=<MQTTHandler.video_intercom_alarm() done, defined at /app/mqtt.py:216> exception=KeyError(<doorbell.Doorbell object at 0x7f0f3cca6860>)>
Traceback (most recent call last):
File “/app/mqtt.py”, line 225, in video_intercom_alarm
call_sensor = cast(Sensor, self._sensors[doorbell][‘call’])
KeyError: <doorbell.Doorbell object at 0x7f0f3cca6860>
[2023-03-15 18:31:21.714][INF] Alarm[1] IP[10.0.0.10] data_len[568] alarm_len[568] status[430]
[2023-03-15 18:31:23.050][DBG] Alarm chan [0] recv timeout[2]!

Вот что показывает журнал если замкнутый третий тревожный выход.

This is what the log shows if the third alarm output is closed

[2023-03-15 18:30:53.016][DBG] Alarm chan [0] recv timeout[2]!
2023-03-15 18:31:21.714 | DEBUG | event:_handle_callback:192 - Callback invoked from SDK
2023-03-15 18:31:21.715 | DEBUG | event:_invoke_handlers:166 - Invoking 2 handlers
2023-03-15 18:31:21.716 | INFO | event:video_intercom_alarm:109 - Video intercom alarm from DoorStation
Task exception was never retrieved
future: <Task finished name=‘MQTT’ coro=<MQTTHandler.video_intercom_alarm() done, defined at /app/mqtt.py:216> exception=KeyError(<doorbell.Doorbell object at 0x7f0f3cca6860>)>
Traceback (most recent call last):
File “/app/mqtt.py”, line 225, in video_intercom_alarm
call_sensor = cast(Sensor, self._sensors[doorbell][‘call’])
KeyError: <doorbell.Doorbell object at 0x7f0f3cca6860>
[2023-03-15 18:31:21.714][INF] Alarm[1] IP[10.0.0.10] data_len[568] alarm_len[568] status[430]
[2023-03-15 18:31:23.050][DBG] Alarm chan [0] recv timeout[2]!

Помогите понять как создать датчики?

Help to understand how to create sensors?

Hi, it it only alarm input 3 and … That’s giving issues?

Can you try to setup manual output_relays?

There is something strange going on in the code handling the video intercom alarm. Can you please open an issue in our Github page to better diagnose the problem?

Hi , seems GitHub is having issues , see here… I think you can just maybe try again later…

1 Like

that dosnt work here:

023-03-15 22:59:48.385 | DEBUG    | config:mqtt_config_from_supervisor:36 - Requesting MQTT service configuration to supervisor
2023-03-15 22:59:48.390 | ERROR    | config:mqtt_config_from_supervisor:40 - MQTT service not available
Traceback (most recent call last):
  File "/app/main.py", line 91, in <module>
    asyncio.run(main())
  File "/usr/local/lib/python3.10/asyncio/runners.py", line 44, in run
    return loop.run_until_complete(main)
  File "/usr/local/lib/python3.10/asyncio/base_events.py", line 649, in run_until_complete
    return future.result()
  File "/app/main.py", line 21, in main
    config.load()
  File "/usr/local/lib/python3.10/site-packages/goodconf/__init__.py", line 144, in load
    super().__init__()
  File "pydantic/env_settings.py", line 39, in pydantic.env_settings.BaseSettings.__init__
  File "pydantic/main.py", line 340, in pydantic.main.BaseModel.__init__
  File "pydantic/main.py", line 1067, in pydantic.main.validate_model
  File "pydantic/fields.py", line 439, in pydantic.fields.ModelField.get_default
  File "/app/config.py", line 41, in mqtt_config_from_supervisor
    raise RuntimeError("This addon need the mosquitto broker to work correctly. Please see the Documentation tab for details.")
RuntimeError: This addon need the mosquitto broker to work correctly. Please see the Documentation tab for details.