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.volvooncall.internal.wrapper;
15 import java.time.ZoneId;
16 import java.util.Optional;
18 import org.eclipse.jdt.annotation.NonNullByDefault;
19 import org.eclipse.jdt.annotation.Nullable;
20 import org.openhab.binding.volvooncall.internal.dto.Position;
21 import org.openhab.binding.volvooncall.internal.dto.PositionData;
22 import org.openhab.core.library.types.DateTimeType;
23 import org.openhab.core.library.types.OnOffType;
24 import org.openhab.core.library.types.PointType;
25 import org.openhab.core.types.State;
26 import org.openhab.core.types.UnDefType;
29 * The {@link VehiclePositionWrapper} stores provides utility functions
30 * over a {@link Position} provided by the rest API
32 * @author Gaƫl L'hopital - Initial contribution
35 public class VehiclePositionWrapper {
36 private final Optional<PositionData> position;
37 private boolean isCalculated;
39 public VehiclePositionWrapper(Position vehicle) {
40 if (vehicle.calculatedPosition != null && vehicle.position.latitude != null) {
41 position = Optional.of(vehicle.position);
43 } else if (vehicle.calculatedPosition != null && vehicle.calculatedPosition.latitude != null) {
44 position = Optional.of(vehicle.calculatedPosition);
47 position = Optional.empty();
51 private State getPositionAsState(PositionData details) {
52 if (details.latitude != null && details.longitude != null) {
53 return new PointType(details.latitude + "," + details.longitude);
55 return UnDefType.NULL;
58 public State getPosition() {
59 return position.map(pos -> getPositionAsState(pos)).orElse(UnDefType.UNDEF);
62 public @Nullable String getPositionAsJSon() {
63 if (getPosition() != UnDefType.UNDEF) {
64 StringBuilder json = new StringBuilder("{\"clientLatitude\":");
65 json.append(position.get().latitude);
66 json.append(",\"clientLongitude\":");
67 json.append(position.get().longitude);
68 json.append(",\"clientAccuracy\":0}");
70 return json.toString();
75 public State isCalculated() {
76 return position.map(pos -> isCalculated ? (State) OnOffType.ON : OnOffType.OFF).orElse(UnDefType.UNDEF);
79 public State isHeading() {
80 return position.map(pos -> pos.isHeading() ? (State) OnOffType.ON : OnOffType.OFF).orElse(UnDefType.UNDEF);
83 public State getTimestamp() {
84 return position.flatMap(pos -> pos.getTimestamp())
85 .map(dt -> (State) new DateTimeType(dt.withZoneSameInstant(ZoneId.systemDefault())))
86 .orElse(UnDefType.NULL);