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.revogi.internal.api;
15 import java.util.List;
16 import java.util.Objects;
17 import java.util.concurrent.CompletableFuture;
19 import org.eclipse.jdt.annotation.NonNullByDefault;
20 import org.openhab.binding.revogi.internal.udp.UdpResponseDTO;
21 import org.openhab.binding.revogi.internal.udp.UdpSenderService;
22 import org.slf4j.Logger;
23 import org.slf4j.LoggerFactory;
25 import com.google.gson.Gson;
26 import com.google.gson.GsonBuilder;
27 import com.google.gson.JsonSyntaxException;
30 * The {@link StatusService} contains methods to get a status of a Revogi SmartStrip
32 * @author Andi Bräu - Initial contribution
35 public class StatusService {
37 private static final String UDP_DISCOVERY_QUERY = "V3{\"sn\":\"%s\", \"cmd\": 90}";
38 public static final String VERSION_STRING = "V3";
39 private final Logger logger = LoggerFactory.getLogger(StatusService.class);
41 private final Gson gson = new GsonBuilder().create();
42 private final UdpSenderService udpSenderService;
44 public StatusService(UdpSenderService udpSenderService) {
45 this.udpSenderService = udpSenderService;
48 public CompletableFuture<StatusDTO> queryStatus(String serialNumber, String ipAddress) {
49 CompletableFuture<List<UdpResponseDTO>> responses;
50 if (ipAddress.trim().isEmpty()) {
51 responses = udpSenderService.broadcastUdpDatagram(String.format(UDP_DISCOVERY_QUERY, serialNumber));
53 responses = udpSenderService.sendMessage(String.format(UDP_DISCOVERY_QUERY, serialNumber), ipAddress);
55 return responses.thenApply(this::getStatus);
58 private StatusDTO getStatus(final List<UdpResponseDTO> singleResponse) {
59 return singleResponse.stream()
60 .filter(response -> !response.getAnswer().isEmpty() && response.getAnswer().contains(VERSION_STRING))
61 .map(response -> deserializeString(response.getAnswer()))
62 .filter(statusRaw -> statusRaw.getCode() == 200 && statusRaw.getResponse() == 90)
63 .map(statusRaw -> new StatusDTO(true, statusRaw.getCode(), statusRaw.getData().getSwitchValue(),
64 statusRaw.getData().getWatt(), statusRaw.getData().getAmp()))
65 .findFirst().orElse(new StatusDTO(false, 503, null, null, null));
68 private StatusRawDTO deserializeString(String response) {
69 String extractedJsonResponse = response.substring(response.lastIndexOf(VERSION_STRING) + 2);
71 return Objects.requireNonNull(gson.fromJson(extractedJsonResponse, StatusRawDTO.class));
72 } catch (JsonSyntaxException e) {
73 logger.warn("Could not parse string \"{}\" to StatusRaw", response, e);
74 return new StatusRawDTO(503, 0, new StatusDTO(false, 503, null, null, null));