2 * Copyright (c) 2010-2021 Contributors to the openHAB project
4 * See the NOTICE file(s) distributed with this work for additional
7 * This program and the accompanying materials are made available under the
8 * terms of the Eclipse Public License 2.0 which is available at
9 * http://www.eclipse.org/legal/epl-2.0
11 * SPDX-License-Identifier: EPL-2.0
13 package org.openhab.binding.ipcamera.internal;
15 import static org.openhab.binding.ipcamera.internal.IpCameraBindingConstants.*;
17 import java.nio.charset.StandardCharsets;
18 import java.util.ArrayList;
20 import org.eclipse.jdt.annotation.NonNullByDefault;
21 import org.eclipse.jdt.annotation.Nullable;
22 import org.openhab.binding.ipcamera.internal.handler.IpCameraHandler;
23 import org.openhab.core.library.types.OnOffType;
24 import org.openhab.core.library.types.StringType;
25 import org.openhab.core.thing.ChannelUID;
26 import org.openhab.core.thing.binding.ThingHandler;
27 import org.openhab.core.types.Command;
28 import org.openhab.core.types.RefreshType;
29 import org.slf4j.Logger;
30 import org.slf4j.LoggerFactory;
32 import io.netty.buffer.ByteBuf;
33 import io.netty.buffer.Unpooled;
34 import io.netty.channel.ChannelDuplexHandler;
35 import io.netty.channel.ChannelHandlerContext;
36 import io.netty.handler.codec.http.DefaultFullHttpRequest;
37 import io.netty.handler.codec.http.FullHttpRequest;
38 import io.netty.handler.codec.http.HttpHeaderNames;
39 import io.netty.handler.codec.http.HttpHeaderValues;
40 import io.netty.handler.codec.http.HttpMethod;
41 import io.netty.handler.codec.http.HttpVersion;
42 import io.netty.util.ReferenceCountUtil;
45 * The {@link HikvisionHandler} is responsible for handling commands, which are
46 * sent to one of the channels.
48 * @author Matthew Skinner - Initial contribution
52 public class HikvisionHandler extends ChannelDuplexHandler {
53 private final Logger logger = LoggerFactory.getLogger(getClass());
54 private IpCameraHandler ipCameraHandler;
55 private int nvrChannel;
56 private int lineCount, vmdCount, leftCount, takenCount, faceCount, pirCount, fieldCount;
58 public HikvisionHandler(ThingHandler handler, int nvrChannel) {
59 ipCameraHandler = (IpCameraHandler) handler;
60 this.nvrChannel = nvrChannel;
63 private void processEvent(String content) {
64 // some cameras use <dynChannelID> or <channelID> and NVRs use channel 0 to say all channels
65 if (content.contains("hannelID>" + nvrChannel) || content.contains("<channelID>0</channelID>")) {
66 final int debounce = 3;
67 String eventType = Helper.fetchXML(content, "", "<eventType>");
70 if (content.contains("<eventState>inactive</eventState>")) {
79 ipCameraHandler.motionDetected(CHANNEL_PIR_ALARM);
82 case "attendedBaggage":
83 ipCameraHandler.setChannelState(CHANNEL_ITEM_TAKEN, OnOffType.ON);
84 takenCount = debounce;
86 case "unattendedBaggage":
87 ipCameraHandler.setChannelState(CHANNEL_ITEM_LEFT, OnOffType.ON);
91 ipCameraHandler.setChannelState(CHANNEL_FACE_DETECTED, OnOffType.ON);
95 ipCameraHandler.motionDetected(CHANNEL_MOTION_ALARM);
98 case "fielddetection":
99 ipCameraHandler.motionDetected(CHANNEL_FIELD_DETECTION_ALARM);
100 fieldCount = debounce;
102 case "linedetection":
103 ipCameraHandler.motionDetected(CHANNEL_LINE_CROSSING_ALARM);
104 lineCount = debounce;
107 logger.debug("Unrecognised Hikvision eventType={}", eventType);
113 // This handles the incoming http replies back from the camera.
115 public void channelRead(@Nullable ChannelHandlerContext ctx, @Nullable Object msg) throws Exception {
116 if (msg == null || ctx == null) {
120 String content = msg.toString();
121 logger.trace("HTTP Result back from camera is \t:{}:", content);
122 if (content.startsWith("--boundary")) {// Alarm checking goes in here//
123 processEvent(content);
125 String replyElement = Helper.fetchXML(content, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>", "<");
126 switch (replyElement) {
127 case "MotionDetection version=":
128 ipCameraHandler.storeHttpReply(
129 "/ISAPI/System/Video/inputs/channels/" + nvrChannel + "01/motionDetection", content);
130 if (content.contains("<enabled>true</enabled>")) {
131 ipCameraHandler.setChannelState(CHANNEL_ENABLE_MOTION_ALARM, OnOffType.ON);
132 } else if (content.contains("<enabled>false</enabled>")) {
133 ipCameraHandler.setChannelState(CHANNEL_ENABLE_MOTION_ALARM, OnOffType.OFF);
136 case "IOInputPort version=":
137 ipCameraHandler.storeHttpReply("/ISAPI/System/IO/inputs/" + nvrChannel, content);
138 if (content.contains("<enabled>true</enabled>")) {
139 ipCameraHandler.setChannelState(CHANNEL_ENABLE_EXTERNAL_ALARM_INPUT, OnOffType.ON);
140 } else if (content.contains("<enabled>false</enabled>")) {
141 ipCameraHandler.setChannelState(CHANNEL_ENABLE_EXTERNAL_ALARM_INPUT, OnOffType.OFF);
143 if (content.contains("<triggering>low</triggering>")) {
144 ipCameraHandler.setChannelState(CHANNEL_TRIGGER_EXTERNAL_ALARM_INPUT, OnOffType.OFF);
145 } else if (content.contains("<triggering>high</triggering>")) {
146 ipCameraHandler.setChannelState(CHANNEL_TRIGGER_EXTERNAL_ALARM_INPUT, OnOffType.ON);
149 case "LineDetection":
150 ipCameraHandler.storeHttpReply("/ISAPI/Smart/LineDetection/" + nvrChannel + "01", content);
151 if (content.contains("<enabled>true</enabled>")) {
152 ipCameraHandler.setChannelState(CHANNEL_ENABLE_LINE_CROSSING_ALARM, OnOffType.ON);
153 } else if (content.contains("<enabled>false</enabled>")) {
154 ipCameraHandler.setChannelState(CHANNEL_ENABLE_LINE_CROSSING_ALARM, OnOffType.OFF);
157 case "TextOverlay version=":
158 ipCameraHandler.storeHttpReply(
159 "/ISAPI/System/Video/inputs/channels/" + nvrChannel + "/overlays/text/1", content);
160 String text = Helper.fetchXML(content, "<enabled>true</enabled>", "<displayText>");
161 ipCameraHandler.setChannelState(CHANNEL_TEXT_OVERLAY, StringType.valueOf(text));
163 case "AudioDetection version=":
164 ipCameraHandler.storeHttpReply("/ISAPI/Smart/AudioDetection/channels/" + nvrChannel + "01",
166 if (content.contains("<enabled>true</enabled>")) {
167 ipCameraHandler.setChannelState(CHANNEL_ENABLE_AUDIO_ALARM, OnOffType.ON);
168 } else if (content.contains("<enabled>false</enabled>")) {
169 ipCameraHandler.setChannelState(CHANNEL_ENABLE_AUDIO_ALARM, OnOffType.OFF);
172 case "IOPortStatus version=":
173 if (content.contains("<ioState>active</ioState>")) {
174 ipCameraHandler.setChannelState(CHANNEL_EXTERNAL_ALARM_INPUT, OnOffType.ON);
175 } else if (content.contains("<ioState>inactive</ioState>")) {
176 ipCameraHandler.setChannelState(CHANNEL_EXTERNAL_ALARM_INPUT, OnOffType.OFF);
179 case "FieldDetection version=":
180 ipCameraHandler.storeHttpReply("/ISAPI/Smart/FieldDetection/" + nvrChannel + "01", content);
181 if (content.contains("<enabled>true</enabled>")) {
182 ipCameraHandler.setChannelState(CHANNEL_ENABLE_FIELD_DETECTION_ALARM, OnOffType.ON);
183 } else if (content.contains("<enabled>false</enabled>")) {
184 ipCameraHandler.setChannelState(CHANNEL_ENABLE_FIELD_DETECTION_ALARM, OnOffType.OFF);
187 case "ResponseStatus version=":
188 ////////////////// External Alarm Input ///////////////
189 if (content.contains(
190 "<requestURL>/ISAPI/System/IO/inputs/" + nvrChannel + "/status</requestURL>")) {
191 // Stops checking the external alarm if camera does not have feature.
192 if (content.contains("<statusString>Invalid Operation</statusString>")) {
193 ipCameraHandler.lowPriorityRequests.remove(0);
194 ipCameraHandler.logger.debug(
195 "Stopping checks for alarm inputs as camera appears to be missing this feature.");
202 ReferenceCountUtil.release(msg);
206 // This does debouncing of the alarms
210 } else if (lineCount == 1) {
211 ipCameraHandler.setChannelState(CHANNEL_LINE_CROSSING_ALARM, OnOffType.OFF);
216 } else if (vmdCount == 1) {
217 ipCameraHandler.setChannelState(CHANNEL_MOTION_ALARM, OnOffType.OFF);
222 } else if (leftCount == 1) {
223 ipCameraHandler.setChannelState(CHANNEL_ITEM_LEFT, OnOffType.OFF);
226 if (takenCount > 1) {
228 } else if (takenCount == 1) {
229 ipCameraHandler.setChannelState(CHANNEL_ITEM_TAKEN, OnOffType.OFF);
234 } else if (faceCount == 1) {
235 ipCameraHandler.setChannelState(CHANNEL_FACE_DETECTED, OnOffType.OFF);
240 } else if (pirCount == 1) {
241 ipCameraHandler.setChannelState(CHANNEL_PIR_ALARM, OnOffType.OFF);
244 if (fieldCount > 1) {
246 } else if (fieldCount == 1) {
247 ipCameraHandler.setChannelState(CHANNEL_FIELD_DETECTION_ALARM, OnOffType.OFF);
250 if (fieldCount == 0 && pirCount == 0 && faceCount == 0 && takenCount == 0 && leftCount == 0 && vmdCount == 0
252 ipCameraHandler.noMotionDetected(CHANNEL_MOTION_ALARM);
256 public void hikSendXml(String httpPutURL, String xml) {
257 logger.trace("Body for PUT:{} is going to be:{}", httpPutURL, xml);
258 FullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, new HttpMethod("PUT"), httpPutURL);
259 request.headers().set(HttpHeaderNames.HOST, ipCameraHandler.cameraConfig.getIp());
260 request.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.CLOSE);
261 request.headers().add(HttpHeaderNames.CONTENT_TYPE, "application/xml; charset=\"UTF-8\"");
262 ByteBuf bbuf = Unpooled.copiedBuffer(xml, StandardCharsets.UTF_8);
263 request.headers().set(HttpHeaderNames.CONTENT_LENGTH, bbuf.readableBytes());
264 request.content().clear().writeBytes(bbuf);
265 ipCameraHandler.sendHttpPUT(httpPutURL, request);
268 public void hikChangeSetting(String httpGetPutURL, String removeElement, String replaceRemovedElementWith) {
269 ChannelTracking localTracker = ipCameraHandler.channelTrackingMap.get(httpGetPutURL);
270 if (localTracker == null) {
271 ipCameraHandler.sendHttpGET(httpGetPutURL);
273 "Did not have a reply stored before hikChangeSetting was run, try again shortly as a reply has just been requested.");
276 String body = localTracker.getReply();
277 if (body.isEmpty()) {
279 "Did not have a reply stored before hikChangeSetting was run, try again shortly as a reply has just been requested.");
280 ipCameraHandler.sendHttpGET(httpGetPutURL);
282 logger.trace("An OLD reply from the camera was:{}", body);
283 if (body.contains("<?xml version=\"1.0\" encoding=\"UTF-8\"?>")) {
284 body = body.substring("<?xml version=\"1.0\" encoding=\"UTF-8\"?>".length());
286 int elementIndexStart = body.indexOf("<" + removeElement + ">");
287 int elementIndexEnd = body.indexOf("</" + removeElement + ">");
288 body = body.substring(0, elementIndexStart) + replaceRemovedElementWith
289 + body.substring(elementIndexEnd + removeElement.length() + 3, body.length());
290 logger.trace("Body for this PUT is going to be:{}", body);
291 localTracker.setReply(body);
292 FullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, new HttpMethod("PUT"),
294 request.headers().set(HttpHeaderNames.HOST, ipCameraHandler.cameraConfig.getIp());
295 request.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.CLOSE);
296 request.headers().add(HttpHeaderNames.CONTENT_TYPE, "application/xml; charset=\"UTF-8\"");
297 ByteBuf bbuf = Unpooled.copiedBuffer(body, StandardCharsets.UTF_8);
298 request.headers().set(HttpHeaderNames.CONTENT_LENGTH, bbuf.readableBytes());
299 request.content().clear().writeBytes(bbuf);
300 ipCameraHandler.sendHttpPUT(httpGetPutURL, request);
304 // This handles the commands that come from the Openhab event bus.
305 public void handleCommand(ChannelUID channelUID, Command command) {
306 if (command instanceof RefreshType) {
307 switch (channelUID.getId()) {
308 case CHANNEL_ENABLE_AUDIO_ALARM:
309 ipCameraHandler.sendHttpGET("/ISAPI/Smart/AudioDetection/channels/" + nvrChannel + "01");
311 case CHANNEL_ENABLE_LINE_CROSSING_ALARM:
312 ipCameraHandler.sendHttpGET("/ISAPI/Smart/LineDetection/" + nvrChannel + "01");
314 case CHANNEL_ENABLE_FIELD_DETECTION_ALARM:
315 ipCameraHandler.logger.debug("FieldDetection command");
316 ipCameraHandler.sendHttpGET("/ISAPI/Smart/FieldDetection/" + nvrChannel + "01");
318 case CHANNEL_ENABLE_MOTION_ALARM:
320 .sendHttpGET("/ISAPI/System/Video/inputs/channels/" + nvrChannel + "01/motionDetection");
322 case CHANNEL_TEXT_OVERLAY:
324 .sendHttpGET("/ISAPI/System/Video/inputs/channels/" + nvrChannel + "/overlays/text/1");
326 case CHANNEL_ENABLE_EXTERNAL_ALARM_INPUT:
327 ipCameraHandler.sendHttpGET("/ISAPI/System/IO/inputs/" + nvrChannel);
329 case CHANNEL_TRIGGER_EXTERNAL_ALARM_INPUT:
330 ipCameraHandler.sendHttpGET("/ISAPI/System/IO/inputs/" + nvrChannel);
333 return; // Return as we have handled the refresh command above and don't need to
335 } // end of "REFRESH"
336 switch (channelUID.getId()) {
337 case CHANNEL_TEXT_OVERLAY:
338 logger.debug("Changing text overlay to {}", command.toString());
339 if (command.toString().isEmpty()) {
340 hikChangeSetting("/ISAPI/System/Video/inputs/channels/" + nvrChannel + "/overlays/text/1",
341 "enabled", "<enabled>false</enabled>");
343 hikChangeSetting("/ISAPI/System/Video/inputs/channels/" + nvrChannel + "/overlays/text/1",
344 "displayText", "<displayText>" + command.toString() + "</displayText>");
345 hikChangeSetting("/ISAPI/System/Video/inputs/channels/" + nvrChannel + "/overlays/text/1",
346 "enabled", "<enabled>true</enabled>");
349 case CHANNEL_ENABLE_EXTERNAL_ALARM_INPUT:
350 logger.debug("Changing enabled state of the external input 1 to {}", command.toString());
351 if (OnOffType.ON.equals(command)) {
352 hikChangeSetting("/ISAPI/System/IO/inputs/" + nvrChannel, "enabled", "<enabled>true</enabled>");
354 hikChangeSetting("/ISAPI/System/IO/inputs/" + nvrChannel, "enabled", "<enabled>false</enabled>");
357 case CHANNEL_TRIGGER_EXTERNAL_ALARM_INPUT:
358 logger.debug("Changing triggering state of the external input 1 to {}", command.toString());
359 if (OnOffType.OFF.equals(command)) {
360 hikChangeSetting("/ISAPI/System/IO/inputs/" + nvrChannel, "triggering",
361 "<triggering>low</triggering>");
363 hikChangeSetting("/ISAPI/System/IO/inputs/" + nvrChannel, "triggering",
364 "<triggering>high</triggering>");
367 case CHANNEL_ENABLE_PIR_ALARM:
368 if (OnOffType.ON.equals(command)) {
369 hikChangeSetting("/ISAPI/WLAlarm/PIR", "enabled", "<enabled>true</enabled>");
371 hikChangeSetting("/ISAPI/WLAlarm/PIR", "enabled", "<enabled>false</enabled>");
374 case CHANNEL_ENABLE_AUDIO_ALARM:
375 if (OnOffType.ON.equals(command)) {
376 hikChangeSetting("/ISAPI/Smart/AudioDetection/channels/" + nvrChannel + "01", "enabled",
377 "<enabled>true</enabled>");
379 hikChangeSetting("/ISAPI/Smart/AudioDetection/channels/" + nvrChannel + "01", "enabled",
380 "<enabled>false</enabled>");
383 case CHANNEL_ENABLE_LINE_CROSSING_ALARM:
384 if (OnOffType.ON.equals(command)) {
385 hikChangeSetting("/ISAPI/Smart/LineDetection/" + nvrChannel + "01", "enabled",
386 "<enabled>true</enabled>");
388 hikChangeSetting("/ISAPI/Smart/LineDetection/" + nvrChannel + "01", "enabled",
389 "<enabled>false</enabled>");
392 case CHANNEL_ENABLE_MOTION_ALARM:
393 if (OnOffType.ON.equals(command)) {
394 hikChangeSetting("/ISAPI/System/Video/inputs/channels/" + nvrChannel + "01/motionDetection",
395 "enabled", "<enabled>true</enabled>");
397 hikChangeSetting("/ISAPI/System/Video/inputs/channels/" + nvrChannel + "01/motionDetection",
398 "enabled", "<enabled>false</enabled>");
401 case CHANNEL_ENABLE_FIELD_DETECTION_ALARM:
402 if (OnOffType.ON.equals(command)) {
403 hikChangeSetting("/ISAPI/Smart/FieldDetection/" + nvrChannel + "01", "enabled",
404 "<enabled>true</enabled>");
406 hikChangeSetting("/ISAPI/Smart/FieldDetection/" + nvrChannel + "01", "enabled",
407 "<enabled>false</enabled>");
410 case CHANNEL_ACTIVATE_ALARM_OUTPUT:
411 if (OnOffType.ON.equals(command)) {
412 hikSendXml("/ISAPI/System/IO/outputs/" + nvrChannel + "/trigger",
413 "<IOPortData version=\"1.0\" xmlns=\"http://www.hikvision.com/ver10/XMLSchema\">\r\n <outputState>high</outputState>\r\n</IOPortData>\r\n");
415 hikSendXml("/ISAPI/System/IO/outputs/" + nvrChannel + "/trigger",
416 "<IOPortData version=\"1.0\" xmlns=\"http://www.hikvision.com/ver10/XMLSchema\">\r\n <outputState>low</outputState>\r\n</IOPortData>\r\n");
422 // If a camera does not need to poll a request as often as snapshots, it can be
423 // added here. Binding steps through the list.
424 public ArrayList<String> getLowPriorityRequests() {
425 ArrayList<String> lowPriorityRequests = new ArrayList<String>(1);
426 lowPriorityRequests.add("/ISAPI/System/IO/inputs/" + nvrChannel + "/status"); // must stay in element 0.
427 return lowPriorityRequests;