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