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.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;
53 * The {@link GoEChargerHandler} is responsible for handling commands, which are
54 * sent to one of the channels.
56 * @author Samuel Brucksch - Initial contribution
57 * @author Reinhard Plaim - Adapt to use API version 2
60 public class GoEChargerHandler extends GoEChargerBaseHandler {
62 private final Logger logger = LoggerFactory.getLogger(GoEChargerHandler.class);
64 public GoEChargerHandler(Thing thing, HttpClient httpClient) {
65 super(thing, httpClient);
69 protected State getValue(String channelId, GoEStatusResponseBaseDTO goeResponseBase) {
70 var state = super.getValue(channelId, goeResponseBase);
71 if (state != UnDefType.UNDEF) {
75 var goeResponse = (GoEStatusResponseDTO) goeResponseBase;
77 case MAX_CURRENT_TEMPORARY:
78 if (goeResponse.maxCurrentTemporary == null) {
79 return UnDefType.UNDEF;
81 return new QuantityType<>(goeResponse.maxCurrentTemporary, Units.AMPERE);
83 if (goeResponse.pwmSignal == null) {
84 return UnDefType.UNDEF;
86 String pwmSignal = null;
87 switch (goeResponse.pwmSignal) {
89 pwmSignal = "READY_NO_CAR";
92 pwmSignal = "CHARGING";
95 pwmSignal = "WAITING_FOR_CAR";
98 pwmSignal = "CHARGING_DONE_CAR_CONNECTED";
102 return new StringType(pwmSignal);
104 if (goeResponse.errorCode == null) {
105 return UnDefType.UNDEF;
108 switch (goeResponse.errorCode) {
125 return new StringType(error);
126 case ACCESS_CONFIGURATION:
127 if (goeResponse.accessConfiguration == null) {
128 return UnDefType.UNDEF;
130 String accessConfiguration = null;
131 switch (goeResponse.accessConfiguration) {
133 accessConfiguration = "OPEN";
136 accessConfiguration = "RFID";
139 accessConfiguration = "AWATTAR";
142 accessConfiguration = "TIMER";
146 return new StringType(accessConfiguration);
148 if (goeResponse.allowCharging == null) {
149 return UnDefType.UNDEF;
151 return goeResponse.allowCharging == 1 ? OnOffType.ON : OnOffType.OFF;
153 if (goeResponse.energy == null) {
154 return UnDefType.UNDEF;
157 if (goeResponse.energy[4] > 0) { // current P1
160 if (goeResponse.energy[5] > 0) { // current P2
163 if (goeResponse.energy[6] > 0) { // current P3
166 return new DecimalType(count);
167 case TEMPERATURE_CIRCUIT_BOARD:
168 if (goeResponse.temperature == null) {
169 return UnDefType.UNDEF;
171 return new QuantityType<>(goeResponse.temperature, SIUnits.CELSIUS);
172 case SESSION_CHARGE_CONSUMPTION:
173 if (goeResponse.sessionChargeConsumption == null) {
174 return UnDefType.UNDEF;
176 return new QuantityType<>((Double) (goeResponse.sessionChargeConsumption / 360000d),
177 Units.KILOWATT_HOUR);
178 case SESSION_CHARGE_CONSUMPTION_LIMIT:
179 if (goeResponse.sessionChargeConsumptionLimit == null) {
180 return UnDefType.UNDEF;
182 return new QuantityType<>((Double) (goeResponse.sessionChargeConsumptionLimit / 10d),
183 Units.KILOWATT_HOUR);
184 case TOTAL_CONSUMPTION:
185 if (goeResponse.totalChargeConsumption == null) {
186 return UnDefType.UNDEF;
188 return new QuantityType<>((Double) (goeResponse.totalChargeConsumption / 10d), Units.KILOWATT_HOUR);
190 if (goeResponse.energy == null) {
191 return UnDefType.UNDEF;
193 // values come in as A*10, 41 means 4.1A
194 return new QuantityType<>((Double) (goeResponse.energy[4] / 10d), Units.AMPERE);
196 if (goeResponse.energy == null) {
197 return UnDefType.UNDEF;
199 return new QuantityType<>((Double) (goeResponse.energy[5] / 10d), Units.AMPERE);
201 if (goeResponse.energy == null) {
202 return UnDefType.UNDEF;
204 return new QuantityType<>((Double) (goeResponse.energy[6] / 10d), Units.AMPERE);
206 if (goeResponse.energy == null) {
207 return UnDefType.UNDEF;
209 // values come in as kW*10, 41 means 4.1kW
210 return new QuantityType<>(goeResponse.energy[7] * 100, Units.WATT);
212 if (goeResponse.energy == null) {
213 return UnDefType.UNDEF;
215 return new QuantityType<>(goeResponse.energy[8] * 100, Units.WATT);
217 if (goeResponse.energy == null) {
218 return UnDefType.UNDEF;
220 return new QuantityType<>(goeResponse.energy[9] * 100, Units.WATT);
222 if (goeResponse.energy == null) {
223 return UnDefType.UNDEF;
225 return new QuantityType<>(goeResponse.energy[0], Units.VOLT);
227 if (goeResponse.energy == null) {
228 return UnDefType.UNDEF;
230 return new QuantityType<>(goeResponse.energy[1], Units.VOLT);
232 if (goeResponse.energy == null) {
233 return UnDefType.UNDEF;
235 return new QuantityType<>(goeResponse.energy[2], Units.VOLT);
237 if (goeResponse.energy == null) {
238 return UnDefType.UNDEF;
240 return new QuantityType<>(goeResponse.energy[11] * 10, Units.WATT);
242 return UnDefType.UNDEF;
246 public void handleCommand(ChannelUID channelUID, Command command) {
247 if (command instanceof RefreshType) {
248 // we can not update single channels and refresh is triggered automatically
256 switch (channelUID.getId()) {
259 if (command instanceof DecimalType) {
260 value = String.valueOf(((DecimalType) command).intValue());
261 } else if (command instanceof QuantityType<?>) {
262 value = String.valueOf(((QuantityType<ElectricCurrent>) command).toUnit(Units.AMPERE).intValue());
265 case MAX_CURRENT_TEMPORARY:
267 if (command instanceof DecimalType) {
268 value = String.valueOf(((DecimalType) command).intValue());
269 } else if (command instanceof QuantityType<?>) {
270 value = String.valueOf(((QuantityType<ElectricCurrent>) command).toUnit(Units.AMPERE).intValue());
273 case SESSION_CHARGE_CONSUMPTION_LIMIT:
276 if (command instanceof DecimalType) {
277 value = String.valueOf(((DecimalType) command).intValue() * multiplier);
278 } else if (command instanceof QuantityType<?>) {
279 value = String.valueOf(
280 ((QuantityType<Energy>) command).toUnit(Units.KILOWATT_HOUR).intValue() * multiplier);
285 if (command instanceof OnOffType) {
286 value = command == OnOffType.ON ? "1" : "0";
289 case ACCESS_CONFIGURATION:
291 if (command instanceof StringType) {
292 switch (command.toString().toUpperCase()) {
311 if (key != null && value != null) {
312 sendData(key, value);
314 logger.warn("Could not update channel {} with key {} and value {}", channelUID.getId(), key, value);
319 public void initialize() {
323 private String getReadUrl() {
324 return GoEChargerBindingConstants.API_URL.replace("%IP%", config.ip.toString());
327 private String getWriteUrl(String key, String value) {
328 return GoEChargerBindingConstants.MQTT_URL.replace("%IP%", config.ip.toString()).replace("%KEY%", key)
329 .replace("%VALUE%", value);
332 private void sendData(String key, String value) {
333 String urlStr = getWriteUrl(key, value);
334 logger.trace("GET URL = {}", urlStr);
337 HttpMethod httpMethod = HttpMethod.GET;
338 ContentResponse contentResponse = httpClient.newRequest(urlStr).method(httpMethod)
339 .timeout(5, TimeUnit.SECONDS).send();
340 String response = contentResponse.getContentAsString();
342 logger.trace("{} Response: {}", httpMethod.toString(), response);
344 var statusCode = contentResponse.getStatus();
345 if (!(statusCode == 200 || statusCode == 204)) {
346 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
347 "@text/unsuccessful.communication-error");
348 logger.debug("Could not send data, Response {}, StatusCode: {}", response, statusCode);
350 } catch (InterruptedException ie) {
351 Thread.currentThread().interrupt();
352 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, ie.toString());
353 logger.debug("Could not send data: {}, {}", urlStr, ie.toString());
354 } catch (TimeoutException | ExecutionException | JsonSyntaxException e) {
355 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, e.toString());
356 logger.debug("Could not send data: {}, {}", urlStr, e.toString());
361 * Request new data from Go-eCharger
363 * @return the Go-eCharger object mapping the JSON response or null in case of
365 * @throws ExecutionException
366 * @throws TimeoutException
367 * @throws InterruptedException
371 protected GoEStatusResponseBaseDTO getGoEData()
372 throws InterruptedException, TimeoutException, ExecutionException, JsonSyntaxException {
373 String urlStr = getReadUrl();
374 logger.trace("GET URL = {}", urlStr);
376 ContentResponse contentResponse = httpClient.newRequest(urlStr).method(HttpMethod.GET)
377 .timeout(5, TimeUnit.SECONDS).send();
379 String response = contentResponse.getContentAsString();
380 logger.trace("GET Response: {}", response);
382 if (config.apiVersion == 1) {
383 return gson.fromJson(response, GoEStatusResponseDTO.class);
385 return gson.fromJson(response, GoEStatusResponseV2DTO.class);
389 protected void updateChannelsAndStatus(@Nullable GoEStatusResponseBaseDTO goeResponse, @Nullable String message) {
390 if (goeResponse == null) {
391 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.OFFLINE.COMMUNICATION_ERROR, message);
392 allChannels.forEach(channel -> updateState(channel, UnDefType.UNDEF));
394 updateStatus(ThingStatus.ONLINE, ThingStatusDetail.NONE);
395 allChannels.forEach(channel -> updateState(channel, getValue(channel, (GoEStatusResponseDTO) goeResponse)));