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.networkupstools.internal.nut;
17 import org.eclipse.jdt.annotation.NonNullByDefault;
20 * API implementation handling communicating with the NUT server.
22 * @author Hilbrand Bouwkamp - Initial contribution
27 private static final String LIST_VAR = "LIST VAR %s";
28 private static final String VAR = "VAR %s";
29 private static final String LIST_UPS = "LIST UPS";
30 private static final String UPS = "UPS ";
31 private static final String GET_VAR = "GET VAR %s %s";
33 private final NutResponseReader responseReader = new NutResponseReader();
34 private final NutConnector connector;
41 * @param username username
42 * @param password password
44 public NutApi(final String host, final int port, final String username, final String password) {
45 this.connector = new NutConnector(host, port, username, password);
49 * Constructor for unit tests to inject mock connector.
51 * @param connector Connector.
53 NutApi(final NutConnector connector) {
54 this.connector = connector;
58 * Closes the connector.
65 * Retrieves a list of the UPS devices available from the NUT server.
67 * @return List of UPS devices
68 * @throws NutException Exception in case of any error related to the API.
70 public Map<String, String> getUpsList() throws NutException {
71 return connector.read(LIST_UPS, r -> responseReader.parseList(UPS, r));
75 * Retrieves a list of the variables available for the given UPS.
77 * @param ups UPS to get the variables for
78 * @return List of variables for the given UPS
79 * @throws NutException Exception in case of any error related to the API.
81 public Map<String, String> getVariables(final String ups) throws NutException {
82 return connector.read(String.format(LIST_VAR, ups), r -> responseReader.parseList(String.format(VAR, ups), r));
86 * Retrieves the value of the given nut variable for the given UPS.
88 * @param ups UPS to get the variables for
89 * @param nut The variable to the value for
90 * @return Returns the value for the given nut
91 * @throws NutException Exception when the variable could not retrieved
93 public String getVariable(final String ups, final String nut) throws NutException {
94 return connector.read(String.format(GET_VAR, ups, nut), r -> responseReader.parseVariable(ups, nut, r));