]> git.basschouten.com Git - openhab-addons.git/blob
51ae91b6e16faf23bb45175400c04d5cc51614e1
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2021 Contributors to the openHAB project
3  *
4  * See the NOTICE file(s) distributed with this work for additional
5  * information.
6  *
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
10  *
11  * SPDX-License-Identifier: EPL-2.0
12  */
13 package org.openhab.binding.ipcamera.internal;
14
15 import static org.openhab.binding.ipcamera.internal.IpCameraBindingConstants.*;
16
17 import java.nio.charset.StandardCharsets;
18 import java.util.ArrayList;
19
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;
31
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;
43
44 /**
45  * The {@link HikvisionHandler} is responsible for handling commands, which are
46  * sent to one of the channels.
47  *
48  * @author Matthew Skinner - Initial contribution
49  */
50
51 @NonNullByDefault
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;
57
58     public HikvisionHandler(ThingHandler handler, int nvrChannel) {
59         ipCameraHandler = (IpCameraHandler) handler;
60         this.nvrChannel = nvrChannel;
61     }
62
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>");
68             switch (eventType) {
69                 case "videoloss":
70                     if (content.contains("<eventState>inactive</eventState>")) {
71                         if (vmdCount > 1) {
72                             vmdCount = 1;
73                         }
74                         countDown();
75                         countDown();
76                     }
77                     break;
78                 case "PIR":
79                     ipCameraHandler.motionDetected(CHANNEL_PIR_ALARM);
80                     pirCount = debounce;
81                     break;
82                 case "attendedBaggage":
83                     ipCameraHandler.setChannelState(CHANNEL_ITEM_TAKEN, OnOffType.ON);
84                     takenCount = debounce;
85                     break;
86                 case "unattendedBaggage":
87                     ipCameraHandler.setChannelState(CHANNEL_ITEM_LEFT, OnOffType.ON);
88                     leftCount = debounce;
89                     break;
90                 case "facedetection":
91                     ipCameraHandler.setChannelState(CHANNEL_FACE_DETECTED, OnOffType.ON);
92                     faceCount = debounce;
93                     break;
94                 case "VMD":
95                     ipCameraHandler.motionDetected(CHANNEL_MOTION_ALARM);
96                     vmdCount = debounce;
97                     break;
98                 case "fielddetection":
99                     ipCameraHandler.motionDetected(CHANNEL_FIELD_DETECTION_ALARM);
100                     fieldCount = debounce;
101                     break;
102                 case "linedetection":
103                     ipCameraHandler.motionDetected(CHANNEL_LINE_CROSSING_ALARM);
104                     lineCount = debounce;
105                     break;
106                 default:
107                     logger.debug("Unrecognised Hikvision eventType={}", eventType);
108             }
109         }
110         countDown();
111     }
112
113     // This handles the incoming http replies back from the camera.
114     @Override
115     public void channelRead(@Nullable ChannelHandlerContext ctx, @Nullable Object msg) throws Exception {
116         if (msg == null || ctx == null) {
117             return;
118         }
119         try {
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);
124             } else {
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);
134                         }
135                         break;
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);
142                         }
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);
147                         }
148                         break;
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);
155                         }
156                         break;
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));
162                         break;
163                     case "AudioDetection version=":
164                         ipCameraHandler.storeHttpReply("/ISAPI/Smart/AudioDetection/channels/" + nvrChannel + "01",
165                                 content);
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);
170                         }
171                         break;
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);
177                         }
178                         break;
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);
185                         }
186                         break;
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.");
196                             }
197                         }
198                         break;
199                 }
200             }
201         } finally {
202             ReferenceCountUtil.release(msg);
203         }
204     }
205
206     // This does debouncing of the alarms
207     void countDown() {
208         if (lineCount > 1) {
209             lineCount--;
210         } else if (lineCount == 1) {
211             ipCameraHandler.setChannelState(CHANNEL_LINE_CROSSING_ALARM, OnOffType.OFF);
212             lineCount--;
213         }
214         if (vmdCount > 1) {
215             vmdCount--;
216         } else if (vmdCount == 1) {
217             ipCameraHandler.setChannelState(CHANNEL_MOTION_ALARM, OnOffType.OFF);
218             vmdCount--;
219         }
220         if (leftCount > 1) {
221             leftCount--;
222         } else if (leftCount == 1) {
223             ipCameraHandler.setChannelState(CHANNEL_ITEM_LEFT, OnOffType.OFF);
224             leftCount--;
225         }
226         if (takenCount > 1) {
227             takenCount--;
228         } else if (takenCount == 1) {
229             ipCameraHandler.setChannelState(CHANNEL_ITEM_TAKEN, OnOffType.OFF);
230             takenCount--;
231         }
232         if (faceCount > 1) {
233             faceCount--;
234         } else if (faceCount == 1) {
235             ipCameraHandler.setChannelState(CHANNEL_FACE_DETECTED, OnOffType.OFF);
236             faceCount--;
237         }
238         if (pirCount > 1) {
239             pirCount--;
240         } else if (pirCount == 1) {
241             ipCameraHandler.setChannelState(CHANNEL_PIR_ALARM, OnOffType.OFF);
242             pirCount--;
243         }
244         if (fieldCount > 1) {
245             fieldCount--;
246         } else if (fieldCount == 1) {
247             ipCameraHandler.setChannelState(CHANNEL_FIELD_DETECTION_ALARM, OnOffType.OFF);
248             fieldCount--;
249         }
250         if (fieldCount == 0 && pirCount == 0 && faceCount == 0 && takenCount == 0 && leftCount == 0 && vmdCount == 0
251                 && lineCount == 0) {
252             ipCameraHandler.noMotionDetected(CHANNEL_MOTION_ALARM);
253         }
254     }
255
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);
266     }
267
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);
272             logger.debug(
273                     "Did not have a reply stored before hikChangeSetting was run, try again shortly as a reply has just been requested.");
274             return;
275         }
276         String body = localTracker.getReply();
277         if (body.isEmpty()) {
278             logger.debug(
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);
281         } else {
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());
285             }
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"),
293                     httpGetPutURL);
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);
301         }
302     }
303
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");
310                     return;
311                 case CHANNEL_ENABLE_LINE_CROSSING_ALARM:
312                     ipCameraHandler.sendHttpGET("/ISAPI/Smart/LineDetection/" + nvrChannel + "01");
313                     return;
314                 case CHANNEL_ENABLE_FIELD_DETECTION_ALARM:
315                     ipCameraHandler.logger.debug("FieldDetection command");
316                     ipCameraHandler.sendHttpGET("/ISAPI/Smart/FieldDetection/" + nvrChannel + "01");
317                     return;
318                 case CHANNEL_ENABLE_MOTION_ALARM:
319                     ipCameraHandler
320                             .sendHttpGET("/ISAPI/System/Video/inputs/channels/" + nvrChannel + "01/motionDetection");
321                     return;
322                 case CHANNEL_TEXT_OVERLAY:
323                     ipCameraHandler
324                             .sendHttpGET("/ISAPI/System/Video/inputs/channels/" + nvrChannel + "/overlays/text/1");
325                     return;
326                 case CHANNEL_ENABLE_EXTERNAL_ALARM_INPUT:
327                     ipCameraHandler.sendHttpGET("/ISAPI/System/IO/inputs/" + nvrChannel);
328                     return;
329                 case CHANNEL_TRIGGER_EXTERNAL_ALARM_INPUT:
330                     ipCameraHandler.sendHttpGET("/ISAPI/System/IO/inputs/" + nvrChannel);
331                     return;
332             }
333             return; // Return as we have handled the refresh command above and don't need to
334                     // continue further.
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>");
342                 } else {
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>");
347                 }
348                 return;
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>");
353                 } else {
354                     hikChangeSetting("/ISAPI/System/IO/inputs/" + nvrChannel, "enabled", "<enabled>false</enabled>");
355                 }
356                 return;
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>");
362                 } else {
363                     hikChangeSetting("/ISAPI/System/IO/inputs/" + nvrChannel, "triggering",
364                             "<triggering>high</triggering>");
365                 }
366                 return;
367             case CHANNEL_ENABLE_PIR_ALARM:
368                 if (OnOffType.ON.equals(command)) {
369                     hikChangeSetting("/ISAPI/WLAlarm/PIR", "enabled", "<enabled>true</enabled>");
370                 } else {
371                     hikChangeSetting("/ISAPI/WLAlarm/PIR", "enabled", "<enabled>false</enabled>");
372                 }
373                 return;
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>");
378                 } else {
379                     hikChangeSetting("/ISAPI/Smart/AudioDetection/channels/" + nvrChannel + "01", "enabled",
380                             "<enabled>false</enabled>");
381                 }
382                 return;
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>");
387                 } else {
388                     hikChangeSetting("/ISAPI/Smart/LineDetection/" + nvrChannel + "01", "enabled",
389                             "<enabled>false</enabled>");
390                 }
391                 return;
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>");
396                 } else {
397                     hikChangeSetting("/ISAPI/System/Video/inputs/channels/" + nvrChannel + "01/motionDetection",
398                             "enabled", "<enabled>false</enabled>");
399                 }
400                 return;
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>");
405                 } else {
406                     hikChangeSetting("/ISAPI/Smart/FieldDetection/" + nvrChannel + "01", "enabled",
407                             "<enabled>false</enabled>");
408                 }
409                 return;
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");
414                 } else {
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");
417                 }
418                 return;
419         }
420     }
421
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;
428     }
429 }