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;
17 import java.util.regex.PatternSyntaxException;
19 import org.eclipse.jdt.annotation.NonNullByDefault;
20 import org.eclipse.jdt.annotation.Nullable;
21 import org.slf4j.Logger;
22 import org.slf4j.LoggerFactory;
25 * The {@link DarkSkyChannelConfiguration} is the class used to match the sunrise and sunset event configuration.
27 * @author Christoph Weitkamp - Initial contribution
30 public class DarkSkyChannelConfiguration {
32 private final Logger logger = LoggerFactory.getLogger(DarkSkyChannelConfiguration.class);
34 private static final Pattern HHMM_PATTERN = Pattern.compile("^([0-1][0-9]|2[0-3])(:[0-5][0-9])$");
35 private static final String TIME_SEPARATOR = ":";
38 private @Nullable String earliest;
39 private @Nullable String latest;
41 public int getOffset() {
45 public void setOffset(int offset) {
49 public @Nullable String getEarliest() {
53 public long getEarliestInMinutes() {
54 return getMinutesFromTime(earliest);
57 public void setEarliest(String earliest) {
58 this.earliest = earliest;
61 public @Nullable String getLatest() {
65 public long getLatestInMinutes() {
66 return getMinutesFromTime(latest);
69 public void setLatest(String latest) {
74 public String toString() {
75 return String.format("[offset=%d, earliest='%s', latest='%s']", offset, earliest, latest);
79 * Parses a hh:mm string and returns the minutes.
81 private long getMinutesFromTime(@Nullable String configTime) {
82 String time = configTime;
83 if (time != null && !(time = time.trim()).isEmpty()) {
85 if (!HHMM_PATTERN.matcher(time).matches()) {
86 throw new NumberFormatException();
88 String[] splittedConfigTime = time.split(TIME_SEPARATOR);
89 if (splittedConfigTime.length < 2) {
90 throw new NumberFormatException();
92 int hour = Integer.parseInt(splittedConfigTime[0]);
93 int minutes = Integer.parseInt(splittedConfigTime[1]);
94 return Duration.ofMinutes(minutes).plusHours(hour).toMinutes();
96 } catch (PatternSyntaxException | NumberFormatException | ArithmeticException ex) {
97 logger.warn("Cannot parse channel configuration '{}' to hour and minutes, use pattern hh:mm, ignoring!",