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