2 * Copyright (c) 2010-2021 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.concurrent.ExecutionException;
18 import java.util.concurrent.TimeUnit;
19 import java.util.concurrent.TimeoutException;
21 import org.eclipse.jetty.client.HttpClient;
22 import org.eclipse.jetty.client.api.Authentication;
23 import org.eclipse.jetty.client.api.AuthenticationStore;
24 import org.eclipse.jetty.client.api.ContentResponse;
25 import org.eclipse.jetty.client.api.Request;
26 import org.eclipse.jetty.http.HttpHeader;
27 import org.eclipse.jetty.http.HttpMethod;
28 import org.eclipse.jetty.util.B64Code;
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(new BasicResult(HttpHeader.AUTHORIZATION, uri, "Basic "
181 + B64Code.encode(endpoint.getUser() + ":" + endpoint.getPassword(), StandardCharsets.ISO_8859_1)));
185 * returns general mower information. See {@MowerInfo} for the detailed information.
187 * @return - the general mower information including a general success status.
189 public MowerInfo getMowerInfo() {
190 String responseString = sendCommand(new StatusCommand());
191 MowerInfo mowerInfo = parser.parse(responseString, MowerInfo.class);
193 // mode might have been changed on the mower. Also Mode JOB does not really exist on the mower, thus cannot
195 if (mowerInfo.getStatus().getMode() == MowerMode.AUTO
196 || mowerInfo.getStatus().getMode() == MowerMode.HOME) {
198 } else if (mowerInfo.getError() != null) {
206 * sends a start command to the mower.
208 * @return - a general answer with success status.
210 public RobonectAnswer start() {
211 String responseString = sendCommand(new StartCommand());
212 return parser.parse(responseString, RobonectAnswer.class);
216 * sends a stop command to the mower.
218 * @return - a general answer with success status.
220 public RobonectAnswer stop() {
221 String responseString = sendCommand(new StopCommand());
222 return parser.parse(responseString, RobonectAnswer.class);
226 * resets the errors on the mower.
228 * @return - a general answer with success status.
230 public RobonectAnswer resetErrors() {
231 String responseString = sendCommand(new ErrorCommand().withReset(true));
232 return parser.parse(responseString, RobonectAnswer.class);
236 * returns the list of all errors happened since last reset.
238 * @return - the list of errors.
240 public ErrorList errorList() {
241 String responseString = sendCommand(new ErrorCommand());
242 return parser.parse(responseString, ErrorList.class);
246 * Sets the mode of the mower. See {@link ModeCommand.Mode} for details about the available modes. Not allowed is
248 * {@link ModeCommand.Mode#JOB}.
250 * @param mode - the desired mower mode.
251 * @return - a general answer with success status.
253 public RobonectAnswer setMode(ModeCommand.Mode mode) {
254 String responseString = sendCommand(createCommand(mode));
258 return parser.parse(responseString, RobonectAnswer.class);
261 private ModeCommand createCommand(ModeCommand.Mode mode) {
262 return new ModeCommand(mode);
266 * Returns the name of the mower.
268 * @return - The name including a general answer with success status.
270 public Name getName() {
271 String responseString = sendCommand(new NameCommand());
272 return parser.parse(responseString, Name.class);
276 * Allows to set the name of the mower.
278 * @param name - the desired name.
279 * @return - The resulting name including a general answer with success status.
281 public Name setName(String name) {
282 String responseString = sendCommand(new NameCommand().withNewName(name));
283 return parser.parse(responseString, Name.class);
286 private String sendCommand(Command command) {
288 if (logger.isDebugEnabled()) {
289 logger.debug("send HTTP GET to: {} ", command.toCommandURL(baseUrl));
291 ContentResponse response = httpClient.newRequest(command.toCommandURL(baseUrl)).method(HttpMethod.GET)
292 .timeout(30000, TimeUnit.MILLISECONDS).send();
293 String responseString = null;
295 // jetty uses UTF-8 as default encoding. However, HTTP 1.1 specifies ISO_8859_1
296 if (response.getEncoding() == null || response.getEncoding().isBlank()) {
297 responseString = new String(response.getContent(), StandardCharsets.ISO_8859_1);
299 // currently v0.9e Robonect does not specifiy the encoding. But if later versions will
300 // add, it should work with the default method to get the content as string.
301 responseString = response.getContentAsString();
304 if (logger.isDebugEnabled()) {
305 logger.debug("Response body was: {} ", responseString);
307 return responseString;
308 } catch (ExecutionException | TimeoutException | InterruptedException e) {
309 throw new RobonectCommunicationException("Could not send command " + command.toCommandURL(baseUrl), e);
314 * Retrieve the version information of the mower and module. See {@link VersionInfo} for details.
316 * @return - the Version Information including the successful status.
318 public VersionInfo getVersionInfo() {
319 String versionResponse = sendCommand(new VersionCommand());
320 return parser.parse(versionResponse, VersionInfo.class);
323 public boolean isJobRunning() {
327 public RobonectAnswer startJob(JobSettings settings) {
328 Command jobCommand = new ModeCommand(ModeCommand.Mode.JOB).withRemoteStart(settings.remoteStart)
329 .withAfter(settings.after).withDuration(settings.duration);
330 String responseString = sendCommand(jobCommand);
331 RobonectAnswer answer = parser.parse(responseString, RobonectAnswer.class);
332 if (answer.isSuccessful()) {
340 public RobonectAnswer stopJob(JobSettings settings) {
341 RobonectAnswer answer = null;
343 answer = setMode(settings.after);
344 if (answer.isSuccessful()) {
348 answer = new RobonectAnswer();
349 // this is not an error, thus return success
350 answer.setSuccessful(true);