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