2 * Copyright (c) 2010-2022 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.goecharger.internal.handler;
15 import static org.openhab.binding.goecharger.internal.GoEChargerBindingConstants.*;
17 import java.util.concurrent.ExecutionException;
18 import java.util.concurrent.TimeUnit;
19 import java.util.concurrent.TimeoutException;
21 import javax.measure.quantity.ElectricCurrent;
22 import javax.measure.quantity.Energy;
24 import org.eclipse.jdt.annotation.NonNullByDefault;
25 import org.eclipse.jdt.annotation.Nullable;
26 import org.eclipse.jetty.client.HttpClient;
27 import org.eclipse.jetty.client.api.ContentResponse;
28 import org.eclipse.jetty.http.HttpMethod;
29 import org.openhab.binding.goecharger.internal.GoEChargerBindingConstants;
30 import org.openhab.binding.goecharger.internal.api.GoEStatusResponseBaseDTO;
31 import org.openhab.binding.goecharger.internal.api.GoEStatusResponseDTO;
32 import org.openhab.binding.goecharger.internal.api.GoEStatusResponseV2DTO;
33 import org.openhab.core.library.types.DecimalType;
34 import org.openhab.core.library.types.OnOffType;
35 import org.openhab.core.library.types.QuantityType;
36 import org.openhab.core.library.types.StringType;
37 import org.openhab.core.library.unit.SIUnits;
38 import org.openhab.core.library.unit.Units;
39 import org.openhab.core.thing.ChannelUID;
40 import org.openhab.core.thing.Thing;
41 import org.openhab.core.thing.ThingStatus;
42 import org.openhab.core.thing.ThingStatusDetail;
43 import org.openhab.core.types.Command;
44 import org.openhab.core.types.RefreshType;
45 import org.openhab.core.types.State;
46 import org.openhab.core.types.UnDefType;
47 import org.slf4j.Logger;
48 import org.slf4j.LoggerFactory;
50 import com.google.gson.JsonSyntaxException;
51 import com.google.gson.annotations.SerializedName;
54 * The {@link GoEChargerV2Handler} is responsible for handling commands, which are
55 * sent to one of the channels.
57 * @author Samuel Brucksch - Initial contribution
58 * @author Reinhard Plaim - Adapt to use API version 2
61 public class GoEChargerV2Handler extends GoEChargerBaseHandler {
63 private final Logger logger = LoggerFactory.getLogger(GoEChargerV2Handler.class);
65 private String filter = "";
67 public GoEChargerV2Handler(Thing thing, HttpClient httpClient) {
68 super(thing, httpClient);
72 protected State getValue(String channelId, GoEStatusResponseBaseDTO goeResponseBase) {
73 var state = super.getValue(channelId, goeResponseBase);
74 if (state != UnDefType.UNDEF) {
78 var goeResponse = (GoEStatusResponseV2DTO) goeResponseBase;
81 if (goeResponse.phases == null) {
82 return UnDefType.UNDEF;
85 if (goeResponse.phases == 2) {
88 return new DecimalType(phases);
90 if (goeResponse.pwmSignal == null) {
91 return UnDefType.UNDEF;
93 String pwmSignal = null;
94 switch (goeResponse.pwmSignal) {
96 pwmSignal = "UNKNOWN/ERROR";
101 pwmSignal = "CHARGING";
104 pwmSignal = "WAITING_FOR_CAR";
107 pwmSignal = "COMPLETE";
113 return new StringType(pwmSignal);
115 if (goeResponse.errorCode == null) {
116 return UnDefType.UNDEF;
119 switch (goeResponse.errorCode) {
121 error = "UNKNOWN/ERROR";
129 error = "WAITING_FOR_CAR";
138 return new StringType(error);
140 return goeResponse.allowCharging == true ? OnOffType.ON : OnOffType.OFF;
141 case TEMPERATURE_TYPE2_PORT:
142 if (goeResponse.temperatures == null) {
143 return UnDefType.UNDEF;
145 return new QuantityType<>(goeResponse.temperatures[0], SIUnits.CELSIUS);
146 case TEMPERATURE_CIRCUIT_BOARD:
147 if (goeResponse.temperatures == null) {
148 return UnDefType.UNDEF;
150 return new QuantityType<>(goeResponse.temperatures[1], SIUnits.CELSIUS);
151 case SESSION_CHARGE_CONSUMPTION:
152 if (goeResponse.sessionChargeConsumption == null) {
153 return UnDefType.UNDEF;
155 return new QuantityType<>(goeResponse.sessionChargeConsumption / 1000d, Units.KILOWATT_HOUR);
156 case SESSION_CHARGE_CONSUMPTION_LIMIT:
157 if (goeResponse.sessionChargeConsumptionLimit == null) {
158 return UnDefType.UNDEF;
160 return new QuantityType<>(goeResponse.sessionChargeConsumptionLimit / 1000d, Units.KILOWATT_HOUR);
161 case TOTAL_CONSUMPTION:
162 if (goeResponse.totalChargeConsumption == null) {
163 return UnDefType.UNDEF;
165 return new QuantityType<>((Double) (goeResponse.totalChargeConsumption / 1000d), Units.KILOWATT_HOUR);
167 if (goeResponse.energy == null) {
168 return UnDefType.UNDEF;
170 return new QuantityType<>(goeResponse.energy[0], Units.VOLT);
172 if (goeResponse.energy == null) {
173 return UnDefType.UNDEF;
175 return new QuantityType<>(goeResponse.energy[1], Units.VOLT);
177 if (goeResponse.energy == null) {
178 return UnDefType.UNDEF;
180 return new QuantityType<>(goeResponse.energy[2], Units.VOLT);
182 if (goeResponse.energy == null) {
183 return UnDefType.UNDEF;
185 return new QuantityType<>(goeResponse.energy[4], Units.AMPERE);
187 if (goeResponse.energy == null) {
188 return UnDefType.UNDEF;
190 return new QuantityType<>(goeResponse.energy[5], Units.AMPERE);
192 if (goeResponse.energy == null) {
193 return UnDefType.UNDEF;
195 return new QuantityType<>(goeResponse.energy[6], Units.AMPERE);
197 if (goeResponse.energy == null) {
198 return UnDefType.UNDEF;
200 return new QuantityType<>(goeResponse.energy[7], Units.WATT);
202 if (goeResponse.energy == null) {
203 return UnDefType.UNDEF;
205 return new QuantityType<>(goeResponse.energy[8], Units.WATT);
207 if (goeResponse.energy == null) {
208 return UnDefType.UNDEF;
210 return new QuantityType<>(goeResponse.energy[9], Units.WATT);
212 if (goeResponse.energy == null) {
213 return UnDefType.UNDEF;
215 return new QuantityType<>(goeResponse.energy[11], Units.WATT);
217 if (goeResponse.forceState == null) {
218 return UnDefType.UNDEF;
220 return new DecimalType(goeResponse.forceState.toString());
222 return UnDefType.UNDEF;
226 public void handleCommand(ChannelUID channelUID, Command command) {
227 if (command instanceof RefreshType) {
228 // we can not update single channels and refresh is triggered automatically
236 switch (channelUID.getId()) {
239 if (command instanceof DecimalType) {
240 value = String.valueOf(((DecimalType) command).intValue());
241 } else if (command instanceof QuantityType<?>) {
242 value = String.valueOf(((QuantityType<ElectricCurrent>) command).toUnit(Units.AMPERE).intValue());
245 case SESSION_CHARGE_CONSUMPTION_LIMIT:
247 var multiplier = 1000;
248 if (command instanceof DecimalType) {
249 value = String.valueOf(((DecimalType) command).intValue() * multiplier);
250 } else if (command instanceof QuantityType<?>) {
251 value = String.valueOf(
252 ((QuantityType<Energy>) command).toUnit(Units.KILOWATT_HOUR).intValue() * multiplier);
257 if (command instanceof DecimalType) {
259 var help = (DecimalType) command;
260 if (help.intValue() == 3) {
261 // set value 2 for 3 phases
264 value = String.valueOf(phases);
269 if (command instanceof DecimalType) {
270 value = String.valueOf(((DecimalType) command).intValue());
274 if (key != null && value != null) {
275 sendData(key, value);
277 logger.warn("Could not update channel {} with key {} and value {}", channelUID.getId(), key, value);
282 public void initialize() {
283 // only read needed parameters
285 var declaredFields = GoEStatusResponseV2DTO.class.getDeclaredFields();
286 var declaredFieldsBase = GoEStatusResponseV2DTO.class.getSuperclass().getDeclaredFields();
288 for (var field : declaredFields) {
289 filter += field.getAnnotation(SerializedName.class).value() + ",";
291 for (var field : declaredFieldsBase) {
292 filter += field.getAnnotation(SerializedName.class).value() + ",";
294 filter = filter.substring(0, filter.length() - 1);
299 private String getReadUrl() {
300 return GoEChargerBindingConstants.API_URL_V2.replace("%IP%", config.ip.toString()) + filter;
303 private String getWriteUrl(String key, String value) {
304 return GoEChargerBindingConstants.SET_URL_V2.replace("%IP%", config.ip.toString()).replace("%KEY%", key)
305 .replace("%VALUE%", value);
308 private void sendData(String key, String value) {
309 String urlStr = getWriteUrl(key, value);
310 logger.trace("POST URL = {}", urlStr);
313 HttpMethod httpMethod = HttpMethod.GET;
314 ContentResponse contentResponse = httpClient.newRequest(urlStr).method(httpMethod)
315 .timeout(5, TimeUnit.SECONDS).send();
316 String response = contentResponse.getContentAsString();
318 logger.trace("{} Response: {}", httpMethod.toString(), response);
320 var statusCode = contentResponse.getStatus();
321 if (!(statusCode == 200 || statusCode == 204)) {
322 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
323 "@text/unsuccessful.communication-error");
324 logger.debug("Could not send data, Response {}, StatusCode: {}", response, statusCode);
326 } catch (InterruptedException ie) {
327 Thread.currentThread().interrupt();
328 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, ie.toString());
329 logger.debug("Could not send data: {}, {}", urlStr, ie.toString());
330 } catch (TimeoutException | ExecutionException | JsonSyntaxException e) {
331 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, e.toString());
332 logger.debug("Could not send data: {}, {}", urlStr, e.toString());
337 * Request new data from Go-eCharger
339 * @return the Go-eCharger object mapping the JSON response or null in case of
341 * @throws ExecutionException
342 * @throws TimeoutException
343 * @throws InterruptedException
347 protected GoEStatusResponseBaseDTO getGoEData()
348 throws InterruptedException, TimeoutException, ExecutionException, JsonSyntaxException {
349 String urlStr = getReadUrl();
350 logger.trace("GET URL = {}", urlStr);
352 ContentResponse contentResponse = httpClient.newRequest(urlStr).method(HttpMethod.GET)
353 .timeout(5, TimeUnit.SECONDS).send();
355 String response = contentResponse.getContentAsString();
356 logger.trace("GET Response: {}", response);
358 if (config.apiVersion == 1) {
359 return gson.fromJson(response, GoEStatusResponseDTO.class);
361 return gson.fromJson(response, GoEStatusResponseV2DTO.class);
364 protected void updateChannelsAndStatus(@Nullable GoEStatusResponseBaseDTO goeResponse, @Nullable String message) {
365 if (goeResponse == null) {
366 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.OFFLINE.COMMUNICATION_ERROR, message);
367 allChannels.forEach(channel -> updateState(channel, UnDefType.UNDEF));
369 updateStatus(ThingStatus.ONLINE);
371 .forEach(channel -> updateState(channel, getValue(channel, (GoEStatusResponseV2DTO) goeResponse)));