]> git.basschouten.com Git - openhab-addons.git/blob
baa58e6907a1e3c2c257a187543ba6ea1862f7c6
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2023 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.sonnen.internal.communication;
14
15 import java.io.IOException;
16 import java.util.Properties;
17
18 import org.eclipse.jdt.annotation.NonNullByDefault;
19 import org.eclipse.jdt.annotation.Nullable;
20 import org.openhab.binding.sonnen.internal.SonnenConfiguration;
21 import org.openhab.core.io.net.http.HttpUtil;
22 import org.slf4j.Logger;
23 import org.slf4j.LoggerFactory;
24
25 import com.google.gson.Gson;
26 import com.google.gson.JsonSyntaxException;
27
28 /**
29  * This class handles the JSON communication with the sonnen battery
30  *
31  * @author Christian Feininger - Initial contribution
32  *
33  */
34 @NonNullByDefault
35 public class SonnenJSONCommunication {
36
37     private final Logger logger = LoggerFactory.getLogger(SonnenJSONCommunication.class);
38     private SonnenConfiguration config;
39
40     private Gson gson;
41     private @Nullable SonnenJsonDataDTO batteryData;
42     private SonnenJsonPowerMeterDataDTO @Nullable [] powerMeterData;
43
44     public SonnenJSONCommunication() {
45         gson = new Gson();
46         config = new SonnenConfiguration();
47     }
48
49     /**
50      * Refreshes the battery connection with the new API Call V2.
51      *
52      * @return an empty string if no error occurred, the error message otherwise.
53      */
54     public String refreshBatteryConnectionAPICALLV2(boolean powerMeter) {
55         String result = "";
56         String urlStr = "http://" + config.hostIP + "/api/v2/status";
57         Properties httpHeader = new Properties();
58         httpHeader = createHeader(config.authToken);
59         try {
60             String response = HttpUtil.executeUrl("GET", urlStr, httpHeader, null, "application/json", 10000);
61             logger.debug("BatteryData = {}", response);
62             if (response == null) {
63                 throw new IOException("HttpUtil.executeUrl returned null");
64             }
65             batteryData = gson.fromJson(response, SonnenJsonDataDTO.class);
66
67             if (powerMeter) {
68                 response = HttpUtil.executeUrl("GET", "http://" + config.hostIP + "/api/v2/powermeter", httpHeader,
69                         null, "application/json", 10000);
70                 logger.debug("PowerMeterData = {}", response);
71                 if (response == null) {
72                     throw new IOException("HttpUtil.executeUrl returned null");
73                 }
74
75                 powerMeterData = gson.fromJson(response, SonnenJsonPowerMeterDataDTO[].class);
76             }
77         } catch (IOException | JsonSyntaxException e) {
78             logger.debug("Error processiong Get request {}:  {}", urlStr, e.getMessage());
79             String message = e.getMessage();
80             if (message != null && message.contains("WWW-Authenticate header")) {
81                 result = "Given token: " + config.authToken + " is not valid.";
82             } else {
83                 result = "Cannot find service on given IP " + config.hostIP + ". Please verify the IP address!";
84                 logger.debug("Error in establishing connection: {}", e.getMessage());
85             }
86             batteryData = null;
87             powerMeterData = new SonnenJsonPowerMeterDataDTO[] {};
88         }
89         return result;
90     }
91
92     /**
93      * Refreshes the battery connection with the Old API Call.
94      *
95      * @return an empty string if no error occurred, the error message otherwise.
96      */
97     public String refreshBatteryConnectionAPICALLV1() {
98         String result = "";
99         String urlStr = "http://" + config.hostIP + "/api/v1/status";
100         try {
101             String response = HttpUtil.executeUrl("GET", urlStr, 10000);
102             logger.debug("BatteryData = {}", response);
103             if (response == null) {
104                 throw new IOException("HttpUtil.executeUrl returned null");
105             }
106             batteryData = gson.fromJson(response, SonnenJsonDataDTO.class);
107         } catch (IOException | JsonSyntaxException e) {
108             logger.debug("Error processiong Get request {}:  {}", urlStr, e.getMessage());
109             result = "Cannot find service on given IP " + config.hostIP + ". Please verify the IP address!";
110             batteryData = null;
111         }
112         return result;
113     }
114
115     /**
116      * Set the config for service to communicate
117      *
118      * @param config2
119      */
120     public void setConfig(SonnenConfiguration config2) {
121         this.config = config2;
122     }
123
124     /**
125      * Returns the actual stored Battery Data
126      *
127      * @return JSON Data from the Battery or null if request failed
128      */
129     public @Nullable SonnenJsonDataDTO getBatteryData() {
130         return this.batteryData;
131     }
132
133     /**
134      * Returns the actual stored Power Meter Data Array
135      *
136      * @return JSON Data from the Power Meter or null if request failed
137      */
138     public SonnenJsonPowerMeterDataDTO @Nullable [] getPowerMeterData() {
139         return this.powerMeterData;
140     }
141
142     /**
143      * Creates the header for the Get Request
144      *
145      * @return The created Header Properties
146      */
147     private Properties createHeader(String authToken) {
148         Properties httpHeader = new Properties();
149         httpHeader.setProperty("Host", config.hostIP);
150         httpHeader.setProperty("Accept", "*/*");
151         httpHeader.setProperty("Proxy-Connection", "keep-alive");
152         httpHeader.setProperty("Auth-Token", authToken);
153         httpHeader.setProperty("Accept-Encoding", "gzip;q=1.0, compress;q=0.5");
154         return httpHeader;
155     }
156 }