]> git.basschouten.com Git - openhab-addons.git/blob
439103bf086e1cb7b832bd03fe9fc37ab344d10d
[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.volvooncall.internal.handler;
14
15 import static org.openhab.binding.volvooncall.internal.VolvoOnCallBindingConstants.*;
16 import static org.openhab.core.library.unit.MetricPrefix.KILO;
17 import static org.openhab.core.library.unit.SIUnits.*;
18 import static org.openhab.core.library.unit.Units.*;
19
20 import java.time.ZonedDateTime;
21 import java.util.Collection;
22 import java.util.Collections;
23 import java.util.HashMap;
24 import java.util.List;
25 import java.util.Map;
26 import java.util.Stack;
27 import java.util.concurrent.ScheduledFuture;
28 import java.util.concurrent.TimeUnit;
29 import java.util.stream.Collectors;
30
31 import org.eclipse.jdt.annotation.NonNullByDefault;
32 import org.eclipse.jdt.annotation.Nullable;
33 import org.openhab.binding.volvooncall.internal.VolvoOnCallException;
34 import org.openhab.binding.volvooncall.internal.action.VolvoOnCallActions;
35 import org.openhab.binding.volvooncall.internal.api.ActionResultController;
36 import org.openhab.binding.volvooncall.internal.api.VocHttpApi;
37 import org.openhab.binding.volvooncall.internal.config.VehicleConfiguration;
38 import org.openhab.binding.volvooncall.internal.dto.Attributes;
39 import org.openhab.binding.volvooncall.internal.dto.DoorsStatus;
40 import org.openhab.binding.volvooncall.internal.dto.Heater;
41 import org.openhab.binding.volvooncall.internal.dto.HvBattery;
42 import org.openhab.binding.volvooncall.internal.dto.Position;
43 import org.openhab.binding.volvooncall.internal.dto.PostResponse;
44 import org.openhab.binding.volvooncall.internal.dto.Status;
45 import org.openhab.binding.volvooncall.internal.dto.Status.FluidLevel;
46 import org.openhab.binding.volvooncall.internal.dto.Trip;
47 import org.openhab.binding.volvooncall.internal.dto.TripDetail;
48 import org.openhab.binding.volvooncall.internal.dto.Trips;
49 import org.openhab.binding.volvooncall.internal.dto.TyrePressure;
50 import org.openhab.binding.volvooncall.internal.dto.TyrePressure.PressureLevel;
51 import org.openhab.binding.volvooncall.internal.dto.Vehicles;
52 import org.openhab.binding.volvooncall.internal.dto.WindowsStatus;
53 import org.openhab.binding.volvooncall.internal.wrapper.VehiclePositionWrapper;
54 import org.openhab.core.library.types.DateTimeType;
55 import org.openhab.core.library.types.DecimalType;
56 import org.openhab.core.library.types.OnOffType;
57 import org.openhab.core.library.types.QuantityType;
58 import org.openhab.core.library.types.StringType;
59 import org.openhab.core.thing.Bridge;
60 import org.openhab.core.thing.Channel;
61 import org.openhab.core.thing.ChannelUID;
62 import org.openhab.core.thing.Thing;
63 import org.openhab.core.thing.ThingStatus;
64 import org.openhab.core.thing.ThingStatusDetail;
65 import org.openhab.core.thing.ThingStatusInfo;
66 import org.openhab.core.thing.binding.BaseThingHandler;
67 import org.openhab.core.thing.binding.ThingHandler;
68 import org.openhab.core.thing.binding.ThingHandlerService;
69 import org.openhab.core.types.Command;
70 import org.openhab.core.types.RefreshType;
71 import org.openhab.core.types.State;
72 import org.openhab.core.types.UnDefType;
73 import org.slf4j.Logger;
74 import org.slf4j.LoggerFactory;
75
76 /**
77  * The {@link VehicleHandler} is responsible for handling commands, which are sent
78  * to one of the channels.
79  *
80  * @author GaĆ«l L'hopital - Initial contribution
81  */
82 @NonNullByDefault
83 public class VehicleHandler extends BaseThingHandler {
84     private final Logger logger = LoggerFactory.getLogger(VehicleHandler.class);
85     private final Map<String, String> activeOptions = new HashMap<>();
86     private @Nullable ScheduledFuture<?> refreshJob;
87     private final List<ScheduledFuture<?>> pendingActions = new Stack<>();
88
89     private Vehicles vehicle = new Vehicles();
90     private VehiclePositionWrapper vehiclePosition = new VehiclePositionWrapper(new Position());
91     private Status vehicleStatus = new Status();
92     private @NonNullByDefault({}) VehicleConfiguration configuration;
93     private @NonNullByDefault({}) VolvoOnCallBridgeHandler bridgeHandler;
94     private long lastTripId;
95
96     public VehicleHandler(Thing thing, VehicleStateDescriptionProvider stateDescriptionProvider) {
97         super(thing);
98     }
99
100     @Override
101     public void initialize() {
102         logger.trace("Initializing the Volvo On Call handler for {}", getThing().getUID());
103
104         Bridge bridge = getBridge();
105         initializeBridge(bridge == null ? null : bridge.getHandler(), bridge == null ? null : bridge.getStatus());
106     }
107
108     @Override
109     public void bridgeStatusChanged(ThingStatusInfo bridgeStatusInfo) {
110         logger.debug("bridgeStatusChanged {} for thing {}", bridgeStatusInfo, getThing().getUID());
111
112         Bridge bridge = getBridge();
113         initializeBridge(bridge == null ? null : bridge.getHandler(), bridgeStatusInfo.getStatus());
114     }
115
116     private void initializeBridge(@Nullable ThingHandler thingHandler, @Nullable ThingStatus bridgeStatus) {
117         logger.debug("initializeBridge {} for thing {}", bridgeStatus, getThing().getUID());
118
119         if (thingHandler != null && bridgeStatus != null) {
120             bridgeHandler = (VolvoOnCallBridgeHandler) thingHandler;
121             if (bridgeStatus == ThingStatus.ONLINE) {
122                 configuration = getConfigAs(VehicleConfiguration.class);
123                 VocHttpApi api = bridgeHandler.getApi();
124                 if (api != null) {
125                     try {
126                         vehicle = api.getURL("vehicles/" + configuration.vin, Vehicles.class);
127                         if (thing.getProperties().isEmpty()) {
128                             Map<String, String> properties = discoverAttributes(api);
129                             updateProperties(properties);
130                         }
131
132                         activeOptions.putAll(
133                                 thing.getProperties().entrySet().stream().filter(p -> "true".equals(p.getValue()))
134                                         .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)));
135
136                         String lastTripIdString = thing.getProperties().get(LAST_TRIP_ID);
137                         if (lastTripIdString != null) {
138                             lastTripId = Long.parseLong(lastTripIdString);
139                         }
140
141                         updateStatus(ThingStatus.ONLINE);
142                         startAutomaticRefresh(configuration.refresh, api);
143                     } catch (VolvoOnCallException e) {
144                         updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.HANDLER_INITIALIZING_ERROR, e.getMessage());
145                     }
146
147                 }
148             } else {
149                 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.BRIDGE_OFFLINE);
150             }
151         } else {
152             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.BRIDGE_UNINITIALIZED);
153         }
154     }
155
156     private Map<String, String> discoverAttributes(VocHttpApi service) throws VolvoOnCallException {
157         Attributes attributes = service.getURL(vehicle.attributesURL, Attributes.class);
158
159         Map<String, String> properties = new HashMap<>();
160         properties.put(CAR_LOCATOR, attributes.carLocatorSupported.toString());
161         properties.put(HONK_AND_OR_BLINK, Boolean.toString(attributes.honkAndBlinkSupported
162                 && attributes.honkAndBlinkVersionsSupported.contains(HONK_AND_OR_BLINK)));
163         properties.put(HONK_BLINK, Boolean.toString(
164                 attributes.honkAndBlinkSupported && attributes.honkAndBlinkVersionsSupported.contains(HONK_BLINK)));
165         properties.put(REMOTE_HEATER, attributes.remoteHeaterSupported.toString());
166         properties.put(UNLOCK, attributes.unlockSupported.toString());
167         properties.put(LOCK, attributes.lockSupported.toString());
168         properties.put(JOURNAL_LOG, Boolean.toString(attributes.journalLogSupported && attributes.journalLogEnabled));
169         properties.put(PRECLIMATIZATION, attributes.preclimatizationSupported.toString());
170         properties.put(ENGINE_START, attributes.engineStartSupported.toString());
171         properties.put(UNLOCK_TIME, attributes.unlockTimeFrame.toString());
172
173         return properties;
174     }
175
176     /**
177      * Start the job refreshing the vehicle data
178      *
179      * @param refresh : refresh frequency in minutes
180      * @param service
181      */
182     private void startAutomaticRefresh(int refresh, VocHttpApi service) {
183         ScheduledFuture<?> refreshJob = this.refreshJob;
184         if (refreshJob == null || refreshJob.isCancelled()) {
185             this.refreshJob = scheduler.scheduleWithFixedDelay(() -> queryApiAndUpdateChannels(service), 1, refresh,
186                     TimeUnit.MINUTES);
187         }
188     }
189
190     private void queryApiAndUpdateChannels(VocHttpApi service) {
191         try {
192             Status newVehicleStatus = service.getURL(vehicle.statusURL, Status.class);
193             vehiclePosition = new VehiclePositionWrapper(service.getURL(Position.class, configuration.vin));
194             // Update all channels from the updated data
195             getThing().getChannels().stream().map(Channel::getUID)
196                     .filter(channelUID -> isLinked(channelUID) && !LAST_TRIP_GROUP.equals(channelUID.getGroupId()))
197                     .forEach(channelUID -> {
198                         String groupID = channelUID.getGroupId();
199                         if (groupID != null) {
200                             State state = getValue(groupID, channelUID.getIdWithoutGroup(), newVehicleStatus,
201                                     vehiclePosition);
202                             updateState(channelUID, state);
203                         }
204                     });
205             if (newVehicleStatus.odometer != vehicleStatus.odometer) {
206                 triggerChannel(GROUP_OTHER + "#" + CAR_EVENT, EVENT_CAR_MOVED);
207                 // We will update trips only if car position has changed to save server queries
208                 updateTrips(service);
209             }
210             if (!vehicleStatus.getEngineRunning().equals(newVehicleStatus.getEngineRunning())
211                     && newVehicleStatus.getEngineRunning().get() == OnOffType.ON) {
212                 triggerChannel(GROUP_OTHER + "#" + CAR_EVENT, EVENT_CAR_STARTED);
213             }
214             vehicleStatus = newVehicleStatus;
215         } catch (VolvoOnCallException e) {
216             logger.warn("Exception occurred during execution: {}", e.getMessage(), e);
217             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, e.getMessage());
218             freeRefreshJob();
219             startAutomaticRefresh(configuration.refresh, service);
220         }
221     }
222
223     private void freeRefreshJob() {
224         ScheduledFuture<?> refreshJob = this.refreshJob;
225         if (refreshJob != null) {
226             refreshJob.cancel(true);
227             this.refreshJob = null;
228         }
229         pendingActions.stream().filter(f -> !f.isCancelled()).forEach(f -> f.cancel(true));
230     }
231
232     @Override
233     public void dispose() {
234         freeRefreshJob();
235         super.dispose();
236     }
237
238     private void updateTrips(VocHttpApi service) throws VolvoOnCallException {
239         // This seems to rewind 100 days by default, did not find any way to filter it
240         Trips carTrips = service.getURL(Trips.class, configuration.vin);
241         List<Trip> newTrips = carTrips.trips.stream().filter(trip -> trip.id >= lastTripId)
242                 .collect(Collectors.toList());
243         Collections.reverse(newTrips);
244
245         logger.debug("Trips discovered : {}", newTrips.size());
246
247         if (!newTrips.isEmpty()) {
248             Long newTripId = newTrips.get(newTrips.size() - 1).id;
249             if (newTripId > lastTripId) {
250                 updateProperty(LAST_TRIP_ID, newTripId.toString());
251                 triggerChannel(GROUP_OTHER + "#" + CAR_EVENT, EVENT_CAR_STOPPED);
252                 lastTripId = newTripId;
253             }
254
255             newTrips.stream().map(t -> t.tripDetails.get(0)).forEach(catchUpTrip -> {
256                 logger.debug("Trip found {}", catchUpTrip.getStartTime());
257                 getThing().getChannels().stream().map(Channel::getUID)
258                         .filter(channelUID -> isLinked(channelUID) && LAST_TRIP_GROUP.equals(channelUID.getGroupId()))
259                         .forEach(channelUID -> {
260                             State state = getTripValue(channelUID.getIdWithoutGroup(), catchUpTrip);
261                             updateState(channelUID, state);
262                         });
263             });
264         }
265     }
266
267     @Override
268     public void handleCommand(ChannelUID channelUID, Command command) {
269         String channelID = channelUID.getIdWithoutGroup();
270         if (command instanceof RefreshType) {
271             VocHttpApi api = bridgeHandler.getApi();
272             if (api != null) {
273                 queryApiAndUpdateChannels(api);
274             }
275         } else if (command instanceof OnOffType onOffCommand) {
276             if (ENGINE_START.equals(channelID) && onOffCommand == OnOffType.ON) {
277                 actionStart(5);
278             } else if (REMOTE_HEATER.equals(channelID) || PRECLIMATIZATION.equals(channelID)) {
279                 actionHeater(channelID, onOffCommand == OnOffType.ON);
280             } else if (CAR_LOCKED.equals(channelID)) {
281                 actionOpenClose((onOffCommand == OnOffType.ON) ? LOCK : UNLOCK, onOffCommand);
282             }
283         }
284     }
285
286     private State getTripValue(String channelId, TripDetail tripDetails) {
287         switch (channelId) {
288             case TRIP_CONSUMPTION:
289                 return tripDetails.getFuelConsumption()
290                         .map(value -> (State) new QuantityType<>(value.floatValue() / 100, LITRE))
291                         .orElse(UnDefType.UNDEF);
292             case TRIP_DISTANCE:
293                 return new QuantityType<>((double) tripDetails.distance / 1000, KILO(METRE));
294             case TRIP_START_TIME:
295                 return tripDetails.getStartTime();
296             case TRIP_END_TIME:
297                 return tripDetails.getEndTime();
298             case TRIP_DURATION:
299                 return tripDetails.getDurationInMinutes().map(value -> (State) new QuantityType<>(value, MINUTE))
300                         .orElse(UnDefType.UNDEF);
301             case TRIP_START_ODOMETER:
302                 return new QuantityType<>((double) tripDetails.startOdometer / 1000, KILO(METRE));
303             case TRIP_STOP_ODOMETER:
304                 return new QuantityType<>((double) tripDetails.endOdometer / 1000, KILO(METRE));
305             case TRIP_START_POSITION:
306                 return tripDetails.getStartPosition();
307             case TRIP_END_POSITION:
308                 return tripDetails.getEndPosition();
309         }
310         return UnDefType.NULL;
311     }
312
313     private State getDoorsValue(String channelId, DoorsStatus doors) {
314         switch (channelId) {
315             case TAILGATE:
316                 return doors.tailgateOpen;
317             case REAR_RIGHT:
318                 return doors.rearRightDoorOpen;
319             case REAR_LEFT:
320                 return doors.rearLeftDoorOpen;
321             case FRONT_RIGHT:
322                 return doors.frontRightDoorOpen;
323             case FRONT_LEFT:
324                 return doors.frontLeftDoorOpen;
325             case HOOD:
326                 return doors.hoodOpen;
327         }
328         return UnDefType.NULL;
329     }
330
331     private State getWindowsValue(String channelId, WindowsStatus windows) {
332         switch (channelId) {
333             case REAR_RIGHT_WND:
334                 return windows.rearRightWindowOpen;
335             case REAR_LEFT_WND:
336                 return windows.rearLeftWindowOpen;
337             case FRONT_RIGHT_WND:
338                 return windows.frontRightWindowOpen;
339             case FRONT_LEFT_WND:
340                 return windows.frontLeftWindowOpen;
341         }
342         return UnDefType.NULL;
343     }
344
345     private State pressureLevelToState(PressureLevel level) {
346         return level != PressureLevel.UNKNOWN ? new DecimalType(level.ordinal()) : UnDefType.UNDEF;
347     }
348
349     private State getTyresValue(String channelId, TyrePressure tyrePressure) {
350         switch (channelId) {
351             case REAR_RIGHT_TYRE:
352                 return pressureLevelToState(tyrePressure.rearRightTyrePressure);
353             case REAR_LEFT_TYRE:
354                 return pressureLevelToState(tyrePressure.rearLeftTyrePressure);
355             case FRONT_RIGHT_TYRE:
356                 return pressureLevelToState(tyrePressure.frontRightTyrePressure);
357             case FRONT_LEFT_TYRE:
358                 return pressureLevelToState(tyrePressure.frontLeftTyrePressure);
359         }
360         return UnDefType.NULL;
361     }
362
363     private State getHeaterValue(String channelId, Heater heater) {
364         switch (channelId) {
365             case REMOTE_HEATER:
366             case PRECLIMATIZATION:
367                 return heater.getStatus();
368         }
369         return UnDefType.NULL;
370     }
371
372     private State getBatteryValue(String channelId, HvBattery hvBattery) {
373         switch (channelId) {
374             case BATTERY_LEVEL:
375                 /*
376                  * If the car is charging the battery level can be reported as 100% by the API regardless of actual
377                  * charge level, but isn't always. So, if we see that the car is Charging, ChargingPaused, or
378                  * ChargingInterrupted and the reported battery level is 100%, then instead produce UNDEF.
379                  *
380                  * If we see FullyCharged, then we can rely on the value being 100% anyway.
381                  */
382                 if (hvBattery.hvBatteryChargeStatusDerived != null
383                         && hvBattery.hvBatteryChargeStatusDerived.toString().startsWith("CablePluggedInCar_Charging")
384                         && hvBattery.hvBatteryLevel != UNDEFINED && hvBattery.hvBatteryLevel == 100) {
385                     return UnDefType.UNDEF;
386                 } else {
387                     return hvBattery.hvBatteryLevel != UNDEFINED ? new QuantityType<>(hvBattery.hvBatteryLevel, PERCENT)
388                             : UnDefType.UNDEF;
389                 }
390             case BATTERY_LEVEL_RAW:
391                 return hvBattery.hvBatteryLevel != UNDEFINED ? new QuantityType<>(hvBattery.hvBatteryLevel, PERCENT)
392                         : UnDefType.UNDEF;
393             case BATTERY_DISTANCE_TO_EMPTY:
394                 return hvBattery.distanceToHVBatteryEmpty != UNDEFINED
395                         ? new QuantityType<>(hvBattery.distanceToHVBatteryEmpty, KILO(METRE))
396                         : UnDefType.UNDEF;
397             case CHARGE_STATUS:
398                 return hvBattery.hvBatteryChargeStatusDerived != null ? hvBattery.hvBatteryChargeStatusDerived
399                         : UnDefType.UNDEF;
400             case CHARGE_STATUS_CABLE:
401                 return hvBattery.hvBatteryChargeStatusDerived != null
402                         ? OnOffType.from(
403                                 hvBattery.hvBatteryChargeStatusDerived.toString().startsWith("CablePluggedInCar_"))
404                         : UnDefType.UNDEF;
405             case CHARGE_STATUS_CHARGING:
406                 return hvBattery.hvBatteryChargeStatusDerived != null
407                         ? OnOffType.from(hvBattery.hvBatteryChargeStatusDerived.toString().endsWith("_Charging"))
408                         : UnDefType.UNDEF;
409             case CHARGE_STATUS_FULLY_CHARGED:
410                 /*
411                  * If the car is charging the battery level can be reported incorrectly by the API, so use the charging
412                  * status instead of checking the level when the car is plugged in.
413                  */
414                 if (hvBattery.hvBatteryChargeStatusDerived != null
415                         && hvBattery.hvBatteryChargeStatusDerived.toString().startsWith("CablePluggedInCar_")) {
416                     return OnOffType.from(hvBattery.hvBatteryChargeStatusDerived.toString().endsWith("_FullyCharged"));
417                 } else {
418                     return hvBattery.hvBatteryLevel != UNDEFINED ? OnOffType.from(hvBattery.hvBatteryLevel == 100)
419                             : UnDefType.UNDEF;
420                 }
421             case TIME_TO_BATTERY_FULLY_CHARGED:
422                 return hvBattery.timeToHVBatteryFullyCharged != UNDEFINED
423                         ? new QuantityType<>(hvBattery.timeToHVBatteryFullyCharged, MINUTE)
424                         : UnDefType.UNDEF;
425             case CHARGING_END:
426                 return hvBattery.timeToHVBatteryFullyCharged != UNDEFINED && hvBattery.timeToHVBatteryFullyCharged > 0
427                         ? new DateTimeType(ZonedDateTime.now().plusMinutes(hvBattery.timeToHVBatteryFullyCharged))
428                         : UnDefType.UNDEF;
429         }
430         return UnDefType.NULL;
431     }
432
433     private State getValue(String groupId, String channelId, Status status, VehiclePositionWrapper position) {
434         switch (channelId) {
435             case CAR_LOCKED:
436                 // Warning : carLocked is in the Doors group but is part of general status informations.
437                 // Did not change it to avoid breaking change for users
438                 return status.getCarLocked().map(State.class::cast).orElse(UnDefType.UNDEF);
439             case ENGINE_RUNNING:
440                 return status.getEngineRunning().map(State.class::cast).orElse(UnDefType.UNDEF);
441             case BRAKE_FLUID_LEVEL:
442                 return fluidLevelToState(status.brakeFluidLevel);
443             case WASHER_FLUID_LEVEL:
444                 return fluidLevelToState(status.washerFluidLevel);
445             case AVERAGE_SPEED:
446                 return status.averageSpeed != UNDEFINED ? new QuantityType<>(status.averageSpeed, KILOMETRE_PER_HOUR)
447                         : UnDefType.UNDEF;
448             case SERVICE_WARNING:
449                 return new StringType(status.serviceWarningStatus);
450             case BULB_FAILURE:
451                 return OnOffType.from(status.aFailedBulb());
452             case REMOTE_HEATER:
453             case PRECLIMATIZATION:
454                 return status.getHeater().map(heater -> getHeaterValue(channelId, heater)).orElse(UnDefType.NULL);
455         }
456         switch (groupId) {
457             case GROUP_TANK:
458                 return getTankValue(channelId, status);
459             case GROUP_ODOMETER:
460                 return getOdometerValue(channelId, status);
461             case GROUP_POSITION:
462                 return getPositionValue(channelId, position);
463             case GROUP_DOORS:
464                 return status.getDoors().map(doors -> getDoorsValue(channelId, doors)).orElse(UnDefType.NULL);
465             case GROUP_WINDOWS:
466                 return status.getWindows().map(windows -> getWindowsValue(channelId, windows)).orElse(UnDefType.NULL);
467             case GROUP_TYRES:
468                 return status.getTyrePressure().map(tyres -> getTyresValue(channelId, tyres)).orElse(UnDefType.NULL);
469             case GROUP_BATTERY:
470                 return status.getHvBattery().map(batteries -> getBatteryValue(channelId, batteries))
471                         .orElse(UnDefType.NULL);
472         }
473         return UnDefType.NULL;
474     }
475
476     private State fluidLevelToState(FluidLevel level) {
477         return level != FluidLevel.UNKNOWN ? new DecimalType(level.ordinal()) : UnDefType.UNDEF;
478     }
479
480     private State getTankValue(String channelId, Status status) {
481         switch (channelId) {
482             case DISTANCE_TO_EMPTY:
483                 return status.distanceToEmpty != UNDEFINED ? new QuantityType<>(status.distanceToEmpty, KILO(METRE))
484                         : UnDefType.UNDEF;
485             case FUEL_AMOUNT:
486                 return status.fuelAmount != UNDEFINED ? new QuantityType<>(status.fuelAmount, LITRE) : UnDefType.UNDEF;
487             case FUEL_LEVEL:
488                 return status.fuelAmountLevel != UNDEFINED ? new QuantityType<>(status.fuelAmountLevel, PERCENT)
489                         : UnDefType.UNDEF;
490             case FUEL_CONSUMPTION:
491                 return status.averageFuelConsumption != UNDEFINED ? new DecimalType(status.averageFuelConsumption / 10)
492                         : UnDefType.UNDEF;
493             case FUEL_ALERT:
494                 return OnOffType.from(status.distanceToEmpty < 100);
495         }
496         return UnDefType.UNDEF;
497     }
498
499     private State getOdometerValue(String channelId, Status status) {
500         switch (channelId) {
501             case ODOMETER:
502                 return status.odometer != UNDEFINED ? new QuantityType<>((double) status.odometer / 1000, KILO(METRE))
503                         : UnDefType.UNDEF;
504             case TRIPMETER1:
505                 return status.tripMeter1 != UNDEFINED
506                         ? new QuantityType<>((double) status.tripMeter1 / 1000, KILO(METRE))
507                         : UnDefType.UNDEF;
508             case TRIPMETER2:
509                 return status.tripMeter2 != UNDEFINED
510                         ? new QuantityType<>((double) status.tripMeter2 / 1000, KILO(METRE))
511                         : UnDefType.UNDEF;
512         }
513         return UnDefType.UNDEF;
514     }
515
516     private State getPositionValue(String channelId, VehiclePositionWrapper position) {
517         switch (channelId) {
518             case ACTUAL_LOCATION:
519                 return position.getPosition();
520             case CALCULATED_LOCATION:
521                 return position.isCalculated();
522             case HEADING:
523                 return position.isHeading();
524             case LOCATION_TIMESTAMP:
525                 return position.getTimestamp();
526         }
527         return UnDefType.UNDEF;
528     }
529
530     public void actionHonkBlink(Boolean honk, Boolean blink) {
531         StringBuilder url = new StringBuilder("vehicles/" + vehicle.vehicleId + "/honk_blink/");
532
533         if (honk && blink && activeOptions.containsKey(HONK_BLINK)) {
534             url.append("both");
535         } else if (honk && activeOptions.containsKey(HONK_AND_OR_BLINK)) {
536             url.append("horn");
537         } else if (blink && activeOptions.containsKey(HONK_AND_OR_BLINK)) {
538             url.append("lights");
539         } else {
540             logger.warn("The vehicle is not capable of this action");
541             return;
542         }
543
544         post(url.toString(), vehiclePosition.getPositionAsJSon());
545     }
546
547     private void post(String url, @Nullable String param) {
548         VocHttpApi api = bridgeHandler.getApi();
549         if (api != null) {
550             try {
551                 PostResponse postResponse = api.postURL(url, param);
552                 if (postResponse != null) {
553                     pendingActions
554                             .add(scheduler.schedule(new ActionResultController(api, postResponse, scheduler, this),
555                                     1000, TimeUnit.MILLISECONDS));
556                 }
557             } catch (VolvoOnCallException e) {
558                 logger.warn("Exception occurred during execution: {}", e.getMessage(), e);
559                 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, e.getMessage());
560             }
561         }
562         pendingActions.removeIf(ScheduledFuture::isDone);
563     }
564
565     public void actionOpenClose(String action, OnOffType controlState) {
566         if (activeOptions.containsKey(action)) {
567             if (vehicleStatus.getCarLocked().isEmpty() || vehicleStatus.getCarLocked().get() != controlState) {
568                 post(String.format("vehicles/%s/%s", configuration.vin, action), "{}");
569             } else {
570                 logger.info("The car {} is already {}ed", configuration.vin, action);
571             }
572         } else {
573             logger.warn("The car {} does not support remote {}ing", configuration.vin, action);
574         }
575     }
576
577     public void actionHeater(String action, Boolean start) {
578         if (activeOptions.containsKey(action)) {
579             String address = String.format("vehicles/%s/%s/%s", configuration.vin,
580                     action.contains(REMOTE_HEATER) ? "heater" : "preclimatization", start ? "start" : "stop");
581             post(address, start ? "{}" : null);
582         } else {
583             logger.warn("The car {} does not support {}", configuration.vin, action);
584         }
585     }
586
587     public void actionStart(Integer runtime) {
588         if (activeOptions.containsKey(ENGINE_START)) {
589             String address = String.format("vehicles/%s/engine/start", vehicle.vehicleId);
590             String json = "{\"runtime\":" + runtime.toString() + "}";
591
592             post(address, json);
593         } else {
594             logger.warn("The car {} does not support remote engine starting", vehicle.vehicleId);
595         }
596     }
597
598     @Override
599     public Collection<Class<? extends ThingHandlerService>> getServices() {
600         return List.of(VolvoOnCallActions.class);
601     }
602 }