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