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