]> git.basschouten.com Git - openhab-addons.git/blob
dc49bf3bd5e98fde7fc95d17b13ab80478fa74d3
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2023 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 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;
25 import java.net.URL;
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;
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.IpCameraDiscoveryService;
38 import org.openhab.core.net.NetworkAddressService;
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 @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);
72
73     public OnvifDiscovery(NetworkAddressService networkAddressService,
74             IpCameraDiscoveryService ipCameraDiscoveryService) {
75         this.ipCameraDiscoveryService = ipCameraDiscoveryService;
76         this.networkAddressService = networkAddressService;
77     }
78
79     public @Nullable List<NetworkInterface> getLocalNICs() {
80         String primaryHostAddress = networkAddressService.getPrimaryIpv4HostAddress();
81         List<NetworkInterface> results = new ArrayList<>(2);
82         try {
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().toString().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);
94                         } else {
95                             logger.debug("Skipping network {} as it was not selected as openHAB's 'Primary Address'",
96                                     inetAddress.getHostAddress());
97                         }
98                     } else {
99                         logger.debug("Skipping network {} as it was not site local", inetAddress.getHostAddress());
100                     }
101                 }
102             }
103         } catch (SocketException ex) {
104         }
105         return results;
106     }
107
108     void searchReply(String url, String xml) {
109         String ipAddress = "";
110         String temp = url;
111         BigDecimal onvifPort = new BigDecimal(80);
112
113         logger.info("Camera found at xAddr:{}", url);
114         int endIndex = temp.indexOf(" ");// Some xAddr have two urls with a space in between.
115         if (endIndex > 0) {
116             temp = temp.substring(0, endIndex);// Use only the first url from now on.
117         }
118
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);
127         }
128         String brand = checkForBrand(xml);
129         if ("onvif".equals(brand)) {
130             try {
131                 brand = getBrandFromLoginPage(ipAddress);
132             } catch (IOException e) {
133                 brand = "onvif";
134             }
135         }
136         ipCameraDiscoveryService.newCameraFound(brand, ipAddress, onvifPort.intValue());
137     }
138
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")) {
147                 String brand;
148                 try {
149                     brand = getBrandFromLoginPage(packet.sender().getHostString());
150                 } catch (IOException e) {
151                     brand = "onvif";
152                 }
153                 logger.info("Possible {} camera found at:{}", brand, packet.sender().getHostString());
154                 if ("reolink".equals(brand)) {
155                     ipCameraDiscoveryService.newCameraFound(brand, packet.sender().getHostString(), 8000);
156                 } else {
157                     ipCameraDiscoveryService.newCameraFound(brand, packet.sender().getHostString(), 80);
158                 }
159             }
160         }
161     }
162
163     String checkForBrand(String response) {
164         if (response.toLowerCase().contains("amcrest")) {
165             return "dahua";
166         } else if (response.toLowerCase().contains("dahua")) {
167             return "dahua";
168         } else if (response.toLowerCase().contains("doorbird")) {
169             return "doorbird";
170         } else if (response.toLowerCase().contains("foscam")) {
171             return "foscam";
172         } else if (response.toLowerCase().contains("hikvision")) {
173             return "hikvision";
174         } else if (response.toLowerCase().contains("instar")) {
175             return "instar";
176         } else if (response.toLowerCase().contains("reolink")) {
177             return "reolink";
178         } else if (response.toLowerCase().contains("ipc-")) {
179             return "dahua";
180         } else if (response.toLowerCase().contains("dh-sd")) {
181             return "dahua";
182         }
183         return "onvif";
184     }
185
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");
194         try {
195             connection.connect();
196             BufferedReader reply = new BufferedReader(new InputStreamReader(connection.getInputStream()));
197             String response = "";
198             String temp;
199             while ((temp = reply.readLine()) != null) {
200                 response += temp;
201             }
202             reply.close();
203             logger.trace("Cameras Login page is:{}", response);
204             brand = checkForBrand(response);
205         } catch (MalformedURLException e) {
206         } finally {
207             connection.disconnect();
208         }
209         return brand;
210     }
211
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:"
214                 + UUID.randomUUID()
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));
219     }
220
221     public void discoverCameras() throws UnknownHostException, InterruptedException {
222         List<NetworkInterface> nics = getLocalNICs();
223         if (nics == null || nics.isEmpty()) {
224             logger.warn(
225                     "No 'Primary Address' selected to use for camera discovery. Check openHAB's Network Settings page to select a valid Primary Address.");
226             return;
227         }
228         NetworkInterface networkInterface = nics.get(0);
229         Bootstrap bootstrap = new Bootstrap().group(new NioEventLoopGroup())
230                 .channelFactory(new ChannelFactory<NioDatagramChannel>() {
231                     @Override
232                     public NioDatagramChannel newChannel() {
233                         return new NioDatagramChannel(InternetProtocolFamily.IPv4);
234                     }
235                 }).handler(new SimpleChannelInboundHandler<DatagramPacket>() {
236                     @Override
237                     protected void channelRead0(@Nullable ChannelHandlerContext ctx, DatagramPacket msg)
238                             throws Exception {
239                         msg.retain(1);
240                         listOfReplys.add(msg);
241                     }
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();
249             datagramChannel
250                     .joinGroup(new InetSocketAddress(InetAddress.getByName("239.255.255.250"), 3702), networkInterface)
251                     .sync();
252             openChannels.add(datagramChannel);
253         }
254         if (!openChannels.isEmpty()) {
255             openChannels.writeAndFlush(wsDiscovery());
256             TimeUnit.SECONDS.sleep(6);
257             openChannels.close();
258             processCameraReplys();
259             bootstrap.config().group().shutdownGracefully();
260         }
261     }
262 }