2 * Copyright (c) 2010-2020 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.apache.commons.lang.StringUtils;
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.eclipse.jetty.util.B64Code;
30 import org.openhab.binding.robonect.internal.model.ErrorList;
31 import org.openhab.binding.robonect.internal.model.ModelParser;
32 import org.openhab.binding.robonect.internal.model.MowerInfo;
33 import org.openhab.binding.robonect.internal.model.MowerMode;
34 import org.openhab.binding.robonect.internal.model.Name;
35 import org.openhab.binding.robonect.internal.model.RobonectAnswer;
36 import org.openhab.binding.robonect.internal.model.VersionInfo;
37 import org.openhab.binding.robonect.internal.model.cmd.Command;
38 import org.openhab.binding.robonect.internal.model.cmd.ErrorCommand;
39 import org.openhab.binding.robonect.internal.model.cmd.ModeCommand;
40 import org.openhab.binding.robonect.internal.model.cmd.NameCommand;
41 import org.openhab.binding.robonect.internal.model.cmd.StartCommand;
42 import org.openhab.binding.robonect.internal.model.cmd.StatusCommand;
43 import org.openhab.binding.robonect.internal.model.cmd.StopCommand;
44 import org.openhab.binding.robonect.internal.model.cmd.VersionCommand;
45 import org.slf4j.Logger;
46 import org.slf4j.LoggerFactory;
49 * The {@link RobonectClient} class is responsible to communicate with the robonect module via it's HTTP interface.
51 * The API of the module is documented here: http://robonect.de/viewtopic.php?f=10&t=37
53 * @author Marco Meyer - Initial contribution
55 public class RobonectClient {
57 private final Logger logger = LoggerFactory.getLogger(RobonectClient.class);
59 private final String baseUrl;
61 private final HttpClient httpClient;
63 private final ModelParser parser;
65 private boolean jobRunning;
68 * The {@link JobSettings} class holds the values required for starting a job.
70 public static class JobSettings {
72 private static final String TIME_REGEX = "^[012]\\d:\\d\\d$";
74 private final Logger logger = LoggerFactory.getLogger(RobonectClient.class);
76 private ModeCommand.RemoteStart remoteStart;
77 private ModeCommand.Mode after;
81 * returns the 'remote start' setting for the job. See {@link ModeCommand.RemoteStart} for details.
83 * @return - the remote start settings for the job.
85 public ModeCommand.RemoteStart getRemoteStart() {
86 if (remoteStart != null) {
89 logger.debug("No explicit remote start set. Return STANDARD.");
90 return ModeCommand.RemoteStart.STANDARD;
95 * Sets the desired 'remote start' settings for the job.
97 * @param remoteStart - The 'remote start' settings. See {@link ModeCommand.RemoteStart} for the allowed modes.
99 public JobSettings withRemoteStart(ModeCommand.RemoteStart remoteStart) {
100 this.remoteStart = remoteStart;
105 * Returns the mode the mower should be set to after the job is complete.
107 * @return - the mode after compleness of the job.
109 public ModeCommand.Mode getAfterMode() {
114 * Sets the mode after the mower is complete with the job.
116 * @param after - the desired mode after job completeness.
118 public JobSettings withAfterMode(ModeCommand.Mode after) {
123 public int getDuration() {
127 public JobSettings withDuration(int duration) {
128 this.duration = duration;
133 private static class BasicResult implements Authentication.Result {
135 private final HttpHeader header;
136 private final URI uri;
137 private final String value;
139 public BasicResult(HttpHeader header, URI uri, String value) {
140 this.header = header;
145 public URI getURI() {
149 public void apply(Request request) {
150 request.header(this.header, this.value);
153 public String toString() {
154 return String.format("Basic authentication result for %s", this.uri);
159 * Creates an instance of RobonectClient which allows to communicate with the specified endpoint via the passed
160 * httpClient instance.
162 * @param httpClient - The HttpClient to use for the communication.
163 * @param endpoint - The endpoint information for connecting and issuing commands.
165 public RobonectClient(HttpClient httpClient, RobonectEndpoint endpoint) {
166 this.httpClient = httpClient;
167 this.baseUrl = "http://" + endpoint.getIpAddress() + "/json";
168 this.parser = new ModelParser();
170 if (endpoint.isUseAuthentication()) {
171 addPreemptiveAuthentication(httpClient, endpoint);
175 private void addPreemptiveAuthentication(HttpClient httpClient, RobonectEndpoint endpoint) {
176 AuthenticationStore auth = httpClient.getAuthenticationStore();
177 URI uri = URI.create(baseUrl);
178 auth.addAuthenticationResult(new BasicResult(HttpHeader.AUTHORIZATION, uri, "Basic "
179 + B64Code.encode(endpoint.getUser() + ":" + endpoint.getPassword(), StandardCharsets.ISO_8859_1)));
183 * returns general mower information. See {@MowerInfo} for the detailed information.
185 * @return - the general mower information including a general success status.
187 public MowerInfo getMowerInfo() {
188 String responseString = sendCommand(new StatusCommand());
189 MowerInfo mowerInfo = parser.parse(responseString, MowerInfo.class);
191 // mode might have been changed on the mower. Also Mode JOB does not really exist on the mower, thus cannot
193 if (mowerInfo.getStatus().getMode() == MowerMode.AUTO
194 || mowerInfo.getStatus().getMode() == MowerMode.HOME) {
196 } else if (mowerInfo.getError() != null) {
204 * sends a start command to the mower.
206 * @return - a general answer with success status.
208 public RobonectAnswer start() {
209 String responseString = sendCommand(new StartCommand());
210 return parser.parse(responseString, RobonectAnswer.class);
214 * sends a stop command to the mower.
216 * @return - a general answer with success status.
218 public RobonectAnswer stop() {
219 String responseString = sendCommand(new StopCommand());
220 return parser.parse(responseString, RobonectAnswer.class);
224 * resets the errors on the mower.
226 * @return - a general answer with success status.
228 public RobonectAnswer resetErrors() {
229 String responseString = sendCommand(new ErrorCommand().withReset(true));
230 return parser.parse(responseString, RobonectAnswer.class);
234 * returns the list of all errors happened since last reset.
236 * @return - the list of errors.
238 public ErrorList errorList() {
239 String responseString = sendCommand(new ErrorCommand());
240 return parser.parse(responseString, ErrorList.class);
244 * Sets the mode of the mower. See {@link ModeCommand.Mode} for details about the available modes. Not allowed is
246 * {@link ModeCommand.Mode#JOB}.
248 * @param mode - the desired mower mode.
249 * @return - a general answer with success status.
251 public RobonectAnswer setMode(ModeCommand.Mode mode) {
252 String responseString = sendCommand(createCommand(mode));
256 return parser.parse(responseString, RobonectAnswer.class);
259 private ModeCommand createCommand(ModeCommand.Mode mode) {
260 return new ModeCommand(mode);
264 * Returns the name of the mower.
266 * @return - The name including a general answer with success status.
268 public Name getName() {
269 String responseString = sendCommand(new NameCommand());
270 return parser.parse(responseString, Name.class);
274 * Allows to set the name of the mower.
276 * @param name - the desired name.
277 * @return - The resulting name including a general answer with success status.
279 public Name setName(String name) {
280 String responseString = sendCommand(new NameCommand().withNewName(name));
281 return parser.parse(responseString, Name.class);
284 private String sendCommand(Command command) {
286 if (logger.isDebugEnabled()) {
287 logger.debug("send HTTP GET to: {} ", command.toCommandURL(baseUrl));
289 ContentResponse response = httpClient.newRequest(command.toCommandURL(baseUrl)).method(HttpMethod.GET)
290 .timeout(30000, TimeUnit.MILLISECONDS).send();
291 String responseString = null;
293 // jetty uses UTF-8 as default encoding. However, HTTP 1.1 specifies ISO_8859_1
294 if (StringUtils.isBlank(response.getEncoding())) {
295 responseString = new String(response.getContent(), StandardCharsets.ISO_8859_1);
297 // currently v0.9e Robonect does not specifiy the encoding. But if later versions will
298 // add, it should work with the default method to get the content as string.
299 responseString = response.getContentAsString();
302 if (logger.isDebugEnabled()) {
303 logger.debug("Response body was: {} ", responseString);
305 return responseString;
306 } catch (ExecutionException | TimeoutException | InterruptedException e) {
307 throw new RobonectCommunicationException("Could not send command " + command.toCommandURL(baseUrl), e);
312 * Retrieve the version information of the mower and module. See {@link VersionInfo} for details.
314 * @return - the Version Information including the successful status.
316 public VersionInfo getVersionInfo() {
317 String versionResponse = sendCommand(new VersionCommand());
318 return parser.parse(versionResponse, VersionInfo.class);
321 public boolean isJobRunning() {
325 public RobonectAnswer startJob(JobSettings settings) {
326 Command jobCommand = new ModeCommand(ModeCommand.Mode.JOB).withRemoteStart(settings.remoteStart)
327 .withAfter(settings.after).withDuration(settings.duration);
328 String responseString = sendCommand(jobCommand);
329 RobonectAnswer answer = parser.parse(responseString, RobonectAnswer.class);
330 if (answer.isSuccessful()) {
338 public RobonectAnswer stopJob(JobSettings settings) {
339 RobonectAnswer answer = null;
341 answer = setMode(settings.after);
342 if (answer.isSuccessful()) {
346 answer = new RobonectAnswer();
347 // this is not an error, thus return success
348 answer.setSuccessful(true);