]> git.basschouten.com Git - openhab-addons.git/blob
23af1099db1b4926808c21bdf947309d4cb498a1
[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.shelly.internal.api1;
14
15 import static org.openhab.binding.shelly.internal.api1.Shelly1CoapJSonDTO.COIOT_PORT;
16
17 import java.net.InetAddress;
18 import java.net.SocketException;
19 import java.net.UnknownHostException;
20 import java.util.Set;
21 import java.util.concurrent.ConcurrentHashMap;
22
23 import org.eclipse.californium.core.CoapResource;
24 import org.eclipse.californium.core.CoapServer;
25 import org.eclipse.californium.core.coap.CoAP;
26 import org.eclipse.californium.core.coap.CoAP.Code;
27 import org.eclipse.californium.core.coap.CoAP.ResponseCode;
28 import org.eclipse.californium.core.coap.Request;
29 import org.eclipse.californium.core.coap.Response;
30 import org.eclipse.californium.core.network.CoapEndpoint;
31 import org.eclipse.californium.core.network.Exchange;
32 import org.eclipse.californium.core.network.config.NetworkConfig;
33 import org.eclipse.californium.elements.UdpMulticastConnector;
34 import org.eclipse.jdt.annotation.NonNullByDefault;
35 import org.eclipse.jdt.annotation.Nullable;
36 import org.slf4j.Logger;
37 import org.slf4j.LoggerFactory;
38
39 /**
40  * The {@link Shelly1CoapServer} 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 Shelly1CoapServer {
46     private final Logger logger = LoggerFactory.getLogger(Shelly1CoapServer.class);
47
48     boolean started = false;
49     private CoapEndpoint statusEndpoint = new CoapEndpoint.Builder().build();
50     private @Nullable UdpMulticastConnector statusConnector;
51     private CoapServer server = new CoapServer(NetworkConfig.getStandard(), COIOT_PORT);
52     private final Set<Shelly1CoapListener> coapListeners = ConcurrentHashMap.newKeySet();
53
54     protected class ShellyStatusListener extends CoapResource {
55         private Shelly1CoapServer listener;
56
57         public ShellyStatusListener(String uri, Shelly1CoapServer 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                     case PUT: // Shelly Motion beta: incorrect, but handle the format
71                         listener.processResponse(createResponse(request));
72                         break;
73                     default:
74                         super.handleRequest(exchange);
75                 }
76             }
77         }
78     }
79
80     public synchronized void start(String localIp, int port, Shelly1CoapListener listener)
81             throws UnknownHostException, SocketException {
82         if (!started) {
83             logger.debug("Initializing CoIoT listener (local IP={}:{})", localIp, port);
84             NetworkConfig nc = NetworkConfig.getStandard();
85             InetAddress localAddr = InetAddress.getByName(localIp);
86             // Join the multicast group on the selected network interface, add UDP listener
87             statusConnector = new UdpMulticastConnector.Builder().setLocalAddress(localAddr, port).setLocalPort(port)
88                     .setOutgoingMulticastInterface(localAddr).addMulticastGroup(CoAP.MULTICAST_IPV4).build();
89             statusEndpoint = new CoapEndpoint.Builder().setNetworkConfig(nc).setConnector(statusConnector).build();
90             server = new CoapServer(NetworkConfig.getStandard(), port);
91             server.addEndpoint(statusEndpoint);
92             CoapResource cit = new ShellyStatusListener("cit", this);
93             CoapResource s = new ShellyStatusListener("s", this);
94             cit.add(s);
95             server.add(cit);
96             started = true;
97         }
98
99         if (!coapListeners.contains(listener)) {
100             coapListeners.add(listener);
101         }
102     }
103
104     protected void processResponse(Response response) {
105         coapListeners.forEach(listener -> listener.processResponse(response));
106     }
107
108     public static Response createResponse(Request request) {
109         Response response = Response.createResponse(request, ResponseCode.CONTENT);
110         response.setType(request.getType());
111         response.setSourceContext(request.getSourceContext());
112         response.setMID(request.getMID());
113         response.setOptions(request.getOptions());
114         response.setPayload(request.getPayload());
115         return response;
116     }
117
118     @Nullable
119     public CoapEndpoint getEndpoint() {
120         return statusEndpoint;
121     }
122
123     /**
124      * Cancel pending requests and shutdown the client
125      */
126     public void stop(Shelly1CoapListener listener) {
127         coapListeners.remove(listener);
128         if (coapListeners.isEmpty()) {
129             stop();
130         }
131     }
132
133     private synchronized void stop() {
134         if (started) {
135             // Last listener
136             server.stop();
137             statusEndpoint.stop();
138             coapListeners.clear();
139             started = false;
140             logger.debug("CoAP Listener stopped");
141         }
142     }
143
144     public void dispose() {
145         stop();
146     }
147 }