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