]> git.basschouten.com Git - openhab-addons.git/blob
d11849347238659a14517333aef0fce4d7231a78
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2021 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.persistence.jpa.internal;
14
15 import java.util.Locale;
16
17 import org.openhab.core.library.types.DateTimeType;
18 import org.openhab.core.library.types.DecimalType;
19 import org.openhab.core.library.types.PointType;
20 import org.openhab.core.types.State;
21
22 /**
23  * Helper class for dealing with State
24  *
25  * @author Manfred Bergmann - Initial contribution
26  *
27  */
28 public class StateHelper {
29
30     /**
31      * Converts the given State to a string that can be persisted in db
32      *
33      * @param state the state of the item to be persisted
34      * @return state converted as string
35      * @throws Exception
36      */
37     public static String toString(State state) throws Exception {
38         if (state instanceof DateTimeType) {
39             return String.valueOf(((DateTimeType) state).getZonedDateTime().toInstant().toEpochMilli());
40         }
41         if (state instanceof DecimalType) {
42             return String.valueOf(((DecimalType) state).doubleValue());
43         }
44         if (state instanceof PointType) {
45             PointType pType = (PointType) state;
46             return String.format(Locale.ENGLISH, "%f;%f;%f", pType.getLatitude().doubleValue(),
47                     pType.getLongitude().doubleValue(), pType.getAltitude().doubleValue());
48         }
49
50         return state.toString();
51     }
52 }