2 * Copyright (c) 2010-2023 Contributors to the openHAB project
4 * See the NOTICE file(s) distributed with this work for additional
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
11 * SPDX-License-Identifier: EPL-2.0
13 package org.openhab.binding.unifi.internal.api;
15 import java.util.Collection;
16 import java.util.List;
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;
41 import com.google.gson.FieldNamingPolicy;
42 import com.google.gson.Gson;
43 import com.google.gson.GsonBuilder;
44 import com.google.gson.JsonObject;
47 * The {@link UniFiController} is the main communication point with an external instance of the Ubiquiti Networks
48 * Controller Software.
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
56 public class UniFiController {
58 private static final int INSIGHT_WITHIN_HOURS = 7 * 24; // scurb: Changed to 7 days.
60 private final Logger logger = LoggerFactory.getLogger(UniFiController.class);
62 private final HttpClient httpClient;
63 private final UniFiControllerCache cache = new UniFiControllerCache();
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;
73 private String csrfToken;
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;
80 this.username = username;
81 this.password = password;
82 this.unifios = unifios;
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())
103 public void start() throws UniFiException {
111 public void stop() throws UniFiException {
115 public void obtainCsrfToken() throws UniFiException {
118 final UniFiControllerRequest<Void> req = newRequest(Void.class, HttpMethod.GET, gson);
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);
134 public void logout() throws UniFiException {
136 final UniFiControllerRequest<Void> req = newRequest(Void.class, HttpMethod.POST, gson);
137 req.setPath(unifios ? "/api/auth/logout" : "/logout");
141 public void refresh() throws UniFiException {
142 synchronized (this) {
144 final Collection<UniFiSite> sites = refreshSites();
146 refreshDevices(sites);
147 refreshClients(sites);
148 refreshInsights(sites);
152 public UniFiControllerCache getCache() {
156 public @Nullable UniFiSwitchPorts getSwitchPorts(@Nullable final String deviceId) {
157 return cache.getSwitchPorts(deviceId);
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());
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());
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));
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);
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);
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");
214 private <T> UniFiControllerRequest<T> newRequest(final Class<T> responseType, final HttpMethod method,
216 return new UniFiControllerRequest<>(responseType, gson, httpClient, method, host, port, csrfToken, unifios);
219 private <T> @Nullable T executeRequest(final UniFiControllerRequest<T> request) throws UniFiException {
220 return executeRequest(request, false);
223 private <T> @Nullable T executeRequest(final UniFiControllerRequest<T> request, final boolean fromLogin)
224 throws UniFiException {
227 result = (T) request.execute();
228 csrfToken = request.getCsrfToken();
229 } catch (final UniFiExpiredSessionException e) {
231 // if this exception is thrown from a login attempt something is wrong, because the login should init
233 throw new UniFiCommunicationException(e);
236 result = (T) executeRequest(request);
238 } catch (final UniFiNotAuthorizedException e) {
239 logger.warn("Not Authorized! Please make sure your controller credentials have administrator rights");
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));
251 private void refreshWlans(final Collection<UniFiSite> sites) throws UniFiException {
252 for (final UniFiSite site : sites) {
253 cache.putWlans(getWlans(site));
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);
263 private void refreshDevices(final Collection<UniFiSite> sites) throws UniFiException {
264 for (final UniFiSite site : sites) {
265 cache.putDevices(getDevices(site));
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);
275 private void refreshClients(final Collection<UniFiSite> sites) throws UniFiException {
276 for (final UniFiSite site : sites) {
277 cache.putClients(getClients(site));
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);
287 private void refreshInsights(final Collection<UniFiSite> sites) throws UniFiException {
288 for (final UniFiSite site : sites) {
289 cache.putInsights(getInsights(site));
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);