]> git.basschouten.com Git - openhab-addons.git/blob
ab5464fc5c4d65c6ec09ab71a9e57d928b370a12
[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.ihc.internal.converters;
14
15 import java.time.ZonedDateTime;
16 import java.util.Calendar;
17 import java.util.GregorianCalendar;
18 import java.util.TimeZone;
19
20 import org.eclipse.jdt.annotation.NonNull;
21 import org.openhab.binding.ihc.internal.ws.exeptions.ConversionException;
22 import org.openhab.binding.ihc.internal.ws.resourcevalues.WSDateValue;
23 import org.openhab.binding.ihc.internal.ws.resourcevalues.WSTimeValue;
24 import org.openhab.core.library.types.DateTimeType;
25
26 /**
27  * DateTimeType <-> WSTimeValue converter.
28  *
29  * @author Pauli Anttila - Initial contribution
30  */
31 public class DateTimeTypeWSTimeValueConverter implements Converter<WSTimeValue, DateTimeType> {
32
33     @Override
34     public DateTimeType convertFromResourceValue(@NonNull WSTimeValue from,
35             @NonNull ConverterAdditionalInfo convertData) throws ConversionException {
36         Calendar cal = dateTimeToCalendar(null, from);
37         return new DateTimeType(ZonedDateTime.ofInstant(cal.toInstant(), TimeZone.getDefault().toZoneId()));
38     }
39
40     @Override
41     public WSTimeValue convertFromOHType(@NonNull DateTimeType from, @NonNull WSTimeValue value,
42             @NonNull ConverterAdditionalInfo convertData) throws ConversionException {
43         Calendar cal = GregorianCalendar.from(from.getZonedDateTime());
44         return new WSTimeValue(value.resourceID, cal.get(Calendar.HOUR_OF_DAY), cal.get(Calendar.MINUTE),
45                 cal.get(Calendar.SECOND));
46     }
47
48     private Calendar dateTimeToCalendar(WSDateValue date, WSTimeValue time) {
49         Calendar cal = new GregorianCalendar(2000, 01, 01);
50         if (date != null) {
51             short year = date.year;
52             short month = date.month;
53             short day = date.day;
54
55             cal.set(year, month - 1, day, 0, 0, 0);
56         }
57         if (time != null) {
58             int hour = time.hours;
59             int minute = time.minutes;
60             int second = time.seconds;
61             cal.set(2000, 0, 1, hour, minute, second);
62         }
63         return cal;
64     }
65 }