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