2 * Copyright (c) 2010-2024 Contributors to the openHAB project
4 * See the NOTICE file(s) distributed with this work for additional
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
11 * SPDX-License-Identifier: EPL-2.0
13 package org.openhab.binding.ipcamera.internal.onvif;
15 import static org.openhab.binding.ipcamera.internal.IpCameraBindingConstants.*;
17 import java.net.ConnectException;
18 import java.net.InetSocketAddress;
19 import java.nio.charset.StandardCharsets;
20 import java.security.MessageDigest;
21 import java.security.NoSuchAlgorithmException;
22 import java.security.SecureRandom;
23 import java.text.SimpleDateFormat;
24 import java.util.ArrayList;
25 import java.util.Base64;
26 import java.util.Date;
27 import java.util.LinkedList;
28 import java.util.List;
29 import java.util.Random;
30 import java.util.TimeZone;
31 import java.util.concurrent.Executors;
32 import java.util.concurrent.ScheduledExecutorService;
33 import java.util.concurrent.TimeUnit;
34 import java.util.concurrent.locks.ReentrantLock;
36 import org.eclipse.jdt.annotation.NonNullByDefault;
37 import org.eclipse.jdt.annotation.Nullable;
38 import org.openhab.binding.ipcamera.internal.Helper;
39 import org.openhab.binding.ipcamera.internal.handler.IpCameraHandler;
40 import org.openhab.core.library.types.OnOffType;
41 import org.openhab.core.thing.ChannelUID;
42 import org.openhab.core.types.StateOption;
43 import org.openhab.core.util.StringUtils;
44 import org.slf4j.Logger;
45 import org.slf4j.LoggerFactory;
47 import io.netty.bootstrap.Bootstrap;
48 import io.netty.buffer.ByteBuf;
49 import io.netty.buffer.Unpooled;
50 import io.netty.channel.Channel;
51 import io.netty.channel.ChannelFuture;
52 import io.netty.channel.ChannelFutureListener;
53 import io.netty.channel.ChannelInitializer;
54 import io.netty.channel.ChannelOption;
55 import io.netty.channel.ConnectTimeoutException;
56 import io.netty.channel.EventLoopGroup;
57 import io.netty.channel.nio.NioEventLoopGroup;
58 import io.netty.channel.socket.SocketChannel;
59 import io.netty.channel.socket.nio.NioSocketChannel;
60 import io.netty.handler.codec.http.DefaultFullHttpRequest;
61 import io.netty.handler.codec.http.FullHttpRequest;
62 import io.netty.handler.codec.http.HttpClientCodec;
63 import io.netty.handler.codec.http.HttpHeaderValues;
64 import io.netty.handler.codec.http.HttpMethod;
65 import io.netty.handler.codec.http.HttpVersion;
66 import io.netty.handler.timeout.IdleStateHandler;
69 * The {@link OnvifConnection} This is a basic Netty implementation for connecting and communicating to ONVIF cameras.
71 * @author Matthew Skinner - Initial contribution
72 * @author Kai Kreuzer - Improve handling for certain cameras
76 public class OnvifConnection {
77 public enum RequestType {
87 CreatePullPointSubscription,
91 GetServiceCapabilities,
107 GetConfigurationOptions,
116 private final Logger logger = LoggerFactory.getLogger(getClass());
117 private ScheduledExecutorService threadPool = Executors.newScheduledThreadPool(2);
118 private @Nullable Bootstrap bootstrap;
119 private EventLoopGroup mainEventLoopGroup = new NioEventLoopGroup(2);
120 private ReentrantLock connecting = new ReentrantLock();
121 private String ipAddress = "";
122 private String user = "";
123 private String password = "";
124 private int onvifPort = 80;
125 private String deviceXAddr = "http://" + ipAddress + "/onvif/device_service";
126 private String eventXAddr = "http://" + ipAddress + "/onvif/device_service";
127 private String mediaXAddr = "http://" + ipAddress + "/onvif/device_service";
128 @SuppressWarnings("unused")
129 private String imagingXAddr = "http://" + ipAddress + "/onvif/device_service";
130 private String ptzXAddr = "http://" + ipAddress + "/onvif/ptz_service";
131 private String subscriptionXAddr = "http://" + ipAddress + "/onvif/device_service";
132 private boolean connectError = false;
133 private boolean refusedError = false;
134 private boolean isConnected = false;
135 private int mediaProfileIndex = 0;
136 private String snapshotUri = "";
137 private String rtspUri = "";
138 private IpCameraHandler ipCameraHandler;
139 private boolean usingEvents = false;
141 // These hold the cameras PTZ position in the range that the camera uses, ie
143 private Float panRangeMin = -1.0f;
144 private Float panRangeMax = 1.0f;
145 private Float tiltRangeMin = -1.0f;
146 private Float tiltRangeMax = 1.0f;
147 private Float zoomMin = 0.0f;
148 private Float zoomMax = 1.0f;
149 // These hold the PTZ values for updating openHABs controls in 0-100 range
150 private Float currentPanPercentage = 0.0f;
151 private Float currentTiltPercentage = 0.0f;
152 private Float currentZoomPercentage = 0.0f;
153 private Float currentPanCamValue = 0.0f;
154 private Float currentTiltCamValue = 0.0f;
155 private Float currentZoomCamValue = 0.0f;
156 private String ptzNodeToken = "000";
157 private String ptzConfigToken = "000";
158 private int presetTokenIndex = 0;
159 private List<String> presetTokens = new LinkedList<>();
160 private List<String> presetNames = new LinkedList<>();
161 private List<String> mediaProfileTokens = new LinkedList<>();
162 private boolean ptzDevice = true;
164 public OnvifConnection(IpCameraHandler ipCameraHandler, String ipAddress, String user, String password) {
165 this.ipCameraHandler = ipCameraHandler;
166 if (!ipAddress.isEmpty()) {
168 this.password = password;
169 getIPandPortFromUrl(ipAddress);
173 private String getXml(RequestType requestType) {
175 switch (requestType) {
177 return "<AbsoluteMove xmlns=\"http://www.onvif.org/ver20/ptz/wsdl\"><ProfileToken>"
178 + mediaProfileTokens.get(mediaProfileIndex) + "</ProfileToken><Position><PanTilt x=\""
179 + currentPanCamValue + "\" y=\"" + currentTiltCamValue
180 + "\" space=\"http://www.onvif.org/ver10/tptz/PanTiltSpaces/PositionGenericSpace\">\n"
181 + "</PanTilt>\n" + "<Zoom x=\"" + currentZoomCamValue
182 + "\" space=\"http://www.onvif.org/ver10/tptz/ZoomSpaces/PositionGenericSpace\">\n"
183 + "</Zoom>\n" + "</Position>\n"
184 + "<Speed><PanTilt x=\"0.1\" y=\"0.1\" space=\"http://www.onvif.org/ver10/tptz/PanTiltSpaces/GenericSpeedSpace\"></PanTilt><Zoom x=\"1.0\" space=\"http://www.onvif.org/ver10/tptz/ZoomSpaces/ZoomGenericSpeedSpace\"></Zoom>\n"
185 + "</Speed></AbsoluteMove>";
186 case AddPTZConfiguration: // not tested to work yet
187 return "<AddPTZConfiguration xmlns=\"http://www.onvif.org/ver20/ptz/wsdl\"><ProfileToken>"
188 + mediaProfileTokens.get(mediaProfileIndex) + "</ProfileToken><ConfigurationToken>"
189 + ptzConfigToken + "</ConfigurationToken></AddPTZConfiguration>";
190 case ContinuousMoveLeft:
191 return "<ContinuousMove xmlns=\"http://www.onvif.org/ver20/ptz/wsdl\"><ProfileToken>"
192 + mediaProfileTokens.get(mediaProfileIndex)
193 + "</ProfileToken><Velocity><PanTilt x=\"-0.5\" y=\"0\" xmlns=\"http://www.onvif.org/ver10/schema\"/></Velocity></ContinuousMove>";
194 case ContinuousMoveRight:
195 return "<ContinuousMove xmlns=\"http://www.onvif.org/ver20/ptz/wsdl\"><ProfileToken>"
196 + mediaProfileTokens.get(mediaProfileIndex)
197 + "</ProfileToken><Velocity><PanTilt x=\"0.5\" y=\"0\" xmlns=\"http://www.onvif.org/ver10/schema\"/></Velocity></ContinuousMove>";
198 case ContinuousMoveUp:
199 return "<ContinuousMove xmlns=\"http://www.onvif.org/ver20/ptz/wsdl\"><ProfileToken>"
200 + mediaProfileTokens.get(mediaProfileIndex)
201 + "</ProfileToken><Velocity><PanTilt x=\"0\" y=\"-0.5\" xmlns=\"http://www.onvif.org/ver10/schema\"/></Velocity></ContinuousMove>";
202 case ContinuousMoveDown:
203 return "<ContinuousMove xmlns=\"http://www.onvif.org/ver20/ptz/wsdl\"><ProfileToken>"
204 + mediaProfileTokens.get(mediaProfileIndex)
205 + "</ProfileToken><Velocity><PanTilt x=\"0\" y=\"0.5\" xmlns=\"http://www.onvif.org/ver10/schema\"/></Velocity></ContinuousMove>";
207 return "<Stop xmlns=\"http://www.onvif.org/ver20/ptz/wsdl\"><ProfileToken>"
208 + mediaProfileTokens.get(mediaProfileIndex)
209 + "</ProfileToken><PanTilt>true</PanTilt><Zoom>true</Zoom></Stop>";
210 case ContinuousMoveIn:
211 return "<ContinuousMove xmlns=\"http://www.onvif.org/ver20/ptz/wsdl\"><ProfileToken>"
212 + mediaProfileTokens.get(mediaProfileIndex)
213 + "</ProfileToken><Velocity><Zoom x=\"0.5\" xmlns=\"http://www.onvif.org/ver10/schema\"/></Velocity></ContinuousMove>";
214 case ContinuousMoveOut:
215 return "<ContinuousMove xmlns=\"http://www.onvif.org/ver20/ptz/wsdl\"><ProfileToken>"
216 + mediaProfileTokens.get(mediaProfileIndex)
217 + "</ProfileToken><Velocity><Zoom x=\"-0.5\" xmlns=\"http://www.onvif.org/ver10/schema\"/></Velocity></ContinuousMove>";
218 case CreatePullPointSubscription:
219 return "<CreatePullPointSubscription xmlns=\"http://www.onvif.org/ver10/events/wsdl\"><InitialTerminationTime>PT600S</InitialTerminationTime></CreatePullPointSubscription>";
220 case GetCapabilities:
221 return "<GetCapabilities xmlns=\"http://www.onvif.org/ver10/device/wsdl\"><Category>All</Category></GetCapabilities>";
223 case GetDeviceInformation:
224 return "<GetDeviceInformation xmlns=\"http://www.onvif.org/ver10/device/wsdl\"/>";
226 return "<GetProfiles xmlns=\"http://www.onvif.org/ver10/media/wsdl\"/>";
227 case GetServiceCapabilities:
228 return "<GetServiceCapabilities xmlns=\"http://docs.oasis-open.org/wsn/b-2/\"></GetServiceCapabilities>";
230 return "<GetSnapshotUri xmlns=\"http://www.onvif.org/ver10/media/wsdl\"><ProfileToken>"
231 + mediaProfileTokens.get(mediaProfileIndex) + "</ProfileToken></GetSnapshotUri>";
233 return "<GetStreamUri xmlns=\"http://www.onvif.org/ver10/media/wsdl\"><StreamSetup><Stream xmlns=\"http://www.onvif.org/ver10/schema\">RTP-Unicast</Stream><Transport xmlns=\"http://www.onvif.org/ver10/schema\"><Protocol>RTSP</Protocol></Transport></StreamSetup><ProfileToken>"
234 + mediaProfileTokens.get(mediaProfileIndex) + "</ProfileToken></GetStreamUri>";
235 case GetSystemDateAndTime:
236 return "<GetSystemDateAndTime xmlns=\"http://www.onvif.org/ver10/device/wsdl\"/>";
238 return "<Subscribe xmlns=\"http://docs.oasis-open.org/wsn/b-2/\"><ConsumerReference><Address>http://"
239 + ipCameraHandler.hostIp + ":" + SERVLET_PORT + "/ipcamera/"
240 + ipCameraHandler.getThing().getUID().getId()
241 + "/OnvifEvent</Address></ConsumerReference></Subscribe>";
243 return "<Unsubscribe xmlns=\"http://docs.oasis-open.org/wsn/b-2/\"></Unsubscribe>";
245 return "<PullMessages xmlns=\"http://www.onvif.org/ver10/events/wsdl\"><Timeout>PT8S</Timeout><MessageLimit>1</MessageLimit></PullMessages>";
246 case GetEventProperties:
247 return "<GetEventProperties xmlns=\"http://www.onvif.org/ver10/events/wsdl\"/>";
248 case RelativeMoveLeft:
249 return "<RelativeMove xmlns=\"http://www.onvif.org/ver20/ptz/wsdl\"><ProfileToken>"
250 + mediaProfileTokens.get(mediaProfileIndex)
251 + "</ProfileToken><Translation><PanTilt x=\"0.05000000\" y=\"0\" xmlns=\"http://www.onvif.org/ver10/schema\"/></Translation></RelativeMove>";
252 case RelativeMoveRight:
253 return "<RelativeMove xmlns=\"http://www.onvif.org/ver20/ptz/wsdl\"><ProfileToken>"
254 + mediaProfileTokens.get(mediaProfileIndex)
255 + "</ProfileToken><Translation><PanTilt x=\"-0.05000000\" y=\"0\" xmlns=\"http://www.onvif.org/ver10/schema\"/></Translation></RelativeMove>";
257 return "<RelativeMove xmlns=\"http://www.onvif.org/ver20/ptz/wsdl\"><ProfileToken>"
258 + mediaProfileTokens.get(mediaProfileIndex)
259 + "</ProfileToken><Translation><PanTilt x=\"0\" y=\"0.100000000\" xmlns=\"http://www.onvif.org/ver10/schema\"/></Translation></RelativeMove>";
260 case RelativeMoveDown:
261 return "<RelativeMove xmlns=\"http://www.onvif.org/ver20/ptz/wsdl\"><ProfileToken>"
262 + mediaProfileTokens.get(mediaProfileIndex)
263 + "</ProfileToken><Translation><PanTilt x=\"0\" y=\"-0.100000000\" xmlns=\"http://www.onvif.org/ver10/schema\"/></Translation></RelativeMove>";
265 return "<RelativeMove xmlns=\"http://www.onvif.org/ver20/ptz/wsdl\"><ProfileToken>"
266 + mediaProfileTokens.get(mediaProfileIndex)
267 + "</ProfileToken><Translation><Zoom x=\"0.0240506344\" xmlns=\"http://www.onvif.org/ver10/schema\"/></Translation></RelativeMove>";
268 case RelativeMoveOut:
269 return "<RelativeMove xmlns=\"http://www.onvif.org/ver20/ptz/wsdl\"><ProfileToken>"
270 + mediaProfileTokens.get(mediaProfileIndex)
271 + "</ProfileToken><Translation><Zoom x=\"-0.0240506344\" xmlns=\"http://www.onvif.org/ver10/schema\"/></Translation></RelativeMove>";
273 return "<Renew xmlns=\"http://docs.oasis-open.org/wsn/b-2\"><TerminationTime>PT1M</TerminationTime></Renew>";
274 case GetConfigurations:
275 return "<GetConfigurations xmlns=\"http://www.onvif.org/ver20/ptz/wsdl\"></GetConfigurations>";
276 case GetConfigurationOptions:
277 return "<GetConfigurationOptions xmlns=\"http://www.onvif.org/ver20/ptz/wsdl\"><ConfigurationToken>"
278 + ptzConfigToken + "</ConfigurationToken></GetConfigurationOptions>";
279 case GetConfiguration:
280 return "<GetConfiguration xmlns=\"http://www.onvif.org/ver20/ptz/wsdl\"><PTZConfigurationToken>"
281 + ptzConfigToken + "</PTZConfigurationToken></GetConfiguration>";
282 case SetConfiguration:// not tested to work yet
283 return "<SetConfiguration xmlns=\"http://www.onvif.org/ver20/ptz/wsdl\"><PTZConfiguration><NodeToken>"
285 + "</NodeToken><DefaultAbsolutePantTiltPositionSpace>AbsolutePanTiltPositionSpace</DefaultAbsolutePantTiltPositionSpace><DefaultAbsoluteZoomPositionSpace>AbsoluteZoomPositionSpace</DefaultAbsoluteZoomPositionSpace></PTZConfiguration></SetConfiguration>";
287 return "<GetNodes xmlns=\"http://www.onvif.org/ver20/ptz/wsdl\"></GetNodes>";
289 return "<GetStatus xmlns=\"http://www.onvif.org/ver20/ptz/wsdl\"><ProfileToken>"
290 + mediaProfileTokens.get(mediaProfileIndex) + "</ProfileToken></GetStatus>";
292 return "<GotoPreset xmlns=\"http://www.onvif.org/ver20/ptz/wsdl\"><ProfileToken>"
293 + mediaProfileTokens.get(mediaProfileIndex) + "</ProfileToken><PresetToken>"
294 + presetTokens.get(presetTokenIndex) + "</PresetToken></GotoPreset>";
296 return "<GetPresets xmlns=\"http://www.onvif.org/ver20/ptz/wsdl\"><ProfileToken>"
297 + mediaProfileTokens.get(mediaProfileIndex) + "</ProfileToken></GetPresets>";
299 } catch (IndexOutOfBoundsException e) {
301 logger.debug("IndexOutOfBoundsException occured, camera is not connected via ONVIF: {}",
304 logger.debug("IndexOutOfBoundsException occured, {}", e.getMessage());
310 public void processReply(String message) {
311 logger.trace("ONVIF reply is: {}", message);
312 if (message.contains("PullMessagesResponse")) {
313 eventRecieved(message);
314 } else if (message.contains("RenewResponse")) {
315 sendOnvifRequest(RequestType.PullMessages, subscriptionXAddr);
316 } else if (message.contains("GetSystemDateAndTimeResponse")) {// 1st to be sent.
317 setIsConnected(true);
318 sendOnvifRequest(RequestType.GetCapabilities, deviceXAddr);
319 parseDateAndTime(message);
320 logger.debug("openHAB UTC dateTime is: {}", getUTCdateTime());
321 } else if (message.contains("GetCapabilitiesResponse")) {// 2nd to be sent.
323 sendOnvifRequest(RequestType.GetProfiles, mediaXAddr);
324 } else if (message.contains("GetProfilesResponse")) {// 3rd to be sent.
325 setIsConnected(true);
326 parseProfiles(message);
327 sendOnvifRequest(RequestType.GetSnapshotUri, mediaXAddr);
328 sendOnvifRequest(RequestType.GetStreamUri, mediaXAddr);
330 sendPTZRequest(RequestType.GetNodes);
332 if (usingEvents) {// stops API cameras from getting sent ONVIF events.
333 sendOnvifRequest(RequestType.GetEventProperties, eventXAddr);
334 sendOnvifRequest(RequestType.GetServiceCapabilities, eventXAddr);
336 } else if (message.contains("GetServiceCapabilitiesResponse")) {
337 if (message.contains("WSSubscriptionPolicySupport=\"true\"")) {
338 sendOnvifRequest(RequestType.Subscribe, eventXAddr);
340 } else if (message.contains("GetEventPropertiesResponse")) {
341 sendOnvifRequest(RequestType.CreatePullPointSubscription, eventXAddr);
342 } else if (message.contains("CreatePullPointSubscriptionResponse")) {
343 subscriptionXAddr = Helper.fetchXML(message, "SubscriptionReference>", "Address>");
344 logger.debug("subscriptionXAddr={}", subscriptionXAddr);
345 sendOnvifRequest(RequestType.PullMessages, subscriptionXAddr);
346 } else if (message.contains("GetStatusResponse")) {
347 processPTZLocation(message);
348 } else if (message.contains("GetPresetsResponse")) {
349 parsePresets(message);
350 } else if (message.contains("GetConfigurationsResponse")) {
351 sendPTZRequest(RequestType.GetPresets);
352 ptzConfigToken = Helper.fetchXML(message, "PTZConfiguration", "token=\"");
353 logger.debug("ptzConfigToken={}", ptzConfigToken);
354 sendPTZRequest(RequestType.GetConfigurationOptions);
355 } else if (message.contains("GetNodesResponse")) {
356 sendPTZRequest(RequestType.GetStatus);
357 ptzNodeToken = Helper.fetchXML(message, "", "token=\"");
358 logger.debug("ptzNodeToken={}", ptzNodeToken);
359 sendPTZRequest(RequestType.GetConfigurations);
360 } else if (message.contains("GetDeviceInformationResponse")) {
361 logger.debug("GetDeviceInformationResponse received");
362 } else if (message.contains("GetSnapshotUriResponse")) {
363 String url = Helper.fetchXML(message, ":MediaUri", ":Uri");
364 if (!url.isBlank()) {
365 snapshotUri = removeIPfromUrl(url);
366 logger.debug("GetSnapshotUri: {}", snapshotUri);
367 if (ipCameraHandler.snapshotUri.isEmpty()
368 && !"ffmpeg".equals(ipCameraHandler.cameraConfig.getSnapshotUrl())) {
369 ipCameraHandler.snapshotUri = snapshotUri;
372 } else if (message.contains("GetStreamUriResponse")) {
373 String xml = StringUtils.unEscapeXml(Helper.fetchXML(message, ":MediaUri", ":Uri>"));
376 logger.debug("GetStreamUri: {}", rtspUri);
377 if (ipCameraHandler.cameraConfig.getFfmpegInput().isEmpty()) {
378 ipCameraHandler.rtspUri = rtspUri;
385 * The {@link removeIPfromUrl} Will throw away all text before the cameras IP, also removes the IP and the PORT
386 * leaving just the URL.
388 * @author Matthew Skinner - Initial contribution
390 String removeIPfromUrl(String url) {
391 int index = url.indexOf("//");
392 if (index != -1) {// now remove the :port
393 index = url.indexOf("/", index + 2);
396 logger.debug("We hit an issue parsing url: {}", url);
399 return url.substring(index);
402 String extractIPportFromUrl(String url) {
403 int startIndex = url.indexOf("//") + 2;
404 int endIndex = url.indexOf("/", startIndex);// skip past any :port to the slash /
405 if (startIndex != -1 && endIndex != -1) {
406 return url.substring(startIndex, endIndex);
408 logger.debug("We hit an issue extracting IP:PORT from url: {}", url);
412 int extractPortFromUrl(String url) {
413 int startIndex = url.indexOf("//") + 2;// skip past http://
414 startIndex = url.indexOf(":", startIndex);
415 if (startIndex == -1) {// no port defined so use port 80
418 int endIndex = url.indexOf("/", startIndex);// skip past any :port to the slash /
419 if (endIndex == -1) {
422 return Integer.parseInt(url.substring(startIndex + 1, endIndex));
425 void parseXAddr(String message) {
426 // Normally I would search '<tt:XAddr>' instead but Foscam needed this work around.
427 String temp = Helper.fetchXML(message, "<tt:Device", "tt:XAddr");
428 if (!temp.isEmpty()) {
430 logger.debug("deviceXAddr: {}", deviceXAddr);
432 temp = Helper.fetchXML(message, "<tt:Events", "tt:XAddr");
433 if (!temp.isEmpty()) {
434 subscriptionXAddr = eventXAddr = temp;
435 logger.debug("eventsXAddr: {}", eventXAddr);
437 temp = Helper.fetchXML(message, "<tt:Media", "tt:XAddr");
438 if (!temp.isEmpty()) {
440 logger.debug("mediaXAddr: {}", mediaXAddr);
443 ptzXAddr = Helper.fetchXML(message, "<tt:PTZ", "tt:XAddr");
444 if (ptzXAddr.isEmpty()) {
446 logger.debug("Camera has no ONVIF PTZ support.");
447 List<org.openhab.core.thing.Channel> removeChannels = new ArrayList<>();
448 org.openhab.core.thing.Channel channel = ipCameraHandler.getThing().getChannel(CHANNEL_PAN);
449 if (channel != null) {
450 removeChannels.add(channel);
452 channel = ipCameraHandler.getThing().getChannel(CHANNEL_TILT);
453 if (channel != null) {
454 removeChannels.add(channel);
456 channel = ipCameraHandler.getThing().getChannel(CHANNEL_ZOOM);
457 if (channel != null) {
458 removeChannels.add(channel);
460 ipCameraHandler.removeChannels(removeChannels);
462 logger.debug("ptzXAddr: {}", ptzXAddr);
466 private void parseDateAndTime(String message) {
467 String minute = Helper.fetchXML(message, "UTCDateTime", "Minute>");
468 String hour = Helper.fetchXML(message, "UTCDateTime", "Hour>");
469 String second = Helper.fetchXML(message, "UTCDateTime", "Second>");
470 String day = Helper.fetchXML(message, "UTCDateTime", "Day>");
471 String month = Helper.fetchXML(message, "UTCDateTime", "Month>");
472 String year = Helper.fetchXML(message, "UTCDateTime", "Year>");
473 logger.debug("Camera UTC dateTime is: {}-{}-{}T{}:{}:{}", year, month, day, hour, minute, second);
476 private String getUTCdateTime() {
477 SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
478 format.setTimeZone(TimeZone.getTimeZone("UTC"));
479 return format.format(new Date());
482 String createNonce() {
483 Random nonce = new SecureRandom();
484 return "" + nonce.nextInt();
487 String encodeBase64(String raw) {
488 return Base64.getEncoder().encodeToString(raw.getBytes());
491 String createDigest(String nOnce, String dateTime) {
492 String beforeEncryption = nOnce + dateTime + password;
493 MessageDigest msgDigest;
494 byte[] encryptedRaw = null;
496 msgDigest = MessageDigest.getInstance("SHA-1");
498 msgDigest.update(beforeEncryption.getBytes(StandardCharsets.UTF_8));
499 encryptedRaw = msgDigest.digest();
500 } catch (NoSuchAlgorithmException e) {
502 return Base64.getEncoder().encodeToString(encryptedRaw);
505 public void sendOnvifRequest(RequestType requestType, String xAddr) {
506 logger.trace("Sending ONVIF request: {}", requestType);
507 String security = "";
508 String extraEnvelope = "";
509 String headerTo = "";
510 String getXmlCache = getXml(requestType);
511 if (requestType.equals(RequestType.CreatePullPointSubscription) || requestType.equals(RequestType.PullMessages)
512 || requestType.equals(RequestType.Renew) || requestType.equals(RequestType.Unsubscribe)) {
513 headerTo = "<a:To s:mustUnderstand=\"1\">" + xAddr + "</a:To>";
514 extraEnvelope = " xmlns:a=\"http://www.w3.org/2005/08/addressing\"";
517 if (!password.isEmpty() && !requestType.equals(RequestType.GetSystemDateAndTime)) {
518 String nonce = createNonce();
519 String dateTime = getUTCdateTime();
520 String digest = createDigest(nonce, dateTime);
521 security = "<Security s:mustUnderstand=\"1\" xmlns=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd\"><UsernameToken><Username>"
523 + "</Username><Password Type=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordDigest\">"
525 + "</Password><Nonce EncodingType=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary\">"
526 + encodeBase64(nonce)
527 + "</Nonce><Created xmlns=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd\">"
528 + dateTime + "</Created></UsernameToken></Security>";
529 headers = "<s:Header>" + security + headerTo + "</s:Header>";
530 } else {// GetSystemDateAndTime must not be password protected as per spec.
533 FullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, new HttpMethod("POST"),
534 removeIPfromUrl(xAddr));
535 String actionString = Helper.fetchXML(getXmlCache, requestType.toString(), "xmlns=\"");
536 request.headers().add("Content-Type",
537 "application/soap+xml; charset=utf-8; action=\"" + actionString + "/" + requestType + "\"");
538 request.headers().add("Charset", "utf-8");
539 request.headers().set("Host", ipAddress + ":" + onvifPort);
540 request.headers().set("Connection", HttpHeaderValues.CLOSE);
541 request.headers().set("Accept-Encoding", "gzip, deflate");
542 String fullXml = "<s:Envelope xmlns:s=\"http://www.w3.org/2003/05/soap-envelope\"" + extraEnvelope + ">"
544 + "<s:Body xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">"
545 + getXmlCache + "</s:Body></s:Envelope>";
546 request.headers().add("SOAPAction", "\"" + actionString + "/" + requestType + "\"");
547 ByteBuf bbuf = Unpooled.copiedBuffer(fullXml, StandardCharsets.UTF_8);
548 request.headers().set("Content-Length", bbuf.readableBytes());
549 request.content().clear().writeBytes(bbuf);
551 Bootstrap localBootstap = bootstrap;
552 if (localBootstap == null) {
553 mainEventLoopGroup = new NioEventLoopGroup(2);
554 localBootstap = new Bootstrap();
555 localBootstap.group(mainEventLoopGroup);
556 localBootstap.channel(NioSocketChannel.class);
557 localBootstap.option(ChannelOption.SO_KEEPALIVE, true);
558 localBootstap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000);
559 localBootstap.option(ChannelOption.SO_SNDBUF, 1024 * 8);
560 localBootstap.option(ChannelOption.SO_RCVBUF, 1024 * 1024);
561 localBootstap.option(ChannelOption.TCP_NODELAY, true);
562 localBootstap.handler(new ChannelInitializer<SocketChannel>() {
565 public void initChannel(SocketChannel socketChannel) throws Exception {
566 socketChannel.pipeline().addLast("idleStateHandler", new IdleStateHandler(20, 20, 20));
567 socketChannel.pipeline().addLast("HttpClientCodec", new HttpClientCodec());
568 socketChannel.pipeline().addLast("OnvifCodec", new OnvifCodec(getHandle()));
571 bootstrap = localBootstap;
573 if (!mainEventLoopGroup.isShuttingDown()) {
574 localBootstap.connect(new InetSocketAddress(ipAddress, onvifPort)).addListener(new ChannelFutureListener() {
576 public void operationComplete(@Nullable ChannelFuture future) {
577 if (future == null) {
580 if (future.isSuccess()) {
581 connectError = false;
582 Channel ch = future.channel();
583 ch.writeAndFlush(request);
584 } else { // an error occurred
585 if (future.isDone() && !future.isCancelled()) {
586 Throwable cause = future.cause();
587 String msg = cause.getMessage();
588 logger.trace("connect failed - cause {}", cause.getMessage());
589 if (cause instanceof ConnectTimeoutException) {
590 logger.debug("Camera is not reachable on IP {}", ipAddress);
592 } else if ((cause instanceof ConnectException) && msg != null
593 && msg.contains("Connection refused")) {
594 logger.debug("Camera ONVIF port {} is refused.", onvifPort);
605 logger.debug("ONVIF message not sent as connection is shutting down");
609 OnvifConnection getHandle() {
613 void getIPandPortFromUrl(String url) {
614 int beginIndex = url.indexOf(":");
615 int endIndex = url.indexOf("/", beginIndex);
616 if (beginIndex >= 0 && endIndex == -1) {// 192.168.1.1:8080
617 ipAddress = url.substring(0, beginIndex);
618 onvifPort = Integer.parseInt(url.substring(beginIndex + 1));
619 } else if (beginIndex >= 0 && endIndex > beginIndex) {// 192.168.1.1:8080/foo/bar
620 ipAddress = url.substring(0, beginIndex);
621 onvifPort = Integer.parseInt(url.substring(beginIndex + 1, endIndex));
622 } else {// 192.168.1.1
624 deviceXAddr = "http://" + ipAddress + "/onvif/device_service";
625 logger.debug("No ONVIF Port found when parsing: {}", url);
628 deviceXAddr = "http://" + ipAddress + ":" + onvifPort + "/onvif/device_service";
631 public void gotoPreset(int index) {
633 if (index > 0) {// 0 is reserved for HOME as cameras seem to start at preset 1.
634 if (presetTokens.isEmpty()) {
635 logger.warn("Camera did not report any ONVIF preset locations, updating preset tokens now.");
636 sendPTZRequest(RequestType.GetPresets);
638 presetTokenIndex = index - 1;
639 sendPTZRequest(RequestType.GotoPreset);
645 public void eventRecieved(String eventMessage) {
646 String topic = Helper.fetchXML(eventMessage, "Topic", "tns1:");
647 if (topic.isEmpty()) {
648 sendOnvifRequest(RequestType.Renew, subscriptionXAddr);
651 String dataName = Helper.fetchXML(eventMessage, "tt:Data", "Name=\"");
652 String dataValue = Helper.fetchXML(eventMessage, "tt:Data", "Value=\"");
653 logger.debug("ONVIF Event Topic: {}, Data: {}, Value: {}", topic, dataName, dataValue);
655 case "RuleEngine/CellMotionDetector/Motion":
656 if ("true".equals(dataValue)) {
657 ipCameraHandler.motionDetected(CHANNEL_CELL_MOTION_ALARM);
658 } else if ("false".equals(dataValue)) {
659 ipCameraHandler.noMotionDetected(CHANNEL_CELL_MOTION_ALARM);
662 case "VideoSource/MotionAlarm":
663 if ("true".equals(dataValue)) {
664 ipCameraHandler.motionDetected(CHANNEL_MOTION_ALARM);
665 } else if ("false".equals(dataValue)) {
666 ipCameraHandler.noMotionDetected(CHANNEL_MOTION_ALARM);
669 case "AudioAnalytics/Audio/DetectedSound":
670 if ("true".equals(dataValue)) {
671 ipCameraHandler.audioDetected();
672 } else if ("false".equals(dataValue)) {
673 ipCameraHandler.noAudioDetected();
676 case "RuleEngine/FieldDetector/ObjectsInside":
677 if ("true".equals(dataValue)) {
678 ipCameraHandler.motionDetected(CHANNEL_FIELD_DETECTION_ALARM);
679 } else if ("false".equals(dataValue)) {
680 ipCameraHandler.noMotionDetected(CHANNEL_FIELD_DETECTION_ALARM);
683 case "RuleEngine/LineDetector/Crossed":
684 if ("ObjectId".equals(dataName)) {
685 ipCameraHandler.motionDetected(CHANNEL_LINE_CROSSING_ALARM);
687 ipCameraHandler.noMotionDetected(CHANNEL_LINE_CROSSING_ALARM);
690 case "RuleEngine/TamperDetector/Tamper":
691 if ("true".equals(dataValue)) {
692 ipCameraHandler.changeAlarmState(CHANNEL_TAMPER_ALARM, OnOffType.ON);
693 } else if ("false".equals(dataValue)) {
694 ipCameraHandler.changeAlarmState(CHANNEL_TAMPER_ALARM, OnOffType.OFF);
697 case "Device/HardwareFailure/StorageFailure":
698 if ("true".equals(dataValue)) {
699 ipCameraHandler.changeAlarmState(CHANNEL_STORAGE_ALARM, OnOffType.ON);
700 } else if ("false".equals(dataValue)) {
701 ipCameraHandler.changeAlarmState(CHANNEL_STORAGE_ALARM, OnOffType.OFF);
704 case "VideoSource/ImageTooDark/AnalyticsService":
705 case "VideoSource/ImageTooDark/ImagingService":
706 case "VideoSource/ImageTooDark/RecordingService":
707 if ("true".equals(dataValue)) {
708 ipCameraHandler.changeAlarmState(CHANNEL_TOO_DARK_ALARM, OnOffType.ON);
709 } else if ("false".equals(dataValue)) {
710 ipCameraHandler.changeAlarmState(CHANNEL_TOO_DARK_ALARM, OnOffType.OFF);
713 case "VideoSource/GlobalSceneChange/AnalyticsService":
714 case "VideoSource/GlobalSceneChange/ImagingService":
715 case "VideoSource/GlobalSceneChange/RecordingService":
716 if ("true".equals(dataValue)) {
717 ipCameraHandler.changeAlarmState(CHANNEL_SCENE_CHANGE_ALARM, OnOffType.ON);
718 } else if ("false".equals(dataValue)) {
719 ipCameraHandler.changeAlarmState(CHANNEL_SCENE_CHANGE_ALARM, OnOffType.OFF);
722 case "VideoSource/ImageTooBright/AnalyticsService":
723 case "VideoSource/ImageTooBright/ImagingService":
724 case "VideoSource/ImageTooBright/RecordingService":
725 if ("true".equals(dataValue)) {
726 ipCameraHandler.changeAlarmState(CHANNEL_TOO_BRIGHT_ALARM, OnOffType.ON);
727 } else if ("false".equals(dataValue)) {
728 ipCameraHandler.changeAlarmState(CHANNEL_TOO_BRIGHT_ALARM, OnOffType.OFF);
731 case "VideoSource/ImageTooBlurry/AnalyticsService":
732 case "VideoSource/ImageTooBlurry/ImagingService":
733 case "VideoSource/ImageTooBlurry/RecordingService":
734 if ("true".equals(dataValue)) {
735 ipCameraHandler.changeAlarmState(CHANNEL_TOO_BLURRY_ALARM, OnOffType.ON);
736 } else if ("false".equals(dataValue)) {
737 ipCameraHandler.changeAlarmState(CHANNEL_TOO_BLURRY_ALARM, OnOffType.OFF);
740 case "RuleEngine/MyRuleDetector/Visitor":
741 if ("true".equals(dataValue)) {
742 ipCameraHandler.changeAlarmState(CHANNEL_DOORBELL, OnOffType.ON);
743 } else if ("false".equals(dataValue)) {
744 ipCameraHandler.changeAlarmState(CHANNEL_DOORBELL, OnOffType.OFF);
747 case "RuleEngine/MyRuleDetector/VehicleDetect":
748 if ("true".equals(dataValue)) {
749 ipCameraHandler.changeAlarmState(CHANNEL_CAR_ALARM, OnOffType.ON);
750 } else if ("false".equals(dataValue)) {
751 ipCameraHandler.changeAlarmState(CHANNEL_CAR_ALARM, OnOffType.OFF);
754 case "RuleEngine/MyRuleDetector/DogCatDetect":
755 if ("true".equals(dataValue)) {
756 ipCameraHandler.changeAlarmState(CHANNEL_ANIMAL_ALARM, OnOffType.ON);
757 } else if ("false".equals(dataValue)) {
758 ipCameraHandler.changeAlarmState(CHANNEL_ANIMAL_ALARM, OnOffType.OFF);
761 case "RuleEngine/MyRuleDetector/FaceDetect":
762 if ("true".equals(dataValue)) {
763 ipCameraHandler.changeAlarmState(CHANNEL_FACE_DETECTED, OnOffType.ON);
764 } else if ("false".equals(dataValue)) {
765 ipCameraHandler.changeAlarmState(CHANNEL_FACE_DETECTED, OnOffType.OFF);
768 case "RuleEngine/MyRuleDetector/PeopleDetect":
769 if ("true".equals(dataValue)) {
770 ipCameraHandler.changeAlarmState(CHANNEL_HUMAN_ALARM, OnOffType.ON);
771 } else if ("false".equals(dataValue)) {
772 ipCameraHandler.changeAlarmState(CHANNEL_HUMAN_ALARM, OnOffType.OFF);
776 logger.debug("Please report this camera has an un-implemented ONVIF event. Topic: {}", topic);
778 sendOnvifRequest(RequestType.Renew, subscriptionXAddr);
781 public boolean supportsPTZ() {
785 public void getStatus() {
787 sendPTZRequest(RequestType.GetStatus);
791 public Float getAbsolutePan() {
792 return currentPanPercentage;
795 public Float getAbsoluteTilt() {
796 return currentTiltPercentage;
799 public Float getAbsoluteZoom() {
800 return currentZoomPercentage;
803 public void setAbsolutePan(Float panValue) {// Value is 0-100% of cameras range
805 currentPanPercentage = panValue;
806 currentPanCamValue = ((((panRangeMin - panRangeMax) * -1) / 100) * panValue + panRangeMin);
810 public void setAbsoluteTilt(Float tiltValue) {// Value is 0-100% of cameras range
812 currentTiltPercentage = tiltValue;
813 currentTiltCamValue = ((((panRangeMin - panRangeMax) * -1) / 100) * tiltValue + tiltRangeMin);
817 public void setAbsoluteZoom(Float zoomValue) {// Value is 0-100% of cameras range
819 currentZoomPercentage = zoomValue;
820 currentZoomCamValue = ((((zoomMin - zoomMax) * -1) / 100) * zoomValue + zoomMin);
824 public void absoluteMove() { // Camera wont move until PTZ values are set, then call this.
826 sendPTZRequest(RequestType.AbsoluteMove);
830 public void setSelectedMediaProfile(int mediaProfileIndex) {
831 this.mediaProfileIndex = mediaProfileIndex;
834 List<String> listOfResults(String message, String heading, String key) {
835 List<String> results = new LinkedList<>();
837 for (int startLookingFromIndex = 0; startLookingFromIndex != -1;) {
838 startLookingFromIndex = message.indexOf(heading, startLookingFromIndex);
839 if (startLookingFromIndex >= 0) {
840 temp = Helper.fetchXML(message.substring(startLookingFromIndex), heading, key);
841 if (!temp.isEmpty()) {
842 logger.trace("String was found: {}", temp);
845 return results;// key string must not exist so stop looking.
847 startLookingFromIndex += temp.length();
853 void parsePresets(String message) {
854 List<StateOption> presets = new ArrayList<>();
855 int counter = 1;// Presets start at 1 not 0. HOME may be added to index 0.
856 presetTokens = listOfResults(message, "<tptz:Preset", "token=\"");
857 presetNames = listOfResults(message, "<tptz:Preset", "<tt:Name>");
858 if (presetTokens.size() != presetNames.size()) {
859 logger.warn("Camera did not report the same number of Tokens and Names for PTZ presets");
862 for (String value : presetNames) {
863 presets.add(new StateOption(Integer.toString(counter++), value));
865 ipCameraHandler.stateDescriptionProvider
866 .setStateOptions(new ChannelUID(ipCameraHandler.getThing().getUID(), CHANNEL_GOTO_PRESET), presets);
869 void parseProfiles(String message) {
870 mediaProfileTokens = listOfResults(message, "<trt:Profiles", "token=\"");
871 if (mediaProfileIndex >= mediaProfileTokens.size()) {
873 "You have set the media profile to {} when the camera reported {} profiles. Falling back to mainstream 0.",
874 mediaProfileIndex, mediaProfileTokens.size());
875 mediaProfileIndex = 0;
879 void processPTZLocation(String result) {
880 logger.debug("Processing new PTZ location now");
882 int beginIndex = result.indexOf("x=\"");
883 int endIndex = result.indexOf("\"", (beginIndex + 3));
884 if (beginIndex >= 0 && endIndex >= 0) {
885 currentPanCamValue = Float.parseFloat(result.substring(beginIndex + 3, endIndex));
886 currentPanPercentage = (((panRangeMin - currentPanCamValue) * -1) / ((panRangeMin - panRangeMax) * -1))
888 logger.debug("Pan is updating to: {} and the cam value is {}", Math.round(currentPanPercentage),
892 "Binding could not determin the cameras current PTZ location. Not all cameras respond to GetStatus requests.");
896 beginIndex = result.indexOf("y=\"");
897 endIndex = result.indexOf("\"", (beginIndex + 3));
898 if (beginIndex >= 0 && endIndex >= 0) {
899 currentTiltCamValue = Float.parseFloat(result.substring(beginIndex + 3, endIndex));
900 currentTiltPercentage = (((tiltRangeMin - currentTiltCamValue) * -1) / ((tiltRangeMin - tiltRangeMax) * -1))
902 logger.debug("Tilt is updating to: {} and the cam value is {}", Math.round(currentTiltPercentage),
903 currentTiltCamValue);
908 beginIndex = result.lastIndexOf("x=\"");
909 endIndex = result.indexOf("\"", (beginIndex + 3));
910 if (beginIndex >= 0 && endIndex >= 0) {
911 currentZoomCamValue = Float.parseFloat(result.substring(beginIndex + 3, endIndex));
912 currentZoomPercentage = (((zoomMin - currentZoomCamValue) * -1) / ((zoomMin - zoomMax) * -1)) * 100;
913 logger.debug("Zoom is updating to: {} and the cam value is {}", Math.round(currentZoomPercentage),
914 currentZoomCamValue);
920 public void sendPTZRequest(RequestType requestType) {
922 logger.debug("ONVIF was not connected when a PTZ request was made, connecting now");
923 connect(usingEvents);
925 sendOnvifRequest(requestType, ptzXAddr);
928 public void sendEventRequest(RequestType requestType) {
929 sendOnvifRequest(requestType, eventXAddr);
932 public void connect(boolean useEvents) {
936 logger.debug("Connecting {} to ONVIF", ipAddress);
937 threadPool = Executors.newScheduledThreadPool(2);
938 sendOnvifRequest(RequestType.GetSystemDateAndTime, deviceXAddr);
939 usingEvents = useEvents;
940 sendOnvifRequest(RequestType.GetCapabilities, deviceXAddr);
947 public boolean isConnectError() {
951 public boolean isRefusedError() {
955 public boolean isConnected() {
964 public void setIsConnected(boolean isConnected) {
967 this.isConnected = isConnected;
968 this.connectError = false;
969 this.refusedError = false;
975 private void cleanup() {
976 if (!isConnected && !mainEventLoopGroup.isShuttingDown()) {
978 mainEventLoopGroup.shutdownGracefully();
979 mainEventLoopGroup.awaitTermination(3, TimeUnit.SECONDS);
980 } catch (InterruptedException e) {
981 logger.warn("ONVIF was not cleanly shutdown, due to being interrupted");
983 logger.debug("Eventloop is shutdown: {}", mainEventLoopGroup.isShutdown());
985 threadPool.shutdown();
990 public void disconnect() {
991 connecting.lock();// Lock out multiple disconnect()/connect() attempts as we try to send Unsubscribe.
993 if (bootstrap != null) {
994 if (isConnected && usingEvents && !mainEventLoopGroup.isShuttingDown()) {
995 // Only makes sense to send if connected
996 // Some cameras may continue to send events even when they can't reach a server.
997 sendOnvifRequest(RequestType.Unsubscribe, subscriptionXAddr);
999 // give time for the Unsubscribe request to be sent, shutdownGracefully will try to send it first.
1000 threadPool.schedule(this::cleanup, 50, TimeUnit.MILLISECONDS);
1005 isConnected = false;// isConnected is not thread safe, connecting.lock() used as fix.
1007 connecting.unlock();