]> git.basschouten.com Git - openhab-addons.git/blob
1cfc49f4a96b49c7b722ca15288808104e89a4de
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2021 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.shelly.internal.coap;
14
15 import static org.openhab.binding.shelly.internal.coap.ShellyCoapJSonDTO.COIOT_PORT;
16
17 import java.net.InetAddress;
18 import java.net.InetSocketAddress;
19 import java.net.UnknownHostException;
20 import java.util.Set;
21
22 import org.eclipse.californium.core.CoapResource;
23 import org.eclipse.californium.core.CoapServer;
24 import org.eclipse.californium.core.coap.CoAP;
25 import org.eclipse.californium.core.coap.CoAP.Code;
26 import org.eclipse.californium.core.coap.CoAP.ResponseCode;
27 import org.eclipse.californium.core.coap.Request;
28 import org.eclipse.californium.core.coap.Response;
29 import org.eclipse.californium.core.network.CoapEndpoint;
30 import org.eclipse.californium.core.network.Exchange;
31 import org.eclipse.californium.core.network.config.NetworkConfig;
32 import org.eclipse.californium.elements.UdpMulticastConnector;
33 import org.eclipse.jdt.annotation.NonNullByDefault;
34 import org.eclipse.jdt.annotation.Nullable;
35 import org.eclipse.jetty.util.ConcurrentHashSet;
36 import org.slf4j.Logger;
37 import org.slf4j.LoggerFactory;
38
39 /**
40  * The {@link ShellyCoapServer} implements the UDP listener and status event processor (for /cit/s messages)
41  *
42  * @author Markus Michels - Initial contribution
43  */
44 @NonNullByDefault
45 public class ShellyCoapServer {
46     private final Logger logger = LoggerFactory.getLogger(ShellyCoapServer.class);
47
48     boolean started = false;
49     private CoapEndpoint statusEndpoint = new CoapEndpoint.Builder().build();
50     private @Nullable UdpMulticastConnector statusConnector;
51     private final CoapServer server = new CoapServer(NetworkConfig.getStandard(), COIOT_PORT);;
52     private final Set<ShellyCoapListener> coapListeners = new ConcurrentHashSet<>();
53
54     protected class ShellyStatusListener extends CoapResource {
55         private ShellyCoapServer listener;
56
57         public ShellyStatusListener(String uri, ShellyCoapServer listener) {
58             super(uri, true);
59             getAttributes().setTitle("ShellyCoapListener");
60             this.listener = listener;
61         }
62
63         @Override
64         public void handleRequest(@Nullable final Exchange exchange) {
65             if (exchange != null) {
66                 Request request = exchange.getRequest();
67                 Code code = exchange.getRequest().getCode();
68                 switch (code) {
69                     case CUSTOM_30:
70                         listener.processResponse(createResponse(request));
71                         break;
72                     default:
73                         super.handleRequest(exchange);
74                 }
75             }
76         }
77     }
78
79     public synchronized void start(String localIp, ShellyCoapListener listener) throws UnknownHostException {
80         if (!started) {
81             logger.debug("Initializing CoIoT listener (local IP={}:{})", localIp, COIOT_PORT);
82             NetworkConfig nc = NetworkConfig.getStandard();
83             InetAddress localAddr = InetAddress.getByName(localIp);
84             InetSocketAddress localPort = new InetSocketAddress(COIOT_PORT);
85
86             // Join the multicast group on the selected network interface
87             statusConnector = new UdpMulticastConnector(localAddr, localPort, CoAP.MULTICAST_IPV4); // bind UDP listener
88             statusEndpoint = new CoapEndpoint.Builder().setNetworkConfig(nc).setConnector(statusConnector).build();
89             server.addEndpoint(statusEndpoint);
90             CoapResource cit = new ShellyStatusListener("cit", this);
91             CoapResource s = new ShellyStatusListener("s", this);
92             cit.add(s);
93             server.add(cit);
94             started = true;
95         }
96
97         if (!coapListeners.contains(listener)) {
98             coapListeners.add(listener);
99         }
100     }
101
102     protected void processResponse(Response response) {
103         coapListeners.forEach(listener -> listener.processResponse(response));
104     }
105
106     public static Response createResponse(Request request) {
107         Response response = Response.createResponse(request, ResponseCode.CONTENT);
108         response.setType(request.getType());
109         response.setSourceContext(request.getSourceContext());
110         response.setMID(request.getMID());
111         response.setOptions(request.getOptions());
112         response.setPayload(request.getPayload());
113         return response;
114     }
115
116     @Nullable
117     public CoapEndpoint getEndpoint() {
118         return statusEndpoint;
119     }
120
121     /**
122      * Cancel pending requests and shutdown the client
123      */
124     public void stop(ShellyCoapListener listener) {
125         coapListeners.remove(listener);
126         if (coapListeners.isEmpty()) {
127             stop();
128         }
129     }
130
131     private synchronized void stop() {
132         if (started) {
133             // Last listener
134             server.stop();
135             statusEndpoint.stop();
136             coapListeners.clear();
137             started = false;
138             logger.debug("CoAP Listener stopped");
139         }
140     }
141
142     public void dispose() {
143         stop();
144     }
145 }