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.nikobus.internal.protocol;
15 import java.util.concurrent.Callable;
16 import java.util.concurrent.atomic.AtomicBoolean;
17 import java.util.function.Consumer;
19 import org.eclipse.jdt.annotation.NonNullByDefault;
20 import org.eclipse.jdt.annotation.Nullable;
21 import org.slf4j.Logger;
22 import org.slf4j.LoggerFactory;
25 * The {@link NikobusCommand} class holds a command that can be send to Nikobus installation.
27 * @author Boris Krivonog - Initial contribution
30 public class NikobusCommand {
31 public static class Result {
32 private final Callable<String> callable;
34 private Result(String result) {
35 callable = () -> result;
38 private Result(Exception exception) {
44 public String get() throws Exception {
45 return callable.call();
49 public static class ResponseHandler {
50 private final Logger logger = LoggerFactory.getLogger(ResponseHandler.class);
51 private final Consumer<Result> resultConsumer;
52 private final int responseLength;
53 private final int addressStart;
54 private final String responseCode;
55 private final AtomicBoolean isCompleted = new AtomicBoolean();
57 private ResponseHandler(int responseLength, int addressStart, String responseCode,
58 Consumer<Result> resultConsumer) {
59 this.responseLength = responseLength;
60 this.addressStart = addressStart;
61 this.responseCode = responseCode;
62 this.resultConsumer = resultConsumer;
65 public boolean isCompleted() {
66 return isCompleted.get();
69 public boolean complete(String result) {
70 return complete(new Result(result));
73 public boolean completeExceptionally(Exception exception) {
74 return complete(new Result(exception));
77 private boolean complete(Result result) {
78 if (isCompleted.getAndSet(true)) {
83 resultConsumer.accept(result);
84 } catch (RuntimeException e) {
85 logger.warn("Processing result {} failed with {}", result, e.getMessage(), e);
91 public int getResponseLength() {
92 return responseLength;
95 public int getAddressStart() {
99 public String getResponseCode() {
104 private final String payload;
105 private final @Nullable ResponseHandler responseHandler;
107 public NikobusCommand(String payload) {
108 this.payload = payload + '\r';
109 this.responseHandler = null;
112 public NikobusCommand(String payload, int responseLength, int addressStart, String responseCode,
113 Consumer<Result> resultConsumer) {
114 this.payload = payload + '\r';
115 this.responseHandler = new ResponseHandler(responseLength, addressStart, responseCode, resultConsumer);
118 public String getPayload() {
122 public @Nullable ResponseHandler getResponseHandler() {
123 return responseHandler;