]> git.basschouten.com Git - openhab-addons.git/blob
3fcbb37d728ad68422bfc0f02dff42507f0048fc
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2022 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.mqtt.generic.values;
14
15 import java.time.format.DateTimeFormatter;
16 import java.util.stream.Collectors;
17 import java.util.stream.Stream;
18
19 import org.eclipse.jdt.annotation.NonNullByDefault;
20 import org.eclipse.jdt.annotation.Nullable;
21 import org.openhab.core.library.CoreItemFactory;
22 import org.openhab.core.library.types.DateTimeType;
23 import org.openhab.core.library.types.StringType;
24 import org.openhab.core.types.Command;
25 import org.openhab.core.types.UnDefType;
26
27 /**
28  * Implements a datetime value.
29  *
30  * @author David Graeff - Initial contribution
31  */
32 @NonNullByDefault
33 public class DateTimeValue extends Value {
34     public DateTimeValue() {
35         super(CoreItemFactory.DATETIME, Stream.of(DateTimeType.class, StringType.class).collect(Collectors.toList()));
36     }
37
38     @Override
39     public void update(Command command) throws IllegalArgumentException {
40         if (command instanceof DateTimeType) {
41             state = ((DateTimeType) command);
42         } else {
43             state = DateTimeType.valueOf(command.toString());
44         }
45     }
46
47     @Override
48     public String getMQTTpublishValue(@Nullable String pattern) {
49         if (state == UnDefType.UNDEF) {
50             return "";
51         }
52         String formatPattern = pattern;
53         if (formatPattern == null || "%s".contentEquals(formatPattern)) {
54             return DateTimeFormatter.ISO_LOCAL_DATE_TIME.format(((DateTimeType) state).getZonedDateTime());
55         }
56         return String.format(formatPattern, ((DateTimeType) state).getZonedDateTime());
57     }
58 }