2 * Copyright (c) 2010-2021 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.darksky.internal.config;
15 import java.time.Duration;
16 import java.util.regex.Pattern;
18 import org.eclipse.jdt.annotation.NonNullByDefault;
19 import org.eclipse.jdt.annotation.Nullable;
20 import org.slf4j.Logger;
21 import org.slf4j.LoggerFactory;
24 * The {@link DarkSkyChannelConfiguration} is the class used to match the sunrise and sunset event configuration.
26 * @author Christoph Weitkamp - Initial contribution
29 public class DarkSkyChannelConfiguration {
31 private final Logger logger = LoggerFactory.getLogger(DarkSkyChannelConfiguration.class);
33 private static final Pattern HHMM_PATTERN = Pattern.compile("^([0-1][0-9]|2[0-3])(:[0-5][0-9])$");
34 private static final String TIME_SEPARATOR = ":";
37 private @Nullable String earliest;
38 private @Nullable String latest;
40 public int getOffset() {
44 public void setOffset(int offset) {
48 public @Nullable String getEarliest() {
52 public long getEarliestInMinutes() {
53 return getMinutesFromTime(earliest);
56 public void setEarliest(String earliest) {
57 this.earliest = earliest;
60 public @Nullable String getLatest() {
64 public long getLatestInMinutes() {
65 return getMinutesFromTime(latest);
68 public void setLatest(String latest) {
73 public String toString() {
74 return String.format("[offset=%d, earliest='%s', latest='%s']", offset, earliest, latest);
78 * Parses a hh:mm string and returns the minutes.
80 private long getMinutesFromTime(@Nullable String configTime) {
81 String time = configTime;
82 if (time != null && !(time = time.trim()).isEmpty()) {
84 if (!HHMM_PATTERN.matcher(time).matches()) {
85 throw new NumberFormatException();
87 String[] splittedConfigTime = time.split(TIME_SEPARATOR);
88 int hour = Integer.parseInt(splittedConfigTime[0]);
89 int minutes = Integer.parseInt(splittedConfigTime[1]);
90 return Duration.ofMinutes(minutes).plusHours(hour).toMinutes();
92 } catch (Exception ex) {
93 logger.warn("Cannot parse channel configuration '{}' to hour and minutes, use pattern hh:mm, ignoring!",