]> git.basschouten.com Git - openhab-addons.git/blob
e6cd9d10d8b94d78a756ce84a6f3fd5995fb1934
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2024 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.onvif;
14
15 import static org.openhab.binding.ipcamera.internal.IpCameraBindingConstants.*;
16
17 import java.net.ConnectException;
18 import java.net.InetSocketAddress;
19 import java.nio.charset.StandardCharsets;
20 import java.security.MessageDigest;
21 import java.security.NoSuchAlgorithmException;
22 import java.security.SecureRandom;
23 import java.text.SimpleDateFormat;
24 import java.util.ArrayList;
25 import java.util.Base64;
26 import java.util.Date;
27 import java.util.LinkedList;
28 import java.util.List;
29 import java.util.Random;
30 import java.util.TimeZone;
31 import java.util.concurrent.Executors;
32 import java.util.concurrent.ScheduledExecutorService;
33 import java.util.concurrent.TimeUnit;
34 import java.util.concurrent.locks.ReentrantLock;
35
36 import org.eclipse.jdt.annotation.NonNullByDefault;
37 import org.eclipse.jdt.annotation.Nullable;
38 import org.openhab.binding.ipcamera.internal.Helper;
39 import org.openhab.binding.ipcamera.internal.handler.IpCameraHandler;
40 import org.openhab.core.library.types.OnOffType;
41 import org.openhab.core.thing.ChannelUID;
42 import org.openhab.core.types.StateOption;
43 import org.openhab.core.util.StringUtils;
44 import org.slf4j.Logger;
45 import org.slf4j.LoggerFactory;
46
47 import io.netty.bootstrap.Bootstrap;
48 import io.netty.buffer.ByteBuf;
49 import io.netty.buffer.Unpooled;
50 import io.netty.channel.Channel;
51 import io.netty.channel.ChannelFuture;
52 import io.netty.channel.ChannelFutureListener;
53 import io.netty.channel.ChannelInitializer;
54 import io.netty.channel.ChannelOption;
55 import io.netty.channel.ConnectTimeoutException;
56 import io.netty.channel.EventLoopGroup;
57 import io.netty.channel.nio.NioEventLoopGroup;
58 import io.netty.channel.socket.SocketChannel;
59 import io.netty.channel.socket.nio.NioSocketChannel;
60 import io.netty.handler.codec.http.DefaultFullHttpRequest;
61 import io.netty.handler.codec.http.FullHttpRequest;
62 import io.netty.handler.codec.http.HttpClientCodec;
63 import io.netty.handler.codec.http.HttpHeaderValues;
64 import io.netty.handler.codec.http.HttpMethod;
65 import io.netty.handler.codec.http.HttpVersion;
66 import io.netty.handler.timeout.IdleStateHandler;
67
68 /**
69  * The {@link OnvifConnection} This is a basic Netty implementation for connecting and communicating to ONVIF cameras.
70  *
71  * @author Matthew Skinner - Initial contribution
72  * @author Kai Kreuzer - Improve handling for certain cameras
73  */
74
75 @NonNullByDefault
76 public class OnvifConnection {
77     public enum RequestType {
78         AbsoluteMove,
79         AddPTZConfiguration,
80         ContinuousMoveLeft,
81         ContinuousMoveRight,
82         ContinuousMoveUp,
83         ContinuousMoveDown,
84         Stop,
85         ContinuousMoveIn,
86         ContinuousMoveOut,
87         CreatePullPointSubscription,
88         GetCapabilities,
89         GetDeviceInformation,
90         GetProfiles,
91         GetServiceCapabilities,
92         GetSnapshotUri,
93         GetStreamUri,
94         GetSystemDateAndTime,
95         Subscribe,
96         Unsubscribe,
97         PullMessages,
98         GetEventProperties,
99         RelativeMoveLeft,
100         RelativeMoveRight,
101         RelativeMoveUp,
102         RelativeMoveDown,
103         RelativeMoveIn,
104         RelativeMoveOut,
105         Renew,
106         GetConfigurations,
107         GetConfigurationOptions,
108         GetConfiguration,
109         SetConfiguration,
110         GetNodes,
111         GetStatus,
112         GotoPreset,
113         GetPresets
114     }
115
116     private final Logger logger = LoggerFactory.getLogger(getClass());
117     private ScheduledExecutorService threadPool = Executors.newScheduledThreadPool(2);
118     private @Nullable Bootstrap bootstrap;
119     private EventLoopGroup mainEventLoopGroup = new NioEventLoopGroup(2);
120     private ReentrantLock connecting = new ReentrantLock();
121     private String ipAddress = "";
122     private String user = "";
123     private String password = "";
124     private int onvifPort = 80;
125     private String deviceXAddr = "http://" + ipAddress + "/onvif/device_service";
126     private String eventXAddr = "http://" + ipAddress + "/onvif/device_service";
127     private String mediaXAddr = "http://" + ipAddress + "/onvif/device_service";
128     @SuppressWarnings("unused")
129     private String imagingXAddr = "http://" + ipAddress + "/onvif/device_service";
130     private String ptzXAddr = "http://" + ipAddress + "/onvif/ptz_service";
131     private String subscriptionXAddr = "http://" + ipAddress + "/onvif/device_service";
132     private boolean isConnected = false;
133     private int mediaProfileIndex = 0;
134     private String rtspUri = "";
135     private IpCameraHandler ipCameraHandler;
136     private boolean supportsEvents = false; // camera has replied that it can do events
137     // Use/skip events even if camera support them. API cameras skip, as their own methods give better results.
138     private boolean usingEvents = false;
139
140     // These hold the cameras PTZ position in the range that the camera uses, ie
141     // mine is -1 to +1
142     private Float panRangeMin = -1.0f;
143     private Float panRangeMax = 1.0f;
144     private Float tiltRangeMin = -1.0f;
145     private Float tiltRangeMax = 1.0f;
146     private Float zoomMin = 0.0f;
147     private Float zoomMax = 1.0f;
148     // These hold the PTZ values for updating openHABs controls in 0-100 range
149     private Float currentPanPercentage = 0.0f;
150     private Float currentTiltPercentage = 0.0f;
151     private Float currentZoomPercentage = 0.0f;
152     private Float currentPanCamValue = 0.0f;
153     private Float currentTiltCamValue = 0.0f;
154     private Float currentZoomCamValue = 0.0f;
155     private String ptzNodeToken = "000";
156     private String ptzConfigToken = "000";
157     private int presetTokenIndex = 0;
158     private List<String> presetTokens = new LinkedList<>();
159     private List<String> presetNames = new LinkedList<>();
160     private List<String> mediaProfileTokens = new LinkedList<>();
161     private boolean ptzDevice = true;
162
163     public OnvifConnection(IpCameraHandler ipCameraHandler, String ipAddress, String user, String password) {
164         this.ipCameraHandler = ipCameraHandler;
165         if (!ipAddress.isEmpty()) {
166             this.user = user;
167             this.password = password;
168             getIPandPortFromUrl(ipAddress);
169         }
170     }
171
172     private String getXml(RequestType requestType) {
173         try {
174             switch (requestType) {
175                 case AbsoluteMove:
176                     return "<AbsoluteMove xmlns=\"http://www.onvif.org/ver20/ptz/wsdl\"><ProfileToken>"
177                             + mediaProfileTokens.get(mediaProfileIndex) + "</ProfileToken><Position><PanTilt x=\""
178                             + currentPanCamValue + "\" y=\"" + currentTiltCamValue
179                             + "\" space=\"http://www.onvif.org/ver10/tptz/PanTiltSpaces/PositionGenericSpace\">\n"
180                             + "</PanTilt>\n" + "<Zoom x=\"" + currentZoomCamValue
181                             + "\" space=\"http://www.onvif.org/ver10/tptz/ZoomSpaces/PositionGenericSpace\">\n"
182                             + "</Zoom>\n" + "</Position>\n"
183                             + "<Speed><PanTilt x=\"0.1\" y=\"0.1\" space=\"http://www.onvif.org/ver10/tptz/PanTiltSpaces/GenericSpeedSpace\"></PanTilt><Zoom x=\"1.0\" space=\"http://www.onvif.org/ver10/tptz/ZoomSpaces/ZoomGenericSpeedSpace\"></Zoom>\n"
184                             + "</Speed></AbsoluteMove>";
185                 case AddPTZConfiguration: // not tested to work yet
186                     return "<AddPTZConfiguration xmlns=\"http://www.onvif.org/ver20/ptz/wsdl\"><ProfileToken>"
187                             + mediaProfileTokens.get(mediaProfileIndex) + "</ProfileToken><ConfigurationToken>"
188                             + ptzConfigToken + "</ConfigurationToken></AddPTZConfiguration>";
189                 case ContinuousMoveLeft:
190                     return "<ContinuousMove xmlns=\"http://www.onvif.org/ver20/ptz/wsdl\"><ProfileToken>"
191                             + mediaProfileTokens.get(mediaProfileIndex)
192                             + "</ProfileToken><Velocity><PanTilt x=\"-0.5\" y=\"0\" xmlns=\"http://www.onvif.org/ver10/schema\"/></Velocity></ContinuousMove>";
193                 case ContinuousMoveRight:
194                     return "<ContinuousMove xmlns=\"http://www.onvif.org/ver20/ptz/wsdl\"><ProfileToken>"
195                             + mediaProfileTokens.get(mediaProfileIndex)
196                             + "</ProfileToken><Velocity><PanTilt x=\"0.5\" y=\"0\" xmlns=\"http://www.onvif.org/ver10/schema\"/></Velocity></ContinuousMove>";
197                 case ContinuousMoveUp:
198                     return "<ContinuousMove xmlns=\"http://www.onvif.org/ver20/ptz/wsdl\"><ProfileToken>"
199                             + mediaProfileTokens.get(mediaProfileIndex)
200                             + "</ProfileToken><Velocity><PanTilt x=\"0\" y=\"-0.5\" xmlns=\"http://www.onvif.org/ver10/schema\"/></Velocity></ContinuousMove>";
201                 case ContinuousMoveDown:
202                     return "<ContinuousMove xmlns=\"http://www.onvif.org/ver20/ptz/wsdl\"><ProfileToken>"
203                             + mediaProfileTokens.get(mediaProfileIndex)
204                             + "</ProfileToken><Velocity><PanTilt x=\"0\" y=\"0.5\" xmlns=\"http://www.onvif.org/ver10/schema\"/></Velocity></ContinuousMove>";
205                 case Stop:
206                     return "<Stop xmlns=\"http://www.onvif.org/ver20/ptz/wsdl\"><ProfileToken>"
207                             + mediaProfileTokens.get(mediaProfileIndex)
208                             + "</ProfileToken><PanTilt>true</PanTilt><Zoom>true</Zoom></Stop>";
209                 case ContinuousMoveIn:
210                     return "<ContinuousMove xmlns=\"http://www.onvif.org/ver20/ptz/wsdl\"><ProfileToken>"
211                             + mediaProfileTokens.get(mediaProfileIndex)
212                             + "</ProfileToken><Velocity><Zoom x=\"0.5\" xmlns=\"http://www.onvif.org/ver10/schema\"/></Velocity></ContinuousMove>";
213                 case ContinuousMoveOut:
214                     return "<ContinuousMove xmlns=\"http://www.onvif.org/ver20/ptz/wsdl\"><ProfileToken>"
215                             + mediaProfileTokens.get(mediaProfileIndex)
216                             + "</ProfileToken><Velocity><Zoom x=\"-0.5\" xmlns=\"http://www.onvif.org/ver10/schema\"/></Velocity></ContinuousMove>";
217                 case CreatePullPointSubscription:
218                     return "<CreatePullPointSubscription xmlns=\"http://www.onvif.org/ver10/events/wsdl\"><InitialTerminationTime>PT600S</InitialTerminationTime></CreatePullPointSubscription>";
219                 case GetCapabilities:
220                     return "<GetCapabilities xmlns=\"http://www.onvif.org/ver10/device/wsdl\"><Category>All</Category></GetCapabilities>";
221
222                 case GetDeviceInformation:
223                     return "<GetDeviceInformation xmlns=\"http://www.onvif.org/ver10/device/wsdl\"/>";
224                 case GetProfiles:
225                     return "<GetProfiles xmlns=\"http://www.onvif.org/ver10/media/wsdl\"/>";
226                 case GetServiceCapabilities:
227                     return "<GetServiceCapabilities xmlns=\"http://docs.oasis-open.org/wsn/b-2/\"></GetServiceCapabilities>";
228                 case GetSnapshotUri:
229                     return "<GetSnapshotUri xmlns=\"http://www.onvif.org/ver10/media/wsdl\"><ProfileToken>"
230                             + mediaProfileTokens.get(mediaProfileIndex) + "</ProfileToken></GetSnapshotUri>";
231                 case GetStreamUri:
232                     return "<GetStreamUri xmlns=\"http://www.onvif.org/ver10/media/wsdl\"><StreamSetup><Stream xmlns=\"http://www.onvif.org/ver10/schema\">RTP-Unicast</Stream><Transport xmlns=\"http://www.onvif.org/ver10/schema\"><Protocol>RTSP</Protocol></Transport></StreamSetup><ProfileToken>"
233                             + mediaProfileTokens.get(mediaProfileIndex) + "</ProfileToken></GetStreamUri>";
234                 case GetSystemDateAndTime:
235                     return "<GetSystemDateAndTime xmlns=\"http://www.onvif.org/ver10/device/wsdl\"/>";
236                 case Subscribe:
237                     return "<Subscribe xmlns=\"http://docs.oasis-open.org/wsn/b-2/\"><ConsumerReference><Address>http://"
238                             + ipCameraHandler.hostIp + ":" + SERVLET_PORT + "/ipcamera/"
239                             + ipCameraHandler.getThing().getUID().getId()
240                             + "/OnvifEvent</Address></ConsumerReference></Subscribe>";
241                 case Unsubscribe:
242                     return "<Unsubscribe xmlns=\"http://docs.oasis-open.org/wsn/b-2/\"></Unsubscribe>";
243                 case PullMessages:
244                     return "<PullMessages xmlns=\"http://www.onvif.org/ver10/events/wsdl\"><Timeout>PT8S</Timeout><MessageLimit>1</MessageLimit></PullMessages>";
245                 case GetEventProperties:
246                     return "<GetEventProperties xmlns=\"http://www.onvif.org/ver10/events/wsdl\"/>";
247                 case RelativeMoveLeft:
248                     return "<RelativeMove xmlns=\"http://www.onvif.org/ver20/ptz/wsdl\"><ProfileToken>"
249                             + mediaProfileTokens.get(mediaProfileIndex)
250                             + "</ProfileToken><Translation><PanTilt x=\"0.05000000\" y=\"0\" xmlns=\"http://www.onvif.org/ver10/schema\"/></Translation></RelativeMove>";
251                 case RelativeMoveRight:
252                     return "<RelativeMove xmlns=\"http://www.onvif.org/ver20/ptz/wsdl\"><ProfileToken>"
253                             + mediaProfileTokens.get(mediaProfileIndex)
254                             + "</ProfileToken><Translation><PanTilt x=\"-0.05000000\" y=\"0\" xmlns=\"http://www.onvif.org/ver10/schema\"/></Translation></RelativeMove>";
255                 case RelativeMoveUp:
256                     return "<RelativeMove xmlns=\"http://www.onvif.org/ver20/ptz/wsdl\"><ProfileToken>"
257                             + mediaProfileTokens.get(mediaProfileIndex)
258                             + "</ProfileToken><Translation><PanTilt x=\"0\" y=\"0.100000000\" xmlns=\"http://www.onvif.org/ver10/schema\"/></Translation></RelativeMove>";
259                 case RelativeMoveDown:
260                     return "<RelativeMove xmlns=\"http://www.onvif.org/ver20/ptz/wsdl\"><ProfileToken>"
261                             + mediaProfileTokens.get(mediaProfileIndex)
262                             + "</ProfileToken><Translation><PanTilt x=\"0\" y=\"-0.100000000\" xmlns=\"http://www.onvif.org/ver10/schema\"/></Translation></RelativeMove>";
263                 case RelativeMoveIn:
264                     return "<RelativeMove xmlns=\"http://www.onvif.org/ver20/ptz/wsdl\"><ProfileToken>"
265                             + mediaProfileTokens.get(mediaProfileIndex)
266                             + "</ProfileToken><Translation><Zoom x=\"0.0240506344\" xmlns=\"http://www.onvif.org/ver10/schema\"/></Translation></RelativeMove>";
267                 case RelativeMoveOut:
268                     return "<RelativeMove xmlns=\"http://www.onvif.org/ver20/ptz/wsdl\"><ProfileToken>"
269                             + mediaProfileTokens.get(mediaProfileIndex)
270                             + "</ProfileToken><Translation><Zoom x=\"-0.0240506344\" xmlns=\"http://www.onvif.org/ver10/schema\"/></Translation></RelativeMove>";
271                 case Renew:
272                     return "<Renew xmlns=\"http://docs.oasis-open.org/wsn/b-2\"><TerminationTime>PT1M</TerminationTime></Renew>";
273                 case GetConfigurations:
274                     return "<GetConfigurations xmlns=\"http://www.onvif.org/ver20/ptz/wsdl\"></GetConfigurations>";
275                 case GetConfigurationOptions:
276                     return "<GetConfigurationOptions xmlns=\"http://www.onvif.org/ver20/ptz/wsdl\"><ConfigurationToken>"
277                             + ptzConfigToken + "</ConfigurationToken></GetConfigurationOptions>";
278                 case GetConfiguration:
279                     return "<GetConfiguration xmlns=\"http://www.onvif.org/ver20/ptz/wsdl\"><PTZConfigurationToken>"
280                             + ptzConfigToken + "</PTZConfigurationToken></GetConfiguration>";
281                 case SetConfiguration:// not tested to work yet
282                     return "<SetConfiguration xmlns=\"http://www.onvif.org/ver20/ptz/wsdl\"><PTZConfiguration><NodeToken>"
283                             + ptzNodeToken
284                             + "</NodeToken><DefaultAbsolutePantTiltPositionSpace>AbsolutePanTiltPositionSpace</DefaultAbsolutePantTiltPositionSpace><DefaultAbsoluteZoomPositionSpace>AbsoluteZoomPositionSpace</DefaultAbsoluteZoomPositionSpace></PTZConfiguration></SetConfiguration>";
285                 case GetNodes:
286                     return "<GetNodes xmlns=\"http://www.onvif.org/ver20/ptz/wsdl\"></GetNodes>";
287                 case GetStatus:
288                     return "<GetStatus xmlns=\"http://www.onvif.org/ver20/ptz/wsdl\"><ProfileToken>"
289                             + mediaProfileTokens.get(mediaProfileIndex) + "</ProfileToken></GetStatus>";
290                 case GotoPreset:
291                     return "<GotoPreset xmlns=\"http://www.onvif.org/ver20/ptz/wsdl\"><ProfileToken>"
292                             + mediaProfileTokens.get(mediaProfileIndex) + "</ProfileToken><PresetToken>"
293                             + presetTokens.get(presetTokenIndex) + "</PresetToken></GotoPreset>";
294                 case GetPresets:
295                     return "<GetPresets xmlns=\"http://www.onvif.org/ver20/ptz/wsdl\"><ProfileToken>"
296                             + mediaProfileTokens.get(mediaProfileIndex) + "</ProfileToken></GetPresets>";
297             }
298         } catch (IndexOutOfBoundsException e) {
299             if (!isConnected) {
300                 logger.debug("IndexOutOfBoundsException occured, camera is not connected via ONVIF: {}",
301                         e.getMessage());
302             } else {
303                 logger.debug("IndexOutOfBoundsException occured, {}", e.getMessage());
304             }
305         }
306         return "notfound";
307     }
308
309     public void processReply(String message) {
310         logger.trace("ONVIF reply is: {}", message);
311         if (message.contains("PullMessagesResponse")) {
312             eventRecieved(message);
313         } else if (message.contains("RenewResponse")) {
314             sendOnvifRequest(RequestType.PullMessages, subscriptionXAddr);
315         } else if (message.contains("GetSystemDateAndTimeResponse")) {// 1st to be sent.
316             setIsConnected(true);// Instar profile T only cameras need this
317             parseDateAndTime(message);
318             logger.debug("openHAB UTC dateTime is: {}", getUTCdateTime());
319         } else if (message.contains("GetCapabilitiesResponse")) {// 2nd to be sent.
320             parseXAddr(message);
321             sendOnvifRequest(RequestType.GetProfiles, mediaXAddr);
322         } else if (message.contains("GetProfilesResponse")) {// 3rd to be sent.
323             setIsConnected(true);
324             parseProfiles(message);
325             sendOnvifRequest(RequestType.GetSnapshotUri, mediaXAddr);
326             sendOnvifRequest(RequestType.GetStreamUri, mediaXAddr);
327             if (ptzDevice) {
328                 sendPTZRequest(RequestType.GetNodes);
329             }
330             if (usingEvents) {// stops API cameras from getting sent ONVIF events.
331                 sendOnvifRequest(RequestType.GetEventProperties, eventXAddr);
332                 sendOnvifRequest(RequestType.GetServiceCapabilities, eventXAddr);
333             }
334         } else if (message.contains("GetServiceCapabilitiesResponse")) {
335             if (message.contains("WSSubscriptionPolicySupport=\"true\"")) {
336                 sendOnvifRequest(RequestType.Subscribe, eventXAddr);
337             }
338         } else if (message.contains("GetEventPropertiesResponse")) {
339             sendOnvifRequest(RequestType.CreatePullPointSubscription, eventXAddr);
340         } else if (message.contains("CreatePullPointSubscriptionResponse")) {
341             supportsEvents = true;
342             subscriptionXAddr = Helper.fetchXML(message, "SubscriptionReference>", "Address>");
343             logger.debug("subscriptionXAddr={}", subscriptionXAddr);
344             sendOnvifRequest(RequestType.PullMessages, subscriptionXAddr);
345         } else if (message.contains("GetStatusResponse")) {
346             processPTZLocation(message);
347         } else if (message.contains("GetPresetsResponse")) {
348             parsePresets(message);
349         } else if (message.contains("GetConfigurationsResponse")) {
350             sendPTZRequest(RequestType.GetPresets);
351             ptzConfigToken = Helper.fetchXML(message, "PTZConfiguration", "token=\"");
352             logger.debug("ptzConfigToken={}", ptzConfigToken);
353             sendPTZRequest(RequestType.GetConfigurationOptions);
354         } else if (message.contains("GetNodesResponse")) {
355             sendPTZRequest(RequestType.GetStatus);
356             ptzNodeToken = Helper.fetchXML(message, "", "token=\"");
357             logger.debug("ptzNodeToken={}", ptzNodeToken);
358             sendPTZRequest(RequestType.GetConfigurations);
359         } else if (message.contains("GetDeviceInformationResponse")) {
360             logger.debug("GetDeviceInformationResponse received");
361         } else if (message.contains("GetSnapshotUriResponse")) {
362             String url = Helper.fetchXML(message, ":MediaUri", ":Uri");
363             if (!url.isBlank()) {
364                 logger.debug("GetSnapshotUri: {}", url);
365                 if (ipCameraHandler.snapshotUri.isEmpty()
366                         && !"ffmpeg".equals(ipCameraHandler.cameraConfig.getSnapshotUrl())) {
367                     ipCameraHandler.snapshotUri = ipCameraHandler.getCorrectUrlFormat(url);
368                     if (ipCameraHandler.getPortFromShortenedUrl(url) != ipCameraHandler.cameraConfig.getPort()) {
369                         logger.warn("ONVIF is reporting the snapshot does not match the things configured port of:{}",
370                                 ipCameraHandler.cameraConfig.getPort());
371                     }
372                 }
373             }
374         } else if (message.contains("GetStreamUriResponse")) {
375             String xml = StringUtils.unEscapeXml(Helper.fetchXML(message, ":MediaUri", ":Uri>"));
376             if (xml != null) {
377                 rtspUri = xml;
378                 logger.debug("GetStreamUri: {}", rtspUri);
379                 if (ipCameraHandler.cameraConfig.getFfmpegInput().isEmpty()) {
380                     ipCameraHandler.rtspUri = rtspUri;
381                 }
382             }
383         }
384     }
385
386     /**
387      * The {@link removeIPandPortFromUrl} Will throw away all text before the cameras IP, also removes the IP and the
388      * PORT
389      * leaving just the URL.
390      *
391      * @author Matthew Skinner - Initial contribution
392      */
393     String removeIPandPortFromUrl(String url) {
394         int index = url.indexOf("//");
395         if (index != -1) {// now remove the :port
396             index = url.indexOf("/", index + 2);
397         }
398         if (index == -1) {
399             logger.debug("We hit an issue parsing url: {}", url);
400             return "";
401         }
402         return url.substring(index);
403     }
404
405     String extractIPportFromUrl(String url) {
406         int startIndex = url.indexOf("//") + 2;
407         int endIndex = url.indexOf("/", startIndex);// skip past any :port to the slash /
408         if (startIndex != -1 && endIndex != -1) {
409             return url.substring(startIndex, endIndex);
410         }
411         logger.debug("We hit an issue extracting IP:PORT from url: {}", url);
412         return "";
413     }
414
415     int extractPortFromUrl(String url) {
416         int startIndex = url.indexOf("//") + 2;// skip past http://
417         startIndex = url.indexOf(":", startIndex);
418         if (startIndex == -1) {// no port defined so use port 80
419             return 80;
420         }
421         int endIndex = url.indexOf("/", startIndex);// skip past any :port to the slash /
422         if (endIndex == -1) {
423             return 80;
424         }
425         return Integer.parseInt(url.substring(startIndex + 1, endIndex));
426     }
427
428     void parseXAddr(String message) {
429         // Normally I would search '<tt:XAddr>' instead but Foscam needed this work around.
430         String temp = Helper.fetchXML(message, "<tt:Device", "tt:XAddr");
431         if (!temp.isEmpty()) {
432             deviceXAddr = temp;
433             logger.debug("deviceXAddr: {}", deviceXAddr);
434         }
435         temp = Helper.fetchXML(message, "<tt:Events", "tt:XAddr");
436         if (!temp.isEmpty()) {
437             subscriptionXAddr = eventXAddr = temp;
438             logger.debug("eventsXAddr: {}", eventXAddr);
439         }
440         temp = Helper.fetchXML(message, "<tt:Media", "tt:XAddr");
441         if (!temp.isEmpty()) {
442             mediaXAddr = temp;
443             logger.debug("mediaXAddr: {}", mediaXAddr);
444         }
445
446         ptzXAddr = Helper.fetchXML(message, "<tt:PTZ", "tt:XAddr");
447         if (ptzXAddr.isEmpty()) {
448             ptzDevice = false;
449             logger.debug("Camera has no ONVIF PTZ support.");
450             List<org.openhab.core.thing.Channel> removeChannels = new ArrayList<>();
451             org.openhab.core.thing.Channel channel = ipCameraHandler.getThing().getChannel(CHANNEL_PAN);
452             if (channel != null) {
453                 removeChannels.add(channel);
454             }
455             channel = ipCameraHandler.getThing().getChannel(CHANNEL_TILT);
456             if (channel != null) {
457                 removeChannels.add(channel);
458             }
459             channel = ipCameraHandler.getThing().getChannel(CHANNEL_ZOOM);
460             if (channel != null) {
461                 removeChannels.add(channel);
462             }
463             ipCameraHandler.removeChannels(removeChannels);
464         } else {
465             logger.debug("ptzXAddr: {}", ptzXAddr);
466         }
467     }
468
469     private void parseDateAndTime(String message) {
470         String minute = Helper.fetchXML(message, "UTCDateTime", "Minute>");
471         String hour = Helper.fetchXML(message, "UTCDateTime", "Hour>");
472         String second = Helper.fetchXML(message, "UTCDateTime", "Second>");
473         String day = Helper.fetchXML(message, "UTCDateTime", "Day>");
474         String month = Helper.fetchXML(message, "UTCDateTime", "Month>");
475         String year = Helper.fetchXML(message, "UTCDateTime", "Year>");
476         logger.debug("Camera  UTC dateTime is: {}-{}-{}T{}:{}:{}", year, month, day, hour, minute, second);
477     }
478
479     private String getUTCdateTime() {
480         SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
481         format.setTimeZone(TimeZone.getTimeZone("UTC"));
482         return format.format(new Date());
483     }
484
485     String createNonce() {
486         Random nonce = new SecureRandom();
487         return "" + nonce.nextInt();
488     }
489
490     String encodeBase64(String raw) {
491         return Base64.getEncoder().encodeToString(raw.getBytes());
492     }
493
494     String createDigest(String nOnce, String dateTime) {
495         String beforeEncryption = nOnce + dateTime + password;
496         MessageDigest msgDigest;
497         byte[] encryptedRaw = null;
498         try {
499             msgDigest = MessageDigest.getInstance("SHA-1");
500             msgDigest.reset();
501             msgDigest.update(beforeEncryption.getBytes(StandardCharsets.UTF_8));
502             encryptedRaw = msgDigest.digest();
503         } catch (NoSuchAlgorithmException e) {
504         }
505         return Base64.getEncoder().encodeToString(encryptedRaw);
506     }
507
508     public void sendOnvifRequest(RequestType requestType, String xAddr) {
509         logger.trace("Sending ONVIF request: {} to {}", requestType, xAddr);
510         int port = extractPortFromUrl(xAddr);
511         String security = "";
512         String extraEnvelope = "";
513         String headerTo = "";
514         String getXmlCache = getXml(requestType);
515         if (requestType.equals(RequestType.CreatePullPointSubscription) || requestType.equals(RequestType.PullMessages)
516                 || requestType.equals(RequestType.Renew) || requestType.equals(RequestType.Unsubscribe)) {
517             headerTo = "<a:To s:mustUnderstand=\"1\">" + xAddr + "</a:To>";
518             extraEnvelope = " xmlns:a=\"http://www.w3.org/2005/08/addressing\"";
519         }
520         String headers;
521         if (!password.isEmpty() && !requestType.equals(RequestType.GetSystemDateAndTime)) {
522             String nonce = createNonce();
523             String dateTime = getUTCdateTime();
524             String digest = createDigest(nonce, dateTime);
525             security = "<Security s:mustUnderstand=\"1\" xmlns=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd\"><UsernameToken><Username>"
526                     + user
527                     + "</Username><Password Type=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordDigest\">"
528                     + digest
529                     + "</Password><Nonce EncodingType=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary\">"
530                     + encodeBase64(nonce)
531                     + "</Nonce><Created xmlns=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd\">"
532                     + dateTime + "</Created></UsernameToken></Security>";
533             headers = "<s:Header>" + security + headerTo + "</s:Header>";
534         } else {// GetSystemDateAndTime must not be password protected as per spec.
535             headers = "";
536         }
537         FullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, new HttpMethod("POST"),
538                 removeIPandPortFromUrl(xAddr));
539         String actionString = Helper.fetchXML(getXmlCache, requestType.toString(), "xmlns=\"");
540         request.headers().add("Content-Type",
541                 "application/soap+xml; charset=utf-8; action=\"" + actionString + "/" + requestType + "\"");
542         request.headers().add("Charset", "utf-8");
543         // Tapo brand have different ports for the event xAddr to the other xAddr, can't use 1 port for all ONVIF calls.
544         request.headers().set("Host", ipAddress + ":" + port);
545         request.headers().set("Connection", HttpHeaderValues.CLOSE);
546         request.headers().set("Accept-Encoding", "gzip, deflate");
547         String fullXml = "<s:Envelope xmlns:s=\"http://www.w3.org/2003/05/soap-envelope\"" + extraEnvelope + ">"
548                 + headers
549                 + "<s:Body xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">"
550                 + getXmlCache + "</s:Body></s:Envelope>";
551         request.headers().add("SOAPAction", "\"" + actionString + "/" + requestType + "\"");
552         ByteBuf bbuf = Unpooled.copiedBuffer(fullXml, StandardCharsets.UTF_8);
553         request.headers().set("Content-Length", bbuf.readableBytes());
554         request.content().clear().writeBytes(bbuf);
555
556         Bootstrap localBootstap = bootstrap;
557         if (localBootstap == null) {
558             mainEventLoopGroup = new NioEventLoopGroup(2);
559             localBootstap = new Bootstrap();
560             localBootstap.group(mainEventLoopGroup);
561             localBootstap.channel(NioSocketChannel.class);
562             localBootstap.option(ChannelOption.SO_KEEPALIVE, true);
563             localBootstap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000);
564             localBootstap.option(ChannelOption.SO_SNDBUF, 1024 * 8);
565             localBootstap.option(ChannelOption.SO_RCVBUF, 1024 * 1024);
566             localBootstap.option(ChannelOption.TCP_NODELAY, true);
567             localBootstap.handler(new ChannelInitializer<SocketChannel>() {
568
569                 @Override
570                 public void initChannel(SocketChannel socketChannel) throws Exception {
571                     socketChannel.pipeline().addLast("idleStateHandler", new IdleStateHandler(20, 20, 20));
572                     socketChannel.pipeline().addLast("HttpClientCodec", new HttpClientCodec());
573                     socketChannel.pipeline().addLast("OnvifCodec", new OnvifCodec(getHandle()));
574                 }
575             });
576             bootstrap = localBootstap;
577         }
578         if (!mainEventLoopGroup.isShuttingDown()) {
579             // Tapo brand have different ports for the event xAddr to the other xAddr, can't use 1 port for all calls.
580             localBootstap.connect(new InetSocketAddress(ipAddress, port)).addListener(new ChannelFutureListener() {
581                 @Override
582                 public void operationComplete(@Nullable ChannelFuture future) {
583                     if (future == null) {
584                         return;
585                     }
586                     if (future.isSuccess()) {
587                         Channel ch = future.channel();
588                         ch.writeAndFlush(request);
589                     } else { // an error occurred
590                         if (future.isDone() && !future.isCancelled()) {
591                             Throwable cause = future.cause();
592                             String msg = cause.getMessage();
593                             logger.debug("connect failed - cause {}", cause.getMessage());
594                             if (cause instanceof ConnectTimeoutException) {
595                                 usingEvents = false;// Prevent Unsubscribe from being sent
596                                 ipCameraHandler.cameraCommunicationError(
597                                         "Camera timed out when trying to connect to the ONVIF port:" + port);
598                             } else if ((cause instanceof ConnectException) && msg != null
599                                     && msg.contains("Connection refused")) {
600                                 usingEvents = false;// Prevent Unsubscribe from being sent
601                                 ipCameraHandler.cameraCommunicationError(
602                                         "Camera refused to connect when using ONVIF to port:" + port);
603                             }
604                         }
605                         if (isConnected) {
606                             disconnect();
607                         }
608                     }
609                 }
610             });
611         } else {
612             logger.debug("ONVIF message not sent as connection is shutting down");
613         }
614     }
615
616     OnvifConnection getHandle() {
617         return this;
618     }
619
620     void getIPandPortFromUrl(String url) {
621         int beginIndex = url.indexOf(":");
622         int endIndex = url.indexOf("/", beginIndex);
623         if (beginIndex >= 0 && endIndex == -1) {// 192.168.1.1:8080
624             ipAddress = url.substring(0, beginIndex);
625             onvifPort = Integer.parseInt(url.substring(beginIndex + 1));
626         } else if (beginIndex >= 0 && endIndex > beginIndex) {// 192.168.1.1:8080/foo/bar
627             ipAddress = url.substring(0, beginIndex);
628             onvifPort = Integer.parseInt(url.substring(beginIndex + 1, endIndex));
629         } else {// 192.168.1.1
630             ipAddress = url;
631             deviceXAddr = "http://" + ipAddress + "/onvif/device_service";
632             logger.debug("No ONVIF Port found when parsing: {}", url);
633             return;
634         }
635         deviceXAddr = "http://" + ipAddress + ":" + onvifPort + "/onvif/device_service";
636     }
637
638     public void gotoPreset(int index) {
639         if (ptzDevice) {
640             if (index > 0) {// 0 is reserved for HOME as cameras seem to start at preset 1.
641                 if (presetTokens.isEmpty()) {
642                     logger.warn("Camera did not report any ONVIF preset locations, updating preset tokens now.");
643                     sendPTZRequest(RequestType.GetPresets);
644                 } else {
645                     presetTokenIndex = index - 1;
646                     sendPTZRequest(RequestType.GotoPreset);
647                 }
648             }
649         }
650     }
651
652     public void eventRecieved(String eventMessage) {
653         String topic = Helper.fetchXML(eventMessage, "Topic", "tns1:");
654         if (topic.isEmpty()) {
655             sendOnvifRequest(RequestType.Renew, subscriptionXAddr);
656             return;
657         }
658         String dataName = Helper.fetchXML(eventMessage, "tt:Data", "Name=\"");
659         String dataValue = Helper.fetchXML(eventMessage, "tt:Data", "Value=\"");
660         logger.debug("ONVIF Event Topic: {}, Data: {}, Value: {}", topic, dataName, dataValue);
661         switch (topic) {
662             case "RuleEngine/CellMotionDetector/Motion":
663                 if ("true".equals(dataValue)) {
664                     ipCameraHandler.motionDetected(CHANNEL_CELL_MOTION_ALARM);
665                 } else if ("false".equals(dataValue)) {
666                     ipCameraHandler.noMotionDetected(CHANNEL_CELL_MOTION_ALARM);
667                 }
668                 break;
669             case "VideoSource/MotionAlarm":
670                 if ("true".equals(dataValue)) {
671                     ipCameraHandler.motionDetected(CHANNEL_MOTION_ALARM);
672                 } else if ("false".equals(dataValue)) {
673                     ipCameraHandler.noMotionDetected(CHANNEL_MOTION_ALARM);
674                 }
675                 break;
676             case "AudioAnalytics/Audio/DetectedSound":
677                 if ("true".equals(dataValue)) {
678                     ipCameraHandler.audioDetected();
679                 } else if ("false".equals(dataValue)) {
680                     ipCameraHandler.noAudioDetected();
681                 }
682                 break;
683             case "RuleEngine/FieldDetector/ObjectsInside":
684                 if ("true".equals(dataValue)) {
685                     ipCameraHandler.motionDetected(CHANNEL_FIELD_DETECTION_ALARM);
686                 } else if ("false".equals(dataValue)) {
687                     ipCameraHandler.noMotionDetected(CHANNEL_FIELD_DETECTION_ALARM);
688                 }
689                 break;
690             case "RuleEngine/LineDetector/Crossed":
691                 if ("ObjectId".equals(dataName)) {
692                     ipCameraHandler.motionDetected(CHANNEL_LINE_CROSSING_ALARM);
693                 } else {
694                     ipCameraHandler.noMotionDetected(CHANNEL_LINE_CROSSING_ALARM);
695                 }
696                 break;
697             case "RuleEngine/TamperDetector/Tamper":
698                 if ("true".equals(dataValue)) {
699                     ipCameraHandler.changeAlarmState(CHANNEL_TAMPER_ALARM, OnOffType.ON);
700                 } else if ("false".equals(dataValue)) {
701                     ipCameraHandler.changeAlarmState(CHANNEL_TAMPER_ALARM, OnOffType.OFF);
702                 }
703                 break;
704             case "Device/HardwareFailure/StorageFailure":
705                 if ("true".equals(dataValue)) {
706                     ipCameraHandler.changeAlarmState(CHANNEL_STORAGE_ALARM, OnOffType.ON);
707                 } else if ("false".equals(dataValue)) {
708                     ipCameraHandler.changeAlarmState(CHANNEL_STORAGE_ALARM, OnOffType.OFF);
709                 }
710                 break;
711             case "VideoSource/ImageTooDark/AnalyticsService":
712             case "VideoSource/ImageTooDark/ImagingService":
713             case "VideoSource/ImageTooDark/RecordingService":
714                 if ("true".equals(dataValue)) {
715                     ipCameraHandler.changeAlarmState(CHANNEL_TOO_DARK_ALARM, OnOffType.ON);
716                 } else if ("false".equals(dataValue)) {
717                     ipCameraHandler.changeAlarmState(CHANNEL_TOO_DARK_ALARM, OnOffType.OFF);
718                 }
719                 break;
720             case "VideoSource/GlobalSceneChange/AnalyticsService":
721             case "VideoSource/GlobalSceneChange/ImagingService":
722             case "VideoSource/GlobalSceneChange/RecordingService":
723                 if ("true".equals(dataValue)) {
724                     ipCameraHandler.changeAlarmState(CHANNEL_SCENE_CHANGE_ALARM, OnOffType.ON);
725                 } else if ("false".equals(dataValue)) {
726                     ipCameraHandler.changeAlarmState(CHANNEL_SCENE_CHANGE_ALARM, OnOffType.OFF);
727                 }
728                 break;
729             case "VideoSource/ImageTooBright/AnalyticsService":
730             case "VideoSource/ImageTooBright/ImagingService":
731             case "VideoSource/ImageTooBright/RecordingService":
732                 if ("true".equals(dataValue)) {
733                     ipCameraHandler.changeAlarmState(CHANNEL_TOO_BRIGHT_ALARM, OnOffType.ON);
734                 } else if ("false".equals(dataValue)) {
735                     ipCameraHandler.changeAlarmState(CHANNEL_TOO_BRIGHT_ALARM, OnOffType.OFF);
736                 }
737                 break;
738             case "VideoSource/ImageTooBlurry/AnalyticsService":
739             case "VideoSource/ImageTooBlurry/ImagingService":
740             case "VideoSource/ImageTooBlurry/RecordingService":
741                 if ("true".equals(dataValue)) {
742                     ipCameraHandler.changeAlarmState(CHANNEL_TOO_BLURRY_ALARM, OnOffType.ON);
743                 } else if ("false".equals(dataValue)) {
744                     ipCameraHandler.changeAlarmState(CHANNEL_TOO_BLURRY_ALARM, OnOffType.OFF);
745                 }
746                 break;
747             case "RuleEngine/MyRuleDetector/Visitor":
748                 if ("true".equals(dataValue)) {
749                     ipCameraHandler.changeAlarmState(CHANNEL_DOORBELL, OnOffType.ON);
750                 } else if ("false".equals(dataValue)) {
751                     ipCameraHandler.changeAlarmState(CHANNEL_DOORBELL, OnOffType.OFF);
752                 }
753                 break;
754             case "RuleEngine/MyRuleDetector/VehicleDetect":
755                 if ("true".equals(dataValue)) {
756                     ipCameraHandler.changeAlarmState(CHANNEL_CAR_ALARM, OnOffType.ON);
757                 } else if ("false".equals(dataValue)) {
758                     ipCameraHandler.changeAlarmState(CHANNEL_CAR_ALARM, OnOffType.OFF);
759                 }
760                 break;
761             case "RuleEngine/MyRuleDetector/DogCatDetect":
762                 if ("true".equals(dataValue)) {
763                     ipCameraHandler.changeAlarmState(CHANNEL_ANIMAL_ALARM, OnOffType.ON);
764                 } else if ("false".equals(dataValue)) {
765                     ipCameraHandler.changeAlarmState(CHANNEL_ANIMAL_ALARM, OnOffType.OFF);
766                 }
767                 break;
768             case "RuleEngine/MyRuleDetector/FaceDetect":
769                 if ("true".equals(dataValue)) {
770                     ipCameraHandler.changeAlarmState(CHANNEL_FACE_DETECTED, OnOffType.ON);
771                 } else if ("false".equals(dataValue)) {
772                     ipCameraHandler.changeAlarmState(CHANNEL_FACE_DETECTED, OnOffType.OFF);
773                 }
774                 break;
775             case "RuleEngine/MyRuleDetector/PeopleDetect":
776                 if ("true".equals(dataValue)) {
777                     ipCameraHandler.changeAlarmState(CHANNEL_HUMAN_ALARM, OnOffType.ON);
778                 } else if ("false".equals(dataValue)) {
779                     ipCameraHandler.changeAlarmState(CHANNEL_HUMAN_ALARM, OnOffType.OFF);
780                 }
781                 break;
782             default:
783                 logger.debug("Please report this camera has an un-implemented ONVIF event. Topic: {}", topic);
784         }
785         sendOnvifRequest(RequestType.Renew, subscriptionXAddr);
786     }
787
788     public boolean supportsPTZ() {
789         return ptzDevice;
790     }
791
792     public void getStatus() {
793         if (ptzDevice) {
794             sendPTZRequest(RequestType.GetStatus);
795         }
796     }
797
798     public Float getAbsolutePan() {
799         return currentPanPercentage;
800     }
801
802     public Float getAbsoluteTilt() {
803         return currentTiltPercentage;
804     }
805
806     public Float getAbsoluteZoom() {
807         return currentZoomPercentage;
808     }
809
810     public void setAbsolutePan(Float panValue) {// Value is 0-100% of cameras range
811         if (ptzDevice) {
812             currentPanPercentage = panValue;
813             currentPanCamValue = ((((panRangeMin - panRangeMax) * -1) / 100) * panValue + panRangeMin);
814         }
815     }
816
817     public void setAbsoluteTilt(Float tiltValue) {// Value is 0-100% of cameras range
818         if (ptzDevice) {
819             currentTiltPercentage = tiltValue;
820             currentTiltCamValue = ((((panRangeMin - panRangeMax) * -1) / 100) * tiltValue + tiltRangeMin);
821         }
822     }
823
824     public void setAbsoluteZoom(Float zoomValue) {// Value is 0-100% of cameras range
825         if (ptzDevice) {
826             currentZoomPercentage = zoomValue;
827             currentZoomCamValue = ((((zoomMin - zoomMax) * -1) / 100) * zoomValue + zoomMin);
828         }
829     }
830
831     public void absoluteMove() { // Camera wont move until PTZ values are set, then call this.
832         if (ptzDevice) {
833             sendPTZRequest(RequestType.AbsoluteMove);
834         }
835     }
836
837     public void setSelectedMediaProfile(int mediaProfileIndex) {
838         this.mediaProfileIndex = mediaProfileIndex;
839     }
840
841     List<String> listOfResults(String message, String heading, String key) {
842         List<String> results = new LinkedList<>();
843         String temp = "";
844         for (int startLookingFromIndex = 0; startLookingFromIndex != -1;) {
845             startLookingFromIndex = message.indexOf(heading, startLookingFromIndex);
846             if (startLookingFromIndex >= 0) {
847                 temp = Helper.fetchXML(message.substring(startLookingFromIndex), heading, key);
848                 if (!temp.isEmpty()) {
849                     logger.trace("String was found: {}", temp);
850                     results.add(temp);
851                 } else {
852                     return results;// key string must not exist so stop looking.
853                 }
854                 startLookingFromIndex += temp.length();
855             }
856         }
857         return results;
858     }
859
860     void parsePresets(String message) {
861         List<StateOption> presets = new ArrayList<>();
862         int counter = 1;// Presets start at 1 not 0. HOME may be added to index 0.
863         presetTokens = listOfResults(message, "<tptz:Preset", "token=\"");
864         presetNames = listOfResults(message, "<tptz:Preset", "<tt:Name>");
865         if (presetTokens.size() != presetNames.size()) {
866             logger.warn("Camera did not report the same number of Tokens and Names for PTZ presets");
867             return;
868         }
869         for (String value : presetNames) {
870             presets.add(new StateOption(Integer.toString(counter++), value));
871         }
872         ipCameraHandler.stateDescriptionProvider
873                 .setStateOptions(new ChannelUID(ipCameraHandler.getThing().getUID(), CHANNEL_GOTO_PRESET), presets);
874     }
875
876     void parseProfiles(String message) {
877         mediaProfileTokens = listOfResults(message, "<trt:Profiles", "token=\"");
878         if (mediaProfileIndex >= mediaProfileTokens.size()) {
879             logger.warn(
880                     "You have set the media profile to {} when the camera reported {} profiles. Falling back to mainstream 0.",
881                     mediaProfileIndex, mediaProfileTokens.size());
882             mediaProfileIndex = 0;
883         }
884     }
885
886     void processPTZLocation(String result) {
887         logger.debug("Processing new PTZ location now");
888
889         int beginIndex = result.indexOf("x=\"");
890         int endIndex = result.indexOf("\"", (beginIndex + 3));
891         if (beginIndex >= 0 && endIndex >= 0) {
892             currentPanCamValue = Float.parseFloat(result.substring(beginIndex + 3, endIndex));
893             currentPanPercentage = (((panRangeMin - currentPanCamValue) * -1) / ((panRangeMin - panRangeMax) * -1))
894                     * 100;
895             logger.debug("Pan is updating to: {} and the cam value is {}", Math.round(currentPanPercentage),
896                     currentPanCamValue);
897         } else {
898             logger.warn(
899                     "Binding could not determin the cameras current PTZ location. Not all cameras respond to GetStatus requests.");
900             return;
901         }
902
903         beginIndex = result.indexOf("y=\"");
904         endIndex = result.indexOf("\"", (beginIndex + 3));
905         if (beginIndex >= 0 && endIndex >= 0) {
906             currentTiltCamValue = Float.parseFloat(result.substring(beginIndex + 3, endIndex));
907             currentTiltPercentage = (((tiltRangeMin - currentTiltCamValue) * -1) / ((tiltRangeMin - tiltRangeMax) * -1))
908                     * 100;
909             logger.debug("Tilt is updating to: {} and the cam value is {}", Math.round(currentTiltPercentage),
910                     currentTiltCamValue);
911         } else {
912             return;
913         }
914
915         beginIndex = result.lastIndexOf("x=\"");
916         endIndex = result.indexOf("\"", (beginIndex + 3));
917         if (beginIndex >= 0 && endIndex >= 0) {
918             currentZoomCamValue = Float.parseFloat(result.substring(beginIndex + 3, endIndex));
919             currentZoomPercentage = (((zoomMin - currentZoomCamValue) * -1) / ((zoomMin - zoomMax) * -1)) * 100;
920             logger.debug("Zoom is updating to: {} and the cam value is {}", Math.round(currentZoomPercentage),
921                     currentZoomCamValue);
922         } else {
923             return;
924         }
925     }
926
927     public void sendPTZRequest(RequestType requestType) {
928         if (!isConnected) {
929             logger.debug("ONVIF was not connected when a PTZ request was made, connecting now");
930             connect(usingEvents);
931         }
932         sendOnvifRequest(requestType, ptzXAddr);
933     }
934
935     public void sendEventRequest(RequestType requestType) {
936         sendOnvifRequest(requestType, eventXAddr);
937     }
938
939     public void connect(boolean useEvents) {
940         connecting.lock();
941         try {
942             if (!isConnected) {
943                 logger.debug("Connecting {} to ONVIF", ipAddress);
944                 threadPool = Executors.newScheduledThreadPool(2);
945                 sendOnvifRequest(RequestType.GetSystemDateAndTime, deviceXAddr);
946                 usingEvents = useEvents;
947                 sendOnvifRequest(RequestType.GetCapabilities, deviceXAddr);
948             }
949         } finally {
950             connecting.unlock();
951         }
952     }
953
954     public boolean isConnected() {
955         connecting.lock();
956         try {
957             return isConnected;
958         } finally {
959             connecting.unlock();
960         }
961     }
962
963     public boolean getEventsSupported() {
964         return supportsEvents;
965     }
966
967     public void setIsConnected(boolean isConnected) {
968         connecting.lock();
969         try {
970             this.isConnected = isConnected;
971         } finally {
972             connecting.unlock();
973         }
974     }
975
976     private void cleanup() {
977         if (!isConnected && !mainEventLoopGroup.isShuttingDown()) {
978             try {
979                 mainEventLoopGroup.shutdownGracefully();
980                 mainEventLoopGroup.awaitTermination(3, TimeUnit.SECONDS);
981             } catch (InterruptedException e) {
982                 logger.warn("ONVIF was not cleanly shutdown, due to being interrupted");
983             } finally {
984                 logger.debug("Eventloop is shutdown: {}", mainEventLoopGroup.isShutdown());
985                 bootstrap = null;
986                 threadPool.shutdown();
987             }
988         }
989     }
990
991     public void disconnect() {
992         connecting.lock();// Lock out multiple disconnect()/connect() attempts as we try to send Unsubscribe.
993         try {
994             if (bootstrap != null) {
995                 if (isConnected && usingEvents && !mainEventLoopGroup.isShuttingDown()) {
996                     // Only makes sense to send if connected
997                     // Some cameras may continue to send events even when they can't reach a server.
998                     sendOnvifRequest(RequestType.Unsubscribe, subscriptionXAddr);
999                 }
1000                 // give time for the Unsubscribe request to be sent, shutdownGracefully will try to send it first.
1001                 threadPool.schedule(this::cleanup, 50, TimeUnit.MILLISECONDS);
1002             } else {
1003                 cleanup();
1004             }
1005
1006             isConnected = false;// isConnected is not thread safe, connecting.lock() used as fix.
1007         } finally {
1008             connecting.unlock();
1009         }
1010     }
1011 }