2 * Copyright (c) 2010-2023 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 java.io.BufferedReader;
16 import java.io.IOException;
17 import java.io.InputStreamReader;
18 import java.math.BigDecimal;
19 import java.net.HttpURLConnection;
20 import java.net.InetAddress;
21 import java.net.InetSocketAddress;
22 import java.net.MalformedURLException;
23 import java.net.NetworkInterface;
24 import java.net.SocketException;
26 import java.net.UnknownHostException;
27 import java.nio.charset.StandardCharsets;
28 import java.util.ArrayList;
29 import java.util.Enumeration;
30 import java.util.List;
31 import java.util.UUID;
32 import java.util.concurrent.TimeUnit;
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.IpCameraDiscoveryService;
38 import org.openhab.core.net.NetworkAddressService;
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 @io.netty.channel.ChannelHandler.Sharable
67 public class OnvifDiscovery {
68 private IpCameraDiscoveryService ipCameraDiscoveryService;
69 private final Logger logger = LoggerFactory.getLogger(OnvifDiscovery.class);
70 private final NetworkAddressService networkAddressService;
71 public ArrayList<DatagramPacket> listOfReplys = new ArrayList<DatagramPacket>(10);
73 public OnvifDiscovery(NetworkAddressService networkAddressService,
74 IpCameraDiscoveryService ipCameraDiscoveryService) {
75 this.ipCameraDiscoveryService = ipCameraDiscoveryService;
76 this.networkAddressService = networkAddressService;
79 public @Nullable List<NetworkInterface> getLocalNICs() {
80 String primaryHostAddress = networkAddressService.getPrimaryIpv4HostAddress();
81 List<NetworkInterface> results = new ArrayList<>(2);
83 for (Enumeration<NetworkInterface> enumNetworks = NetworkInterface.getNetworkInterfaces(); enumNetworks
84 .hasMoreElements();) {
85 NetworkInterface networkInterface = enumNetworks.nextElement();
86 for (Enumeration<InetAddress> enumIpAddr = networkInterface.getInetAddresses(); enumIpAddr
87 .hasMoreElements();) {
88 InetAddress inetAddress = enumIpAddr.nextElement();
89 if (!inetAddress.isLoopbackAddress() && inetAddress.getHostAddress().length() < 18
90 && inetAddress.isSiteLocalAddress()) {
91 if (inetAddress.getHostAddress().equals(primaryHostAddress)) {
92 results.add(networkInterface);
93 logger.debug("Scanning network {} for any ONVIF cameras", primaryHostAddress);
95 logger.debug("Skipping network {} as it was not selected as openHAB's 'Primary Address'",
96 inetAddress.getHostAddress());
99 logger.debug("Skipping network {} as it was not site local", inetAddress.getHostAddress());
103 } catch (SocketException ex) {
108 void searchReply(String url, String xml) {
109 String ipAddress = "";
111 BigDecimal onvifPort = new BigDecimal(80);
113 logger.info("Camera found at xAddr:{}", url);
114 int endIndex = temp.indexOf(" ");// Some xAddr have two urls with a space in between.
116 temp = temp.substring(0, endIndex);// Use only the first url from now on.
119 int beginIndex = temp.indexOf(":") + 3;// add 3 to ignore the :// after http.
120 int secondIndex = temp.indexOf(":", beginIndex); // find second :
121 endIndex = temp.indexOf("/", beginIndex);
122 if (secondIndex > beginIndex && endIndex > secondIndex) {// http://192.168.0.1:8080/onvif/device_service
123 ipAddress = temp.substring(beginIndex, secondIndex);
124 onvifPort = new BigDecimal(temp.substring(secondIndex + 1, endIndex));
125 } else {// // http://192.168.0.1/onvif/device_service
126 ipAddress = temp.substring(beginIndex, endIndex);
128 String brand = checkForBrand(xml);
129 if ("onvif".equals(brand)) {
131 brand = getBrandFromLoginPage(ipAddress);
132 } catch (IOException e) {
136 ipCameraDiscoveryService.newCameraFound(brand, ipAddress, onvifPort.intValue());
139 void processCameraReplys() {
140 for (DatagramPacket packet : listOfReplys) {
141 String xml = packet.content().toString(CharsetUtil.UTF_8);
142 logger.trace("Device replied to discovery with:{}", xml);
143 String xAddr = Helper.fetchXML(xml, "", "d:XAddrs>");// Foscam <wsdd:XAddrs> and all other brands <d:XAddrs>
144 if (!xAddr.isEmpty()) {
145 searchReply(xAddr, xml);
146 } else if (xml.contains("onvif")) {
149 brand = getBrandFromLoginPage(packet.sender().getHostString());
150 } catch (IOException e) {
153 logger.info("Possible {} camera found at:{}", brand, packet.sender().getHostString());
154 if ("reolink".equals(brand)) {
155 ipCameraDiscoveryService.newCameraFound(brand, packet.sender().getHostString(), 8000);
157 ipCameraDiscoveryService.newCameraFound(brand, packet.sender().getHostString(), 80);
163 String checkForBrand(String response) {
164 if (response.toLowerCase().contains("amcrest")) {
166 } else if (response.toLowerCase().contains("dahua")) {
168 } else if (response.toLowerCase().contains("doorbird")) {
170 } else if (response.toLowerCase().contains("foscam")) {
172 } else if (response.toLowerCase().contains("hikvision")) {
174 } else if (response.toLowerCase().contains("instar")) {
176 } else if (response.toLowerCase().contains("reolink")) {
178 } else if (response.toLowerCase().contains("ipc-")) {
180 } else if (response.toLowerCase().contains("dh-sd")) {
186 public String getBrandFromLoginPage(String hostname) throws IOException {
187 URL url = new URL("http://" + hostname);
188 String brand = "onvif";
189 HttpURLConnection connection = (HttpURLConnection) url.openConnection();
190 connection.setConnectTimeout(1000);
191 connection.setReadTimeout(2000);
192 connection.setInstanceFollowRedirects(true);
193 connection.setRequestMethod("GET");
195 connection.connect();
196 BufferedReader reply = new BufferedReader(new InputStreamReader(connection.getInputStream()));
197 String response = "";
199 while ((temp = reply.readLine()) != null) {
203 logger.trace("Cameras Login page is:{}", response);
204 brand = checkForBrand(response);
205 } catch (MalformedURLException e) {
207 connection.disconnect();
212 private DatagramPacket wsDiscovery() throws UnknownHostException {
213 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:"
215 + "</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>";
216 ByteBuf discoveryProbeMessage = Unpooled.copiedBuffer(xml, 0, xml.length(), StandardCharsets.UTF_8);
217 return new DatagramPacket(discoveryProbeMessage,
218 new InetSocketAddress(InetAddress.getByName("239.255.255.250"), 3702), new InetSocketAddress(0));
221 public void discoverCameras() throws UnknownHostException, InterruptedException {
222 List<NetworkInterface> nics = getLocalNICs();
223 if (nics == null || nics.isEmpty()) {
225 "No 'Primary Address' selected to use for camera discovery. Check openHAB's Network Settings page to select a valid Primary Address.");
228 NetworkInterface networkInterface = nics.get(0);
229 Bootstrap bootstrap = new Bootstrap().group(new NioEventLoopGroup())
230 .channelFactory(new ChannelFactory<NioDatagramChannel>() {
232 public NioDatagramChannel newChannel() {
233 return new NioDatagramChannel(InternetProtocolFamily.IPv4);
235 }).handler(new SimpleChannelInboundHandler<DatagramPacket>() {
237 protected void channelRead0(@Nullable ChannelHandlerContext ctx, DatagramPacket msg)
240 listOfReplys.add(msg);
242 }).option(ChannelOption.SO_BROADCAST, true).option(ChannelOption.SO_REUSEADDR, true)
243 .option(ChannelOption.IP_MULTICAST_LOOP_DISABLED, false).option(ChannelOption.SO_RCVBUF, 2048)
244 .option(ChannelOption.IP_MULTICAST_TTL, 255).option(ChannelOption.IP_MULTICAST_IF, networkInterface);
245 ChannelGroup openChannels = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
246 for (NetworkInterface nic : nics) {
247 DatagramChannel datagramChannel = (DatagramChannel) bootstrap.option(ChannelOption.IP_MULTICAST_IF, nic)
248 .bind(new InetSocketAddress(0)).sync().channel();
250 .joinGroup(new InetSocketAddress(InetAddress.getByName("239.255.255.250"), 3702), networkInterface)
252 openChannels.add(datagramChannel);
254 if (!openChannels.isEmpty()) {
255 openChannels.writeAndFlush(wsDiscovery());
256 TimeUnit.SECONDS.sleep(6);
257 openChannels.close();
258 processCameraReplys();
259 bootstrap.config().group().shutdownGracefully();