2 * Copyright (c) 2010-2020 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
14 package org.openhab.binding.ipcamera.internal.onvif;
16 import java.io.BufferedReader;
17 import java.io.IOException;
18 import java.io.InputStreamReader;
19 import java.math.BigDecimal;
20 import java.net.HttpURLConnection;
21 import java.net.InetAddress;
22 import java.net.InetSocketAddress;
23 import java.net.MalformedURLException;
24 import java.net.NetworkInterface;
25 import java.net.SocketException;
27 import java.net.UnknownHostException;
28 import java.nio.charset.StandardCharsets;
29 import java.util.ArrayList;
30 import java.util.Enumeration;
31 import java.util.List;
32 import java.util.UUID;
33 import java.util.concurrent.TimeUnit;
35 import org.eclipse.jdt.annotation.NonNullByDefault;
36 import org.eclipse.jdt.annotation.Nullable;
37 import org.openhab.binding.ipcamera.internal.Helper;
38 import org.openhab.binding.ipcamera.internal.IpCameraDiscoveryService;
39 import org.slf4j.Logger;
40 import org.slf4j.LoggerFactory;
42 import io.netty.bootstrap.Bootstrap;
43 import io.netty.buffer.ByteBuf;
44 import io.netty.buffer.Unpooled;
45 import io.netty.channel.ChannelFactory;
46 import io.netty.channel.ChannelHandlerContext;
47 import io.netty.channel.ChannelOption;
48 import io.netty.channel.SimpleChannelInboundHandler;
49 import io.netty.channel.group.ChannelGroup;
50 import io.netty.channel.group.DefaultChannelGroup;
51 import io.netty.channel.nio.NioEventLoopGroup;
52 import io.netty.channel.socket.DatagramChannel;
53 import io.netty.channel.socket.DatagramPacket;
54 import io.netty.channel.socket.InternetProtocolFamily;
55 import io.netty.channel.socket.nio.NioDatagramChannel;
56 import io.netty.util.CharsetUtil;
57 import io.netty.util.concurrent.GlobalEventExecutor;
60 * The {@link OnvifDiscovery} is responsible for finding cameras that are ONVIF using UDP multicast.
62 * @author Matthew Skinner - Initial contribution
66 public class OnvifDiscovery {
67 private IpCameraDiscoveryService ipCameraDiscoveryService;
68 private final Logger logger = LoggerFactory.getLogger(OnvifDiscovery.class);
69 public ArrayList<DatagramPacket> listOfReplys = new ArrayList<DatagramPacket>(10);
71 public OnvifDiscovery(IpCameraDiscoveryService ipCameraDiscoveryService) {
72 this.ipCameraDiscoveryService = ipCameraDiscoveryService;
75 public @Nullable List<NetworkInterface> getLocalNICs() {
76 List<NetworkInterface> results = new ArrayList<>(2);
78 for (Enumeration<NetworkInterface> enumNetworks = NetworkInterface.getNetworkInterfaces(); enumNetworks
79 .hasMoreElements();) {
80 NetworkInterface networkInterface = enumNetworks.nextElement();
81 for (Enumeration<InetAddress> enumIpAddr = networkInterface.getInetAddresses(); enumIpAddr
82 .hasMoreElements();) {
83 InetAddress inetAddress = enumIpAddr.nextElement();
84 if (!inetAddress.isLoopbackAddress() && inetAddress.getHostAddress().toString().length() < 18
85 && inetAddress.isSiteLocalAddress()) {
86 results.add(networkInterface);
90 } catch (SocketException ex) {
95 void searchReply(String url, String xml) {
96 String ipAddress = "";
98 BigDecimal onvifPort = new BigDecimal(80);
100 logger.info("Camera found at xAddr:{}", url);
101 int endIndex = temp.indexOf(" ");// Some xAddr have two urls with a space in between.
103 temp = temp.substring(0, endIndex);// Use only the first url from now on.
106 int beginIndex = temp.indexOf(":") + 3;// add 3 to ignore the :// after http.
107 int secondIndex = temp.indexOf(":", beginIndex); // find second :
108 endIndex = temp.indexOf("/", beginIndex);
109 if (secondIndex > beginIndex && endIndex > secondIndex) {// http://192.168.0.1:8080/onvif/device_service
110 ipAddress = temp.substring(beginIndex, secondIndex);
111 onvifPort = new BigDecimal(temp.substring(secondIndex + 1, endIndex));
112 } else {// // http://192.168.0.1/onvif/device_service
113 ipAddress = temp.substring(beginIndex, endIndex);
115 String brand = checkForBrand(xml);
116 if (brand.equals("onvif")) {
118 brand = getBrandFromLoginPage(ipAddress);
119 } catch (IOException e) {
123 ipCameraDiscoveryService.newCameraFound(brand, ipAddress, onvifPort.intValue());
126 void processCameraReplys() {
127 for (DatagramPacket packet : listOfReplys) {
128 logger.trace("Device replied to discovery with:{}", packet.toString());
129 String xml = packet.content().toString(CharsetUtil.UTF_8);
130 String xAddr = Helper.fetchXML(xml, "", "<d:XAddrs>");
131 if (!xAddr.equals("")) {
132 searchReply(xAddr, xml);
133 } else if (xml.contains("onvif")) {
134 logger.info("Possible ONVIF camera found at:{}", packet.sender().getHostString());
135 ipCameraDiscoveryService.newCameraFound("onvif", packet.sender().getHostString(), 80);
140 String checkForBrand(String response) {
141 if (response.toLowerCase().contains("amcrest")) {
143 } else if (response.toLowerCase().contains("dahua")) {
145 } else if (response.toLowerCase().contains("foscam")) {
147 } else if (response.toLowerCase().contains("hikvision")) {
149 } else if (response.toLowerCase().contains("instar")) {
151 } else if (response.toLowerCase().contains("doorbird")) {
153 } else if (response.toLowerCase().contains("ipc-")) {
155 } else if (response.toLowerCase().contains("dh-sd")) {
161 public String getBrandFromLoginPage(String hostname) throws IOException {
162 URL url = new URL("http://" + hostname);
163 String brand = "onvif";
164 HttpURLConnection connection = (HttpURLConnection) url.openConnection();
165 connection.setConnectTimeout(1000);
166 connection.setReadTimeout(2000);
167 connection.setInstanceFollowRedirects(true);
168 connection.setRequestMethod("GET");
170 connection.connect();
171 BufferedReader reply = new BufferedReader(new InputStreamReader(connection.getInputStream()));
172 String response = "";
174 while ((temp = reply.readLine()) != null) {
178 logger.trace("Cameras Login page is:{}", response);
179 brand = checkForBrand(response);
180 } catch (MalformedURLException e) {
182 connection.disconnect();
187 private DatagramPacket wsDiscovery() throws UnknownHostException {
188 String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><e:Envelope xmlns:e=\"http://www.w3.org/2003/05/soap-envelope\" xmlns:w=\"http://schemas.xmlsoap.org/ws/2004/08/addressing\" xmlns:d=\"http://schemas.xmlsoap.org/ws/2005/04/discovery\" xmlns:dn=\"http://www.onvif.org/ver10/network/wsdl\"><e:Header><w:MessageID>uuid:"
190 + "</w:MessageID><w:To e:mustUnderstand=\"true\">urn:schemas-xmlsoap-org:ws:2005:04:discovery</w:To><w:Action a:mustUnderstand=\"true\">http://schemas.xmlsoap.org/ws/2005/04/discovery/Probe</w:Action></e:Header><e:Body><d:Probe><d:Types xmlns:d=\"http://schemas.xmlsoap.org/ws/2005/04/discovery\" xmlns:dp0=\"http://www.onvif.org/ver10/network/wsdl\">dp0:NetworkVideoTransmitter</d:Types></d:Probe></e:Body></e:Envelope>";
191 ByteBuf discoveryProbeMessage = Unpooled.copiedBuffer(xml, 0, xml.length(), StandardCharsets.UTF_8);
192 return new DatagramPacket(discoveryProbeMessage,
193 new InetSocketAddress(InetAddress.getByName("239.255.255.250"), 3702), new InetSocketAddress(0));
196 public void discoverCameras() throws UnknownHostException, InterruptedException {
197 List<NetworkInterface> nics = getLocalNICs();
198 if (nics == null || nics.isEmpty()) {
201 NetworkInterface networkInterface = nics.get(0);
202 Bootstrap bootstrap = new Bootstrap().group(new NioEventLoopGroup())
203 .channelFactory(new ChannelFactory<NioDatagramChannel>() {
205 public NioDatagramChannel newChannel() {
206 return new NioDatagramChannel(InternetProtocolFamily.IPv4);
208 }).handler(new SimpleChannelInboundHandler<DatagramPacket>() {
210 protected void channelRead0(@Nullable ChannelHandlerContext ctx, DatagramPacket msg)
213 listOfReplys.add(msg);
215 }).option(ChannelOption.SO_BROADCAST, true).option(ChannelOption.SO_REUSEADDR, true)
216 .option(ChannelOption.IP_MULTICAST_LOOP_DISABLED, false).option(ChannelOption.SO_RCVBUF, 2048)
217 .option(ChannelOption.IP_MULTICAST_TTL, 255).option(ChannelOption.IP_MULTICAST_IF, networkInterface);
218 ChannelGroup openChannels = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
219 for (NetworkInterface nic : nics) {
220 DatagramChannel datagramChannel = (DatagramChannel) bootstrap.option(ChannelOption.IP_MULTICAST_IF, nic)
221 .bind(new InetSocketAddress(0)).sync().channel();
223 .joinGroup(new InetSocketAddress(InetAddress.getByName("239.255.255.250"), 3702), networkInterface)
225 openChannels.add(datagramChannel);
227 if (!openChannels.isEmpty()) {
228 openChannels.writeAndFlush(wsDiscovery());
229 TimeUnit.SECONDS.sleep(6);
230 openChannels.close();
231 processCameraReplys();
232 bootstrap.config().group().shutdownGracefully();