]> git.basschouten.com Git - openhab-addons.git/blob
1f3f0e6b91c8c6e469eaa94eafa882d07fc69d1c
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2021 Contributors to the openHAB project
3  *
4  * See the NOTICE file(s) distributed with this work for additional
5  * information.
6  *
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
10  *
11  * SPDX-License-Identifier: EPL-2.0
12  */
13 package org.openhab.binding.robonect.internal;
14
15 import java.net.URI;
16 import java.nio.charset.StandardCharsets;
17 import java.util.concurrent.ExecutionException;
18 import java.util.concurrent.TimeUnit;
19 import java.util.concurrent.TimeoutException;
20
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;
46
47 /**
48  * The {@link RobonectClient} class is responsible to communicate with the robonect module via it's HTTP interface.
49  *
50  * The API of the module is documented here: http://robonect.de/viewtopic.php?f=10&t=37
51  *
52  * @author Marco Meyer - Initial contribution
53  */
54 public class RobonectClient {
55
56     private final Logger logger = LoggerFactory.getLogger(RobonectClient.class);
57
58     private final String baseUrl;
59
60     private final HttpClient httpClient;
61
62     private final ModelParser parser;
63
64     private boolean jobRunning;
65
66     /**
67      * The {@link JobSettings} class holds the values required for starting a job.
68      */
69     public static class JobSettings {
70
71         private static final String TIME_REGEX = "^[012]\\d:\\d\\d$";
72
73         private final Logger logger = LoggerFactory.getLogger(RobonectClient.class);
74
75         private ModeCommand.RemoteStart remoteStart;
76         private ModeCommand.Mode after;
77         private int duration;
78
79         /**
80          * returns the 'remote start' setting for the job. See {@link ModeCommand.RemoteStart} for details.
81          *
82          * @return - the remote start settings for the job.
83          */
84         public ModeCommand.RemoteStart getRemoteStart() {
85             if (remoteStart != null) {
86                 return remoteStart;
87             } else {
88                 logger.debug("No explicit remote start set. Return STANDARD.");
89                 return ModeCommand.RemoteStart.STANDARD;
90             }
91         }
92
93         /**
94          * Sets the desired 'remote start' settings for the job.
95          *
96          * @param remoteStart - The 'remote start' settings. See {@link ModeCommand.RemoteStart} for the allowed modes.
97          */
98         public JobSettings withRemoteStart(ModeCommand.RemoteStart remoteStart) {
99             this.remoteStart = remoteStart;
100             return this;
101         }
102
103         /**
104          * Returns the mode the mower should be set to after the job is complete.
105          *
106          * @return - the mode after compleness of the job.
107          */
108         public ModeCommand.Mode getAfterMode() {
109             return after;
110         }
111
112         /**
113          * Sets the mode after the mower is complete with the job.
114          *
115          * @param after - the desired mode after job completeness.
116          */
117         public JobSettings withAfterMode(ModeCommand.Mode after) {
118             this.after = after;
119             return this;
120         }
121
122         public int getDuration() {
123             return duration;
124         }
125
126         public JobSettings withDuration(int duration) {
127             this.duration = duration;
128             return this;
129         }
130     }
131
132     private static class BasicResult implements Authentication.Result {
133
134         private final HttpHeader header;
135         private final URI uri;
136         private final String value;
137
138         public BasicResult(HttpHeader header, URI uri, String value) {
139             this.header = header;
140             this.uri = uri;
141             this.value = value;
142         }
143
144         @Override
145         public URI getURI() {
146             return this.uri;
147         }
148
149         @Override
150         public void apply(Request request) {
151             request.header(this.header, this.value);
152         }
153
154         @Override
155         public String toString() {
156             return String.format("Basic authentication result for %s", this.uri);
157         }
158     }
159
160     /**
161      * Creates an instance of RobonectClient which allows to communicate with the specified endpoint via the passed
162      * httpClient instance.
163      *
164      * @param httpClient - The HttpClient to use for the communication.
165      * @param endpoint - The endpoint information for connecting and issuing commands.
166      */
167     public RobonectClient(HttpClient httpClient, RobonectEndpoint endpoint) {
168         this.httpClient = httpClient;
169         this.baseUrl = "http://" + endpoint.getIpAddress() + "/json";
170         this.parser = new ModelParser();
171
172         if (endpoint.isUseAuthentication()) {
173             addPreemptiveAuthentication(httpClient, endpoint);
174         }
175     }
176
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)));
182     }
183
184     /**
185      * returns general mower information. See {@MowerInfo} for the detailed information.
186      *
187      * @return - the general mower information including a general success status.
188      */
189     public MowerInfo getMowerInfo() {
190         String responseString = sendCommand(new StatusCommand());
191         MowerInfo mowerInfo = parser.parse(responseString, MowerInfo.class);
192         if (jobRunning) {
193             // mode might have been changed on the mower. Also Mode JOB does not really exist on the mower, thus cannot
194             // be checked here
195             if (mowerInfo.getStatus().getMode() == MowerMode.AUTO
196                     || mowerInfo.getStatus().getMode() == MowerMode.HOME) {
197                 jobRunning = false;
198             } else if (mowerInfo.getError() != null) {
199                 jobRunning = false;
200             }
201         }
202         return mowerInfo;
203     }
204
205     /**
206      * sends a start command to the mower.
207      *
208      * @return - a general answer with success status.
209      */
210     public RobonectAnswer start() {
211         String responseString = sendCommand(new StartCommand());
212         return parser.parse(responseString, RobonectAnswer.class);
213     }
214
215     /**
216      * sends a stop command to the mower.
217      *
218      * @return - a general answer with success status.
219      */
220     public RobonectAnswer stop() {
221         String responseString = sendCommand(new StopCommand());
222         return parser.parse(responseString, RobonectAnswer.class);
223     }
224
225     /**
226      * resets the errors on the mower.
227      *
228      * @return - a general answer with success status.
229      */
230     public RobonectAnswer resetErrors() {
231         String responseString = sendCommand(new ErrorCommand().withReset(true));
232         return parser.parse(responseString, RobonectAnswer.class);
233     }
234
235     /**
236      * returns the list of all errors happened since last reset.
237      *
238      * @return - the list of errors.
239      */
240     public ErrorList errorList() {
241         String responseString = sendCommand(new ErrorCommand());
242         return parser.parse(responseString, ErrorList.class);
243     }
244
245     /**
246      * Sets the mode of the mower. See {@link ModeCommand.Mode} for details about the available modes. Not allowed is
247      * mode
248      * {@link ModeCommand.Mode#JOB}.
249      *
250      * @param mode - the desired mower mode.
251      * @return - a general answer with success status.
252      */
253     public RobonectAnswer setMode(ModeCommand.Mode mode) {
254         String responseString = sendCommand(createCommand(mode));
255         if (jobRunning) {
256             jobRunning = false;
257         }
258         return parser.parse(responseString, RobonectAnswer.class);
259     }
260
261     private ModeCommand createCommand(ModeCommand.Mode mode) {
262         return new ModeCommand(mode);
263     }
264
265     /**
266      * Returns the name of the mower.
267      *
268      * @return - The name including a general answer with success status.
269      */
270     public Name getName() {
271         String responseString = sendCommand(new NameCommand());
272         return parser.parse(responseString, Name.class);
273     }
274
275     /**
276      * Allows to set the name of the mower.
277      *
278      * @param name - the desired name.
279      * @return - The resulting name including a general answer with success status.
280      */
281     public Name setName(String name) {
282         String responseString = sendCommand(new NameCommand().withNewName(name));
283         return parser.parse(responseString, Name.class);
284     }
285
286     private String sendCommand(Command command) {
287         try {
288             if (logger.isDebugEnabled()) {
289                 logger.debug("send HTTP GET to: {} ", command.toCommandURL(baseUrl));
290             }
291             ContentResponse response = httpClient.newRequest(command.toCommandURL(baseUrl)).method(HttpMethod.GET)
292                     .timeout(30000, TimeUnit.MILLISECONDS).send();
293             String responseString = null;
294
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);
298             } else {
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();
302             }
303
304             if (logger.isDebugEnabled()) {
305                 logger.debug("Response body was: {} ", responseString);
306             }
307             return responseString;
308         } catch (ExecutionException | TimeoutException | InterruptedException e) {
309             throw new RobonectCommunicationException("Could not send command " + command.toCommandURL(baseUrl), e);
310         }
311     }
312
313     /**
314      * Retrieve the version information of the mower and module. See {@link VersionInfo} for details.
315      *
316      * @return - the Version Information including the successful status.
317      */
318     public VersionInfo getVersionInfo() {
319         String versionResponse = sendCommand(new VersionCommand());
320         return parser.parse(versionResponse, VersionInfo.class);
321     }
322
323     public boolean isJobRunning() {
324         return jobRunning;
325     }
326
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()) {
333             jobRunning = true;
334         } else {
335             jobRunning = false;
336         }
337         return answer;
338     }
339
340     public RobonectAnswer stopJob(JobSettings settings) {
341         RobonectAnswer answer = null;
342         if (jobRunning) {
343             answer = setMode(settings.after);
344             if (answer.isSuccessful()) {
345                 jobRunning = false;
346             }
347         } else {
348             answer = new RobonectAnswer();
349             // this is not an error, thus return success
350             answer.setSuccessful(true);
351         }
352         return answer;
353     }
354 }