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.robonect.internal;
16 import java.nio.charset.StandardCharsets;
17 import java.util.Base64;
18 import java.util.concurrent.ExecutionException;
19 import java.util.concurrent.TimeUnit;
20 import java.util.concurrent.TimeoutException;
22 import org.eclipse.jetty.client.HttpClient;
23 import org.eclipse.jetty.client.api.Authentication;
24 import org.eclipse.jetty.client.api.AuthenticationStore;
25 import org.eclipse.jetty.client.api.ContentResponse;
26 import org.eclipse.jetty.client.api.Request;
27 import org.eclipse.jetty.http.HttpHeader;
28 import org.eclipse.jetty.http.HttpMethod;
29 import org.openhab.binding.robonect.internal.model.ErrorList;
30 import org.openhab.binding.robonect.internal.model.ModelParser;
31 import org.openhab.binding.robonect.internal.model.MowerInfo;
32 import org.openhab.binding.robonect.internal.model.MowerMode;
33 import org.openhab.binding.robonect.internal.model.Name;
34 import org.openhab.binding.robonect.internal.model.RobonectAnswer;
35 import org.openhab.binding.robonect.internal.model.VersionInfo;
36 import org.openhab.binding.robonect.internal.model.cmd.Command;
37 import org.openhab.binding.robonect.internal.model.cmd.ErrorCommand;
38 import org.openhab.binding.robonect.internal.model.cmd.ModeCommand;
39 import org.openhab.binding.robonect.internal.model.cmd.NameCommand;
40 import org.openhab.binding.robonect.internal.model.cmd.StartCommand;
41 import org.openhab.binding.robonect.internal.model.cmd.StatusCommand;
42 import org.openhab.binding.robonect.internal.model.cmd.StopCommand;
43 import org.openhab.binding.robonect.internal.model.cmd.VersionCommand;
44 import org.slf4j.Logger;
45 import org.slf4j.LoggerFactory;
48 * The {@link RobonectClient} class is responsible to communicate with the robonect module via it's HTTP interface.
50 * The API of the module is documented here: http://robonect.de/viewtopic.php?f=10&t=37
52 * @author Marco Meyer - Initial contribution
54 public class RobonectClient {
56 private final Logger logger = LoggerFactory.getLogger(RobonectClient.class);
58 private final String baseUrl;
60 private final HttpClient httpClient;
62 private final ModelParser parser;
64 private boolean jobRunning;
67 * The {@link JobSettings} class holds the values required for starting a job.
69 public static class JobSettings {
71 private static final String TIME_REGEX = "^[012]\\d:\\d\\d$";
73 private final Logger logger = LoggerFactory.getLogger(RobonectClient.class);
75 private ModeCommand.RemoteStart remoteStart;
76 private ModeCommand.Mode after;
80 * returns the 'remote start' setting for the job. See {@link ModeCommand.RemoteStart} for details.
82 * @return - the remote start settings for the job.
84 public ModeCommand.RemoteStart getRemoteStart() {
85 if (remoteStart != null) {
88 logger.debug("No explicit remote start set. Return STANDARD.");
89 return ModeCommand.RemoteStart.STANDARD;
94 * Sets the desired 'remote start' settings for the job.
96 * @param remoteStart - The 'remote start' settings. See {@link ModeCommand.RemoteStart} for the allowed modes.
98 public JobSettings withRemoteStart(ModeCommand.RemoteStart remoteStart) {
99 this.remoteStart = remoteStart;
104 * Returns the mode the mower should be set to after the job is complete.
106 * @return - the mode after compleness of the job.
108 public ModeCommand.Mode getAfterMode() {
113 * Sets the mode after the mower is complete with the job.
115 * @param after - the desired mode after job completeness.
117 public JobSettings withAfterMode(ModeCommand.Mode after) {
122 public int getDuration() {
126 public JobSettings withDuration(int duration) {
127 this.duration = duration;
132 private static class BasicResult implements Authentication.Result {
134 private final HttpHeader header;
135 private final URI uri;
136 private final String value;
138 public BasicResult(HttpHeader header, URI uri, String value) {
139 this.header = header;
145 public URI getURI() {
150 public void apply(Request request) {
151 request.header(this.header, this.value);
155 public String toString() {
156 return String.format("Basic authentication result for %s", this.uri);
161 * Creates an instance of RobonectClient which allows to communicate with the specified endpoint via the passed
162 * httpClient instance.
164 * @param httpClient - The HttpClient to use for the communication.
165 * @param endpoint - The endpoint information for connecting and issuing commands.
167 public RobonectClient(HttpClient httpClient, RobonectEndpoint endpoint) {
168 this.httpClient = httpClient;
169 this.baseUrl = "http://" + endpoint.getIpAddress() + "/json";
170 this.parser = new ModelParser();
172 if (endpoint.isUseAuthentication()) {
173 addPreemptiveAuthentication(httpClient, endpoint);
177 private void addPreemptiveAuthentication(HttpClient httpClient, RobonectEndpoint endpoint) {
178 AuthenticationStore auth = httpClient.getAuthenticationStore();
179 URI uri = URI.create(baseUrl);
180 auth.addAuthenticationResult(
181 new BasicResult(HttpHeader.AUTHORIZATION, uri, "Basic " + Base64.getEncoder().encodeToString(
182 (endpoint.getUser() + ":" + endpoint.getPassword()).getBytes(StandardCharsets.ISO_8859_1))));
186 * returns general mower information. See {@MowerInfo} for the detailed information.
188 * @return - the general mower information including a general success status.
190 public MowerInfo getMowerInfo() {
191 String responseString = sendCommand(new StatusCommand());
192 MowerInfo mowerInfo = parser.parse(responseString, MowerInfo.class);
194 // mode might have been changed on the mower. Also Mode JOB does not really exist on the mower, thus cannot
196 if (mowerInfo.getStatus().getMode() == MowerMode.AUTO
197 || mowerInfo.getStatus().getMode() == MowerMode.HOME) {
199 } else if (mowerInfo.getError() != null) {
207 * sends a start command to the mower.
209 * @return - a general answer with success status.
211 public RobonectAnswer start() {
212 String responseString = sendCommand(new StartCommand());
213 return parser.parse(responseString, RobonectAnswer.class);
217 * sends a stop command to the mower.
219 * @return - a general answer with success status.
221 public RobonectAnswer stop() {
222 String responseString = sendCommand(new StopCommand());
223 return parser.parse(responseString, RobonectAnswer.class);
227 * resets the errors on the mower.
229 * @return - a general answer with success status.
231 public RobonectAnswer resetErrors() {
232 String responseString = sendCommand(new ErrorCommand().withReset(true));
233 return parser.parse(responseString, RobonectAnswer.class);
237 * returns the list of all errors happened since last reset.
239 * @return - the list of errors.
241 public ErrorList errorList() {
242 String responseString = sendCommand(new ErrorCommand());
243 return parser.parse(responseString, ErrorList.class);
247 * Sets the mode of the mower. See {@link ModeCommand.Mode} for details about the available modes. Not allowed is
249 * {@link ModeCommand.Mode#JOB}.
251 * @param mode - the desired mower mode.
252 * @return - a general answer with success status.
254 public RobonectAnswer setMode(ModeCommand.Mode mode) {
255 String responseString = sendCommand(createCommand(mode));
259 return parser.parse(responseString, RobonectAnswer.class);
262 private ModeCommand createCommand(ModeCommand.Mode mode) {
263 return new ModeCommand(mode);
267 * Returns the name of the mower.
269 * @return - The name including a general answer with success status.
271 public Name getName() {
272 String responseString = sendCommand(new NameCommand());
273 return parser.parse(responseString, Name.class);
277 * Allows to set the name of the mower.
279 * @param name - the desired name.
280 * @return - The resulting name including a general answer with success status.
282 public Name setName(String name) {
283 String responseString = sendCommand(new NameCommand().withNewName(name));
284 return parser.parse(responseString, Name.class);
287 private String sendCommand(Command command) {
289 if (logger.isDebugEnabled()) {
290 logger.debug("send HTTP GET to: {} ", command.toCommandURL(baseUrl));
292 ContentResponse response = httpClient.newRequest(command.toCommandURL(baseUrl)).method(HttpMethod.GET)
293 .timeout(30000, TimeUnit.MILLISECONDS).send();
294 String responseString = null;
296 // jetty uses UTF-8 as default encoding. However, HTTP 1.1 specifies ISO_8859_1
297 if (response.getEncoding() == null || response.getEncoding().isBlank()) {
298 responseString = new String(response.getContent(), StandardCharsets.ISO_8859_1);
300 // currently v0.9e Robonect does not specifiy the encoding. But if later versions will
301 // add, it should work with the default method to get the content as string.
302 responseString = response.getContentAsString();
305 if (logger.isDebugEnabled()) {
306 logger.debug("Response body was: {} ", responseString);
308 return responseString;
309 } catch (ExecutionException | TimeoutException | InterruptedException e) {
310 throw new RobonectCommunicationException("Could not send command " + command.toCommandURL(baseUrl), e);
315 * Retrieve the version information of the mower and module. See {@link VersionInfo} for details.
317 * @return - the Version Information including the successful status.
319 public VersionInfo getVersionInfo() {
320 String versionResponse = sendCommand(new VersionCommand());
321 return parser.parse(versionResponse, VersionInfo.class);
324 public boolean isJobRunning() {
328 public RobonectAnswer startJob(JobSettings settings) {
329 Command jobCommand = new ModeCommand(ModeCommand.Mode.JOB).withRemoteStart(settings.remoteStart)
330 .withAfter(settings.after).withDuration(settings.duration);
331 String responseString = sendCommand(jobCommand);
332 RobonectAnswer answer = parser.parse(responseString, RobonectAnswer.class);
333 if (answer.isSuccessful()) {
341 public RobonectAnswer stopJob(JobSettings settings) {
342 RobonectAnswer answer = null;
344 answer = setMode(settings.after);
345 if (answer.isSuccessful()) {
349 answer = new RobonectAnswer();
350 // this is not an error, thus return success
351 answer.setSuccessful(true);