]> git.basschouten.com Git - openhab-addons.git/blob
0e8f5600bd62ffd0c01faf5db9cde1bdef966a6d
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2020 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
14 package org.openhab.binding.ipcamera.internal.onvif;
15
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;
26 import java.net.URL;
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;
34
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;
41
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;
58
59 /**
60  * The {@link OnvifDiscovery} is responsible for finding cameras that are ONVIF using UDP multicast.
61  *
62  * @author Matthew Skinner - Initial contribution
63  */
64
65 @NonNullByDefault
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);
70
71     public OnvifDiscovery(IpCameraDiscoveryService ipCameraDiscoveryService) {
72         this.ipCameraDiscoveryService = ipCameraDiscoveryService;
73     }
74
75     public @Nullable List<NetworkInterface> getLocalNICs() {
76         List<NetworkInterface> results = new ArrayList<>(2);
77         try {
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);
87                     }
88                 }
89             }
90         } catch (SocketException ex) {
91         }
92         return results;
93     }
94
95     void searchReply(String url, String xml) {
96         String ipAddress = "";
97         String temp = url;
98         BigDecimal onvifPort = new BigDecimal(80);
99
100         logger.info("Camera found at xAddr:{}", url);
101         int endIndex = temp.indexOf(" ");// Some xAddr have two urls with a space in between.
102         if (endIndex > 0) {
103             temp = temp.substring(0, endIndex);// Use only the first url from now on.
104         }
105
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);
114         }
115         String brand = checkForBrand(xml);
116         if (brand.equals("onvif")) {
117             try {
118                 brand = getBrandFromLoginPage(ipAddress);
119             } catch (IOException e) {
120                 brand = "onvif";
121             }
122         }
123         ipCameraDiscoveryService.newCameraFound(brand, ipAddress, onvifPort.intValue());
124     }
125
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);
136             }
137         }
138     }
139
140     String checkForBrand(String response) {
141         if (response.toLowerCase().contains("amcrest")) {
142             return "dahua";
143         } else if (response.toLowerCase().contains("dahua")) {
144             return "dahua";
145         } else if (response.toLowerCase().contains("foscam")) {
146             return "foscam";
147         } else if (response.toLowerCase().contains("hikvision")) {
148             return "hikvision";
149         } else if (response.toLowerCase().contains("instar")) {
150             return "instar";
151         } else if (response.toLowerCase().contains("doorbird")) {
152             return "doorbird";
153         } else if (response.toLowerCase().contains("ipc-")) {
154             return "dahua";
155         } else if (response.toLowerCase().contains("dh-sd")) {
156             return "dahua";
157         }
158         return "onvif";
159     }
160
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");
169         try {
170             connection.connect();
171             BufferedReader reply = new BufferedReader(new InputStreamReader(connection.getInputStream()));
172             String response = "";
173             String temp;
174             while ((temp = reply.readLine()) != null) {
175                 response += temp;
176             }
177             reply.close();
178             logger.trace("Cameras Login page is:{}", response);
179             brand = checkForBrand(response);
180         } catch (MalformedURLException e) {
181         } finally {
182             connection.disconnect();
183         }
184         return brand;
185     }
186
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:"
189                 + UUID.randomUUID()
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));
194     }
195
196     public void discoverCameras() throws UnknownHostException, InterruptedException {
197         List<NetworkInterface> nics = getLocalNICs();
198         if (nics == null || nics.isEmpty()) {
199             return;
200         }
201         NetworkInterface networkInterface = nics.get(0);
202         Bootstrap bootstrap = new Bootstrap().group(new NioEventLoopGroup())
203                 .channelFactory(new ChannelFactory<NioDatagramChannel>() {
204                     @Override
205                     public NioDatagramChannel newChannel() {
206                         return new NioDatagramChannel(InternetProtocolFamily.IPv4);
207                     }
208                 }).handler(new SimpleChannelInboundHandler<DatagramPacket>() {
209                     @Override
210                     protected void channelRead0(@Nullable ChannelHandlerContext ctx, DatagramPacket msg)
211                             throws Exception {
212                         msg.retain(1);
213                         listOfReplys.add(msg);
214                     }
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();
222             datagramChannel
223                     .joinGroup(new InetSocketAddress(InetAddress.getByName("239.255.255.250"), 3702), networkInterface)
224                     .sync();
225             openChannels.add(datagramChannel);
226         }
227         if (!openChannels.isEmpty()) {
228             openChannels.writeAndFlush(wsDiscovery());
229             TimeUnit.SECONDS.sleep(6);
230             openChannels.close();
231             processCameraReplys();
232             bootstrap.config().group().shutdownGracefully();
233         }
234     }
235 }