]> git.basschouten.com Git - openhab-addons.git/blob
59e72b4f799ebdb4f7c3f1dcbddd6135aa932ba2
[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.unifi.internal.api;
14
15 import java.util.Collection;
16 import java.util.List;
17
18 import org.eclipse.jdt.annotation.NonNullByDefault;
19 import org.eclipse.jdt.annotation.Nullable;
20 import org.eclipse.jetty.client.HttpClient;
21 import org.eclipse.jetty.http.HttpMethod;
22 import org.openhab.binding.unifi.internal.api.cache.UniFiControllerCache;
23 import org.openhab.binding.unifi.internal.api.dto.UnfiPortOverrideJsonObject;
24 import org.openhab.binding.unifi.internal.api.dto.UniFiClient;
25 import org.openhab.binding.unifi.internal.api.dto.UniFiDevice;
26 import org.openhab.binding.unifi.internal.api.dto.UniFiSite;
27 import org.openhab.binding.unifi.internal.api.dto.UniFiSwitchPorts;
28 import org.openhab.binding.unifi.internal.api.dto.UniFiUnknownClient;
29 import org.openhab.binding.unifi.internal.api.dto.UniFiWiredClient;
30 import org.openhab.binding.unifi.internal.api.dto.UniFiWirelessClient;
31 import org.openhab.binding.unifi.internal.api.dto.UniFiWlan;
32 import org.openhab.binding.unifi.internal.api.util.UnfiPortOverrideJsonElementDeserializer;
33 import org.openhab.binding.unifi.internal.api.util.UniFiClientDeserializer;
34 import org.openhab.binding.unifi.internal.api.util.UniFiClientInstanceCreator;
35 import org.openhab.binding.unifi.internal.api.util.UniFiDeviceInstanceCreator;
36 import org.openhab.binding.unifi.internal.api.util.UniFiSiteInstanceCreator;
37 import org.openhab.binding.unifi.internal.api.util.UniFiWlanInstanceCreator;
38 import org.slf4j.Logger;
39 import org.slf4j.LoggerFactory;
40
41 import com.google.gson.FieldNamingPolicy;
42 import com.google.gson.Gson;
43 import com.google.gson.GsonBuilder;
44 import com.google.gson.JsonObject;
45
46 /**
47  * The {@link UniFiController} is the main communication point with an external instance of the Ubiquiti Networks
48  * Controller Software.
49  *
50  * @author Matthew Bowman - Initial contribution
51  * @author Patrik Wimnell - Blocking / Unblocking client support
52  * @author Jacob Laursen - Fix online/blocked channels (broken by UniFi Controller 5.12.35)
53  * @author Hilbrand Bouwkamp - Added POEPort support, moved generic cache related code to cache object
54  */
55 @NonNullByDefault
56 public class UniFiController {
57
58     private static final int INSIGHT_WITHIN_HOURS = 7 * 24; // scurb: Changed to 7 days.
59
60     private final Logger logger = LoggerFactory.getLogger(UniFiController.class);
61
62     private final HttpClient httpClient;
63     private final UniFiControllerCache cache = new UniFiControllerCache();
64
65     private final String host;
66     private final int port;
67     private final String username;
68     private final String password;
69     private final boolean unifios;
70     private final Gson gson;
71     private final Gson poeGson;
72
73     private String csrfToken;
74
75     public UniFiController(final HttpClient httpClient, final String host, final int port, final String username,
76             final String password, final boolean unifios) {
77         this.httpClient = httpClient;
78         this.host = host;
79         this.port = port;
80         this.username = username;
81         this.password = password;
82         this.unifios = unifios;
83         this.csrfToken = "";
84         final UniFiSiteInstanceCreator siteInstanceCreator = new UniFiSiteInstanceCreator(cache);
85         final UniFiWlanInstanceCreator wlanInstanceCreator = new UniFiWlanInstanceCreator(cache);
86         final UniFiDeviceInstanceCreator deviceInstanceCreator = new UniFiDeviceInstanceCreator(cache);
87         final UniFiClientInstanceCreator clientInstanceCreator = new UniFiClientInstanceCreator(cache);
88         this.gson = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
89                 .registerTypeAdapter(UniFiSite.class, siteInstanceCreator)
90                 .registerTypeAdapter(UniFiWlan.class, wlanInstanceCreator)
91                 .registerTypeAdapter(UniFiDevice.class, deviceInstanceCreator)
92                 .registerTypeAdapter(UniFiClient.class, new UniFiClientDeserializer())
93                 .registerTypeAdapter(UniFiUnknownClient.class, clientInstanceCreator)
94                 .registerTypeAdapter(UniFiWiredClient.class, clientInstanceCreator)
95                 .registerTypeAdapter(UniFiWirelessClient.class, clientInstanceCreator).create();
96         this.poeGson = new GsonBuilder()
97                 .registerTypeAdapter(UnfiPortOverrideJsonObject.class, new UnfiPortOverrideJsonElementDeserializer())
98                 .create();
99     }
100
101     // Public API
102
103     public void start() throws UniFiException {
104         if (unifios) {
105             obtainCsrfToken();
106         }
107
108         login();
109     }
110
111     public void stop() throws UniFiException {
112         logout();
113     }
114
115     public void obtainCsrfToken() throws UniFiException {
116         csrfToken = "";
117
118         final UniFiControllerRequest<Void> req = newRequest(Void.class, HttpMethod.GET, gson);
119         req.setPath("/");
120         executeRequest(req);
121     }
122
123     public void login() throws UniFiException {
124         final UniFiControllerRequest<Void> req = newRequest(Void.class, HttpMethod.POST, gson);
125         req.setPath(unifios ? "/api/auth/login" : "/api/login");
126         req.setBodyParameter("username", username);
127         req.setBodyParameter("password", password);
128         // scurb: Changed strict = false to make blocking feature work
129         req.setBodyParameter("strict", false);
130         req.setBodyParameter("remember", false);
131         executeRequest(req, true);
132     }
133
134     public void logout() throws UniFiException {
135         csrfToken = "";
136         final UniFiControllerRequest<Void> req = newRequest(Void.class, HttpMethod.POST, gson);
137         req.setPath(unifios ? "/api/auth/logout" : "/logout");
138         executeRequest(req);
139     }
140
141     public void refresh() throws UniFiException {
142         synchronized (this) {
143             cache.clear();
144             final Collection<UniFiSite> sites = refreshSites();
145             refreshWlans(sites);
146             refreshDevices(sites);
147             refreshClients(sites);
148             refreshInsights(sites);
149         }
150     }
151
152     public UniFiControllerCache getCache() {
153         return cache;
154     }
155
156     public @Nullable UniFiSwitchPorts getSwitchPorts(@Nullable final String deviceId) {
157         return cache.getSwitchPorts(deviceId);
158     }
159
160     public void block(final UniFiClient client, final boolean blocked) throws UniFiException {
161         final UniFiControllerRequest<Void> req = newRequest(Void.class, HttpMethod.POST, gson);
162         req.setAPIPath(String.format("/api/s/%s/cmd/stamgr", client.getSite().getName()));
163         req.setBodyParameter("cmd", blocked ? "block-sta" : "unblock-sta");
164         req.setBodyParameter("mac", client.getMac());
165         executeRequest(req);
166         refresh();
167     }
168
169     public void reconnect(final UniFiClient client) throws UniFiException {
170         final UniFiControllerRequest<Void> req = newRequest(Void.class, HttpMethod.POST, gson);
171         req.setAPIPath(String.format("/api/s/%s/cmd/stamgr", client.getSite().getName()));
172         req.setBodyParameter("cmd", "kick-sta");
173         req.setBodyParameter("mac", client.getMac());
174         executeRequest(req);
175         refresh();
176     }
177
178     public boolean poeMode(final UniFiDevice device, final List<JsonObject> data) throws UniFiException {
179         // Safety check to make sure no empty data is send to avoid corrupting override data on the device.
180         if (data.isEmpty() || data.stream().anyMatch(p -> p.entrySet().isEmpty())) {
181             logger.info("Not overriding port for '{}', because port data contains empty json: {}", device.getName(),
182                     poeGson.toJson(data));
183             return false;
184         } else {
185             final UniFiControllerRequest<Void> req = newRequest(Void.class, HttpMethod.PUT, poeGson);
186             req.setAPIPath(String.format("/api/s/%s/rest/device/%s", device.getSite().getName(), device.getId()));
187             req.setBodyParameter("port_overrides", data);
188             executeRequest(req);
189             return true;
190         }
191     }
192
193     public void poePowerCycle(final UniFiDevice device, final Integer portIdx) throws UniFiException {
194         final UniFiControllerRequest<Void> req = newRequest(Void.class, HttpMethod.POST, gson);
195         req.setAPIPath(String.format("/api/s/%s/cmd/devmgr", device.getSite().getName()));
196         req.setBodyParameter("cmd", "power-cycle");
197         req.setBodyParameter("mac", device.getMac());
198         req.setBodyParameter("port_idx", portIdx);
199         executeRequest(req);
200         refresh();
201     }
202
203     public void enableWifi(final UniFiWlan wlan, final boolean enable) throws UniFiException {
204         final UniFiControllerRequest<Void> req = newRequest(Void.class, HttpMethod.PUT, poeGson);
205         req.setAPIPath(String.format("/api/s/%s/rest/wlanconf/%s", wlan.getSite().getName(), wlan.getId()));
206         req.setBodyParameter("_id", wlan.getId());
207         req.setBodyParameter("enabled", enable ? "true" : "false");
208         executeRequest(req);
209         refresh();
210     }
211
212     // Internal API
213
214     private <T> UniFiControllerRequest<T> newRequest(final Class<T> responseType, final HttpMethod method,
215             final Gson gson) {
216         return new UniFiControllerRequest<>(responseType, gson, httpClient, method, host, port, csrfToken, unifios);
217     }
218
219     private <T> @Nullable T executeRequest(final UniFiControllerRequest<T> request) throws UniFiException {
220         return executeRequest(request, false);
221     }
222
223     private <T> @Nullable T executeRequest(final UniFiControllerRequest<T> request, final boolean fromLogin)
224             throws UniFiException {
225         T result;
226         try {
227             result = (T) request.execute();
228             csrfToken = request.getCsrfToken();
229         } catch (final UniFiExpiredSessionException e) {
230             if (fromLogin) {
231                 // if this exception is thrown from a login attempt something is wrong, because the login should init
232                 // the session.
233                 throw new UniFiCommunicationException(e);
234             } else {
235                 login();
236                 result = (T) executeRequest(request);
237             }
238         } catch (final UniFiNotAuthorizedException e) {
239             logger.warn("Not Authorized! Please make sure your controller credentials have administrator rights");
240             result = (T) null;
241         }
242         return result;
243     }
244
245     private List<UniFiSite> refreshSites() throws UniFiException {
246         final UniFiControllerRequest<UniFiSite[]> req = newRequest(UniFiSite[].class, HttpMethod.GET, gson);
247         req.setAPIPath("/api/self/sites");
248         return cache.setSites(executeRequest(req));
249     }
250
251     private void refreshWlans(final Collection<UniFiSite> sites) throws UniFiException {
252         for (final UniFiSite site : sites) {
253             cache.putWlans(getWlans(site));
254         }
255     }
256
257     private UniFiWlan @Nullable [] getWlans(final UniFiSite site) throws UniFiException {
258         final UniFiControllerRequest<UniFiWlan[]> req = newRequest(UniFiWlan[].class, HttpMethod.GET, gson);
259         req.setAPIPath(String.format("/api/s/%s/rest/wlanconf", site.getName()));
260         return executeRequest(req);
261     }
262
263     private void refreshDevices(final Collection<UniFiSite> sites) throws UniFiException {
264         for (final UniFiSite site : sites) {
265             cache.putDevices(getDevices(site));
266         }
267     }
268
269     private UniFiDevice @Nullable [] getDevices(final UniFiSite site) throws UniFiException {
270         final UniFiControllerRequest<UniFiDevice[]> req = newRequest(UniFiDevice[].class, HttpMethod.GET, gson);
271         req.setAPIPath(String.format("/api/s/%s/stat/device", site.getName()));
272         return executeRequest(req);
273     }
274
275     private void refreshClients(final Collection<UniFiSite> sites) throws UniFiException {
276         for (final UniFiSite site : sites) {
277             cache.putClients(getClients(site));
278         }
279     }
280
281     private UniFiClient @Nullable [] getClients(final UniFiSite site) throws UniFiException {
282         final UniFiControllerRequest<UniFiClient[]> req = newRequest(UniFiClient[].class, HttpMethod.GET, gson);
283         req.setAPIPath(String.format("/api/s/%s/stat/sta", site.getName()));
284         return executeRequest(req);
285     }
286
287     private void refreshInsights(final Collection<UniFiSite> sites) throws UniFiException {
288         for (final UniFiSite site : sites) {
289             cache.putInsights(getInsights(site));
290         }
291     }
292
293     private UniFiClient @Nullable [] getInsights(final UniFiSite site) throws UniFiException {
294         final UniFiControllerRequest<UniFiClient[]> req = newRequest(UniFiClient[].class, HttpMethod.GET, gson);
295         req.setAPIPath(String.format("/api/s/%s/stat/alluser", site.getName()));
296         req.setQueryParameter("within", INSIGHT_WITHIN_HOURS);
297         return executeRequest(req);
298     }
299 }