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.sonnen.internal.communication;
15 import java.io.IOException;
17 import org.eclipse.jdt.annotation.NonNullByDefault;
18 import org.eclipse.jdt.annotation.Nullable;
19 import org.openhab.binding.sonnen.internal.SonnenConfiguration;
20 import org.openhab.core.io.net.http.HttpUtil;
21 import org.slf4j.Logger;
22 import org.slf4j.LoggerFactory;
24 import com.google.gson.Gson;
25 import com.google.gson.JsonSyntaxException;
28 * This class handles the JSON communication with the sonnen battery
30 * @author Christian Feininger - Initial contribution
34 public class SonnenJSONCommunication {
36 private final Logger logger = LoggerFactory.getLogger(SonnenJSONCommunication.class);
37 private SonnenConfiguration config;
40 private @Nullable SonnenJsonDataDTO batteryData;
42 public SonnenJSONCommunication() {
44 config = new SonnenConfiguration();
48 * Refreshes the battery connection.
50 * @return an empty string if no error occurred, the error message otherwise.
52 public String refreshBatteryConnection() {
54 String urlStr = "http://" + config.hostIP + "/api/v1/status";
57 String response = HttpUtil.executeUrl("GET", urlStr, 10000);
58 logger.debug("BatteryData = {}", response);
59 if (response == null) {
60 throw new IOException("HttpUtil.executeUrl returned null");
62 batteryData = gson.fromJson(response, SonnenJsonDataDTO.class);
63 } catch (IOException | JsonSyntaxException e) {
64 logger.debug("Error processiong Get request {}: {}", urlStr, e.getMessage());
65 result = "Cannot find service on given IP " + config.hostIP + ". Please verify the IP address!";
72 * Set the config for service to communicate
76 public void setConfig(SonnenConfiguration config2) {
77 this.config = config2;
81 * Returns the actual stored Battery Data
83 * @return JSON Data from the Battery or null if request failed
85 public @Nullable SonnenJsonDataDTO getBatteryData() {
86 return this.batteryData;