[awattar] make use of clock object

Signed-off-by: Thomas Leber <thomas@tl-photography.at>
This commit is contained in:
Thomas Leber 2024-12-22 22:45:10 +01:00
parent 70a9c79e6e
commit 77d372f2c1
8 changed files with 55 additions and 74 deletions

View File

@ -32,9 +32,9 @@ import org.openhab.core.library.unit.Units;
@NonNullByDefault
public class AwattarUtil {
public static long getMillisToNextMinute(int mod, TimeZoneProvider timeZoneProvider) {
public static long getMillisToNextMinute(int mod, ZoneId zoneId) {
long now = Instant.now().toEpochMilli();
ZonedDateTime dt = ZonedDateTime.now(timeZoneProvider.getTimeZone()).truncatedTo(ChronoUnit.MINUTES);
ZonedDateTime dt = ZonedDateTime.now(zoneId).truncatedTo(ChronoUnit.MINUTES);
int min = dt.getMinute();
int offset = min % mod;
offset = offset == 0 ? mod : offset;

View File

@ -23,6 +23,7 @@ import static org.openhab.binding.awattar.internal.AwattarUtil.getCalendarForHou
import static org.openhab.binding.awattar.internal.AwattarUtil.getDuration;
import static org.openhab.binding.awattar.internal.AwattarUtil.getMillisToNextMinute;
import java.time.Clock;
import java.time.Instant;
import java.time.ZoneId;
import java.time.ZonedDateTime;
@ -67,17 +68,17 @@ import org.slf4j.LoggerFactory;
*/
@NonNullByDefault
public class AwattarBestPriceHandler extends BaseThingHandler {
private final Clock clock;
private static final int THING_REFRESH_INTERVAL = 60;
private final Logger logger = LoggerFactory.getLogger(AwattarBestPriceHandler.class);
private @Nullable ScheduledFuture<?> thingRefresher;
private final TimeZoneProvider timeZoneProvider;
public AwattarBestPriceHandler(Thing thing, TimeZoneProvider timeZoneProvider) {
public AwattarBestPriceHandler(Thing thing, Clock clock) {
super(thing);
this.timeZoneProvider = timeZoneProvider;
this.clock = clock;
}
@Override
@ -97,7 +98,7 @@ public class AwattarBestPriceHandler extends BaseThingHandler {
* here
*/
thingRefresher = scheduler.scheduleAtFixedRate(this::refreshChannels,
getMillisToNextMinute(1, timeZoneProvider), THING_REFRESH_INTERVAL * 1000L,
getMillisToNextMinute(1, clock.getZone()), THING_REFRESH_INTERVAL * 1000L,
TimeUnit.MILLISECONDS);
}
}
@ -163,7 +164,7 @@ public class AwattarBestPriceHandler extends BaseThingHandler {
long diff;
switch (channelId) {
case CHANNEL_ACTIVE:
state = OnOffType.from(result.isActive(getNow()));
state = OnOffType.from(result.isActive(clock.instant()));
break;
case CHANNEL_START:
state = new DateTimeType(Instant.ofEpochMilli(result.getStart()));
@ -172,7 +173,7 @@ public class AwattarBestPriceHandler extends BaseThingHandler {
state = new DateTimeType(Instant.ofEpochMilli(result.getEnd()));
break;
case CHANNEL_COUNTDOWN:
diff = result.getStart() - getNow().toEpochMilli();
diff = result.getStart() - clock.instant().toEpochMilli();
if (diff >= 0) {
state = getDuration(diff);
} else {
@ -180,8 +181,8 @@ public class AwattarBestPriceHandler extends BaseThingHandler {
}
break;
case CHANNEL_REMAINING:
if (result.isActive(getNow())) {
diff = result.getEnd() - getNow().toEpochMilli();
if (result.isActive(clock.instant())) {
diff = result.getEnd() - clock.instant().toEpochMilli();
state = getDuration(diff);
} else {
state = QuantityType.valueOf(0, Units.MINUTE);
@ -227,7 +228,7 @@ public class AwattarBestPriceHandler extends BaseThingHandler {
protected TimeRange getRange(int start, int duration, ZoneId zoneId) {
ZonedDateTime startTime = getStartTime(start, zoneId);
ZonedDateTime endTime = startTime.plusHours(duration);
ZonedDateTime now = getNow().atZone(zoneId);
ZonedDateTime now = clock.instant().atZone(zoneId);
if (now.getHour() < start) {
// we are before the range, so we might be still within the last range
startTime = startTime.minusDays(1);
@ -251,14 +252,4 @@ public class AwattarBestPriceHandler extends BaseThingHandler {
protected ZonedDateTime getStartTime(int start, ZoneId zoneId) {
return getCalendarForHour(start, zoneId);
}
/**
* Returns the current time.
*
* @param zoneId the time zone
* @return the current time
*/
protected Instant getNow() {
return Instant.now();
}
}

View File

@ -15,13 +15,13 @@ package org.openhab.binding.awattar.internal.handler;
import static org.openhab.binding.awattar.internal.AwattarBindingConstants.CHANNEL_MARKET_NET;
import static org.openhab.binding.awattar.internal.AwattarBindingConstants.CHANNEL_TOTAL_NET;
import java.time.Clock;
import java.time.Instant;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.SortedSet;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import java.util.function.ToDoubleFunction;
import javax.measure.Unit;
@ -32,7 +32,6 @@ import org.openhab.binding.awattar.internal.AwattarBridgeConfiguration;
import org.openhab.binding.awattar.internal.AwattarPrice;
import org.openhab.binding.awattar.internal.api.AwattarApi;
import org.openhab.binding.awattar.internal.api.AwattarApi.AwattarApiException;
import org.openhab.core.i18n.TimeZoneProvider;
import org.openhab.core.library.types.QuantityType;
import org.openhab.core.library.unit.CurrencyUnits;
import org.openhab.core.thing.Bridge;
@ -65,20 +64,20 @@ public class AwattarBridgeHandler extends BaseBridgeHandler {
private final Logger logger = LoggerFactory.getLogger(AwattarBridgeHandler.class);
private final HttpClient httpClient;
private final Clock clock;
private @Nullable ScheduledFuture<?> dataRefresher;
private Instant lastRefresh = Instant.EPOCH;
// This cache stores price data for up to two days
private @Nullable SortedSet<AwattarPrice> prices;
private ZoneId zone;
private @Nullable AwattarApi awattarApi;
public AwattarBridgeHandler(Bridge thing, HttpClient httpClient, TimeZoneProvider timeZoneProvider) {
public AwattarBridgeHandler(Bridge thing, HttpClient httpClient, Clock clock) {
super(thing);
this.httpClient = httpClient;
zone = timeZoneProvider.getTimeZone();
this.clock = clock;
}
@Override
@ -87,7 +86,7 @@ public class AwattarBridgeHandler extends BaseBridgeHandler {
AwattarBridgeConfiguration config = getConfigAs(AwattarBridgeConfiguration.class);
try {
awattarApi = new AwattarApi(httpClient, zone, config);
awattarApi = new AwattarApi(httpClient, clock.getZone(), config);
dataRefresher = scheduler.scheduleWithFixedDelay(this::refreshIfNeeded, 0, DATA_REFRESH_INTERVAL * 1000L,
TimeUnit.MILLISECONDS);
@ -154,17 +153,15 @@ public class AwattarBridgeHandler extends BaseBridgeHandler {
return priceUnit;
}
private void createAndSendTimeSeries(String channelId, Function<AwattarPrice, Double> valueFunction) {
private void createAndSendTimeSeries(String channelId, ToDoubleFunction<AwattarPrice> valueFunction) {
SortedSet<AwattarPrice> locPrices = getPrices();
Unit<?> priceUnit = getPriceUnit();
if (locPrices == null) {
return;
}
TimeSeries timeSeries = new TimeSeries(TimeSeries.Policy.REPLACE);
locPrices.forEach(p -> {
timeSeries.add(Instant.ofEpochMilli(p.timerange().start()),
new QuantityType<>(valueFunction.apply(p) / 100.0, priceUnit));
});
locPrices.forEach(p -> timeSeries.add(Instant.ofEpochMilli(p.timerange().start()),
new QuantityType<>(valueFunction.applyAsDouble(p) / 100.0, priceUnit)));
sendTimeSeries(channelId, timeSeries);
}
@ -200,13 +197,14 @@ public class AwattarBridgeHandler extends BaseBridgeHandler {
// do not refresh before 15:00, since the prices for the next day are available
// only after 14:00
ZonedDateTime now = ZonedDateTime.now(zone);
if (now.getHour() < 15) {
Instant now = clock.instant();
if (now.isBefore(clock.instant().truncatedTo(java.time.temporal.ChronoUnit.DAYS).plus(15,
java.time.temporal.ChronoUnit.HOURS))) {
return false;
}
// refresh then every 3 hours, if the last refresh was more than an hour ago
if (now.getHour() % 3 == 0 && lastRefresh.getEpochSecond() < now.minusHours(1).toEpochSecond()) {
if (lastRefresh.plus(3, java.time.temporal.ChronoUnit.HOURS).isBefore(now)) {
// update the last refresh time
lastRefresh = Instant.now();
@ -218,7 +216,7 @@ public class AwattarBridgeHandler extends BaseBridgeHandler {
}
public ZoneId getTimeZone() {
return zone;
return clock.getZone();
}
@Nullable
@ -261,6 +259,7 @@ public class AwattarBridgeHandler extends BaseBridgeHandler {
switch (channelUID.getId()) {
case CHANNEL_MARKET_NET -> createAndSendTimeSeries(CHANNEL_MARKET_NET, AwattarPrice::netPrice);
case CHANNEL_TOTAL_NET -> createAndSendTimeSeries(CHANNEL_TOTAL_NET, AwattarPrice::netTotal);
default -> logger.warn("Channel {} not supported", channelUID.getId());
}
}
}

View File

@ -16,6 +16,7 @@ import static org.openhab.binding.awattar.internal.AwattarBindingConstants.THING
import static org.openhab.binding.awattar.internal.AwattarBindingConstants.THING_TYPE_BRIDGE;
import static org.openhab.binding.awattar.internal.AwattarBindingConstants.THING_TYPE_PRICE;
import java.time.Clock;
import java.util.Set;
import org.eclipse.jdt.annotation.NonNullByDefault;
@ -50,13 +51,13 @@ public class AwattarHandlerFactory extends BaseThingHandlerFactory {
private static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Set.of(THING_TYPE_PRICE, THING_TYPE_BESTPRICE,
THING_TYPE_BRIDGE);
private final HttpClient httpClient;
private final TimeZoneProvider timeZoneProvider;
private final Clock systemClock;
@Activate
public AwattarHandlerFactory(final @Reference HttpClientFactory httpClientFactory,
final @Reference TimeZoneProvider timeZoneProvider) {
this.httpClient = httpClientFactory.getCommonHttpClient();
this.timeZoneProvider = timeZoneProvider;
this.systemClock = Clock.system(timeZoneProvider.getTimeZone());
}
@Override
@ -69,11 +70,11 @@ public class AwattarHandlerFactory extends BaseThingHandlerFactory {
ThingTypeUID thingTypeUID = thing.getThingTypeUID();
if (THING_TYPE_BRIDGE.equals(thingTypeUID)) {
return new AwattarBridgeHandler((Bridge) thing, httpClient, timeZoneProvider);
return new AwattarBridgeHandler((Bridge) thing, httpClient, systemClock);
} else if (THING_TYPE_PRICE.equals(thingTypeUID)) {
return new AwattarPriceHandler(thing, timeZoneProvider);
return new AwattarPriceHandler(thing, systemClock);
} else if (THING_TYPE_BESTPRICE.equals(thingTypeUID)) {
return new AwattarBestPriceHandler(thing, timeZoneProvider);
return new AwattarBestPriceHandler(thing, systemClock);
}
logger.warn("Unknown thing type {}, not creating handler!", thingTypeUID);

View File

@ -23,6 +23,7 @@ import static org.openhab.binding.awattar.internal.AwattarUtil.getMillisToNextMi
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.Clock;
import java.time.ZonedDateTime;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
@ -30,7 +31,6 @@ import java.util.concurrent.TimeUnit;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable;
import org.openhab.binding.awattar.internal.AwattarPrice;
import org.openhab.core.i18n.TimeZoneProvider;
import org.openhab.core.library.types.DecimalType;
import org.openhab.core.thing.Bridge;
import org.openhab.core.thing.Channel;
@ -55,15 +55,16 @@ import org.slf4j.LoggerFactory;
*/
@NonNullByDefault
public class AwattarPriceHandler extends BaseThingHandler {
private final Clock clock;
private static final int THING_REFRESH_INTERVAL = 60;
private final Logger logger = LoggerFactory.getLogger(AwattarPriceHandler.class);
private final TimeZoneProvider timeZoneProvider;
private @Nullable ScheduledFuture<?> thingRefresher;
public AwattarPriceHandler(Thing thing, TimeZoneProvider timeZoneProvider) {
public AwattarPriceHandler(Thing thing, Clock clock) {
super(thing);
this.timeZoneProvider = timeZoneProvider;
this.clock = clock;
}
@Override
@ -90,7 +91,7 @@ public class AwattarPriceHandler extends BaseThingHandler {
* here
*/
thingRefresher = scheduler.scheduleAtFixedRate(this::refreshChannels,
getMillisToNextMinute(1, timeZoneProvider), THING_REFRESH_INTERVAL * 1000,
getMillisToNextMinute(1, clock.getZone()), THING_REFRESH_INTERVAL * 1000L,
TimeUnit.MILLISECONDS);
}
}
@ -153,7 +154,7 @@ public class AwattarPriceHandler extends BaseThingHandler {
AwattarPrice price = bridgeHandler.getPriceFor(target.toInstant().toEpochMilli());
if (price == null) {
logger.trace("No price found for hour {}", target.toString());
logger.trace("No price found for hour {}", target);
updateState(channelUID, state);
return;
}

View File

@ -45,7 +45,6 @@ import org.mockito.quality.Strictness;
import org.openhab.binding.awattar.internal.AwattarBridgeConfiguration;
import org.openhab.binding.awattar.internal.AwattarPrice;
import org.openhab.binding.awattar.internal.api.AwattarApi.AwattarApiException;
import org.openhab.core.i18n.TimeZoneProvider;
import org.openhab.core.test.java.JavaTest;
/**
@ -60,7 +59,6 @@ import org.openhab.core.test.java.JavaTest;
class AwattarApiTest extends JavaTest {
// API Mocks
private @Mock @NonNullByDefault({}) HttpClient httpClientMock;
private @Mock @NonNullByDefault({}) TimeZoneProvider timeZoneProviderMock;
private @Mock @NonNullByDefault({}) Request requestMock;
private @Mock @NonNullByDefault({}) ContentResponse contentResponseMock;
private @Mock @NonNullByDefault({}) AwattarBridgeConfiguration config;
@ -86,8 +84,6 @@ class AwattarApiTest extends JavaTest {
when(requestMock.timeout(10, TimeUnit.SECONDS)).thenReturn(requestMock);
when(requestMock.send()).thenReturn(contentResponseMock);
when(timeZoneProviderMock.getTimeZone()).thenReturn(ZoneId.of("GMT+2"));
config.basePrice = 0.0;
config.vatPercent = 0.0;
config.country = "DE";

View File

@ -19,7 +19,7 @@ import static org.mockito.Mockito.when;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.time.ZoneId;
import java.time.Clock;
import java.util.List;
import org.eclipse.jdt.annotation.NonNullByDefault;
@ -36,7 +36,6 @@ import org.mockito.quality.Strictness;
import org.openhab.binding.awattar.internal.AwattarBindingConstants;
import org.openhab.binding.awattar.internal.api.AwattarApi;
import org.openhab.binding.awattar.internal.api.AwattarApi.AwattarApiException;
import org.openhab.core.i18n.TimeZoneProvider;
import org.openhab.core.test.java.JavaTest;
import org.openhab.core.thing.Bridge;
import org.openhab.core.thing.Thing;
@ -62,7 +61,7 @@ class AwattarBridgeHandlerRefreshTest extends JavaTest {
private @Mock @NonNullByDefault({}) Bridge bridgeMock;
private @Mock @NonNullByDefault({}) ThingHandlerCallback bridgeCallbackMock;
private @Mock @NonNullByDefault({}) HttpClient httpClientMock;
private @Mock @NonNullByDefault({}) TimeZoneProvider timeZoneProviderMock;
private @Mock @NonNullByDefault({}) Clock clockMock;
private @Mock @NonNullByDefault({}) AwattarApi awattarApiMock;
// best price handler mocks
@ -73,10 +72,8 @@ class AwattarBridgeHandlerRefreshTest extends JavaTest {
@BeforeEach
public void setUp() throws IllegalArgumentException, IllegalAccessException {
when(timeZoneProviderMock.getTimeZone()).thenReturn(ZoneId.of("GMT+2"));
when(bridgeMock.getUID()).thenReturn(BRIDGE_UID);
bridgeHandler = new AwattarBridgeHandler(bridgeMock, httpClientMock, timeZoneProviderMock);
bridgeHandler = new AwattarBridgeHandler(bridgeMock, httpClientMock, clockMock);
bridgeHandler.setCallback(bridgeCallbackMock);
List<Field> fields = ReflectionSupport.findFields(AwattarBridgeHandler.class,

View File

@ -30,6 +30,7 @@ import static org.openhab.binding.awattar.internal.AwattarBindingConstants.CHANN
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.time.Clock;
import java.time.Instant;
import java.time.ZoneId;
import java.time.ZonedDateTime;
@ -61,7 +62,6 @@ import org.openhab.binding.awattar.internal.api.AwattarApi;
import org.openhab.binding.awattar.internal.api.AwattarApi.AwattarApiException;
import org.openhab.binding.awattar.internal.dto.AwattarApiData;
import org.openhab.core.config.core.Configuration;
import org.openhab.core.i18n.TimeZoneProvider;
import org.openhab.core.library.types.DateTimeType;
import org.openhab.core.library.types.OnOffType;
import org.openhab.core.library.types.QuantityType;
@ -91,7 +91,6 @@ public class AwattarBridgeHandlerTest extends JavaTest {
private @Mock @NonNullByDefault({}) Bridge bridgeMock;
private @Mock @NonNullByDefault({}) ThingHandlerCallback bridgeCallbackMock;
private @Mock @NonNullByDefault({}) HttpClient httpClientMock;
private @Mock @NonNullByDefault({}) TimeZoneProvider timeZoneProviderMock;
private @Mock @NonNullByDefault({}) AwattarApi awattarApiMock;
// best price handler mocks
@ -116,10 +115,10 @@ public class AwattarBridgeHandlerTest extends JavaTest {
when(awattarApiMock.getData()).thenReturn(result);
}
when(timeZoneProviderMock.getTimeZone()).thenReturn(ZoneId.of("GMT+2"));
Clock clock = Clock.fixed(Instant.parse("2024-06-15T12:00:00Z"), ZoneId.of("GMT+2"));
when(bridgeMock.getUID()).thenReturn(BRIDGE_UID);
bridgeHandler = new AwattarBridgeHandler(bridgeMock, httpClientMock, timeZoneProviderMock);
bridgeHandler = new AwattarBridgeHandler(bridgeMock, httpClientMock, clock);
bridgeHandler.setCallback(bridgeCallbackMock);
// mock the private field awattarApi
@ -202,14 +201,11 @@ public class AwattarBridgeHandlerTest extends JavaTest {
consecutive);
when(bestpriceMock.getConfiguration()).thenReturn(new Configuration(config));
AwattarBestPriceHandler handler = new AwattarBestPriceHandler(bestpriceMock, timeZoneProviderMock) {
AwattarBestPriceHandler handler = new AwattarBestPriceHandler(bestpriceMock,
Clock.fixed(Instant.parse("2024-06-15T12:00:00Z"), ZoneId.of("GMT+2"))) {
protected ZonedDateTime getStartTime(int start, ZoneId zoneId) {
return ZonedDateTime.of(2024, 6, 15, 12, 0, 0, 0, zoneId);
}
protected Instant getNow() {
return ZonedDateTime.of(2024, 6, 15, 12, 0, 0, 0, ZoneId.of("GMT+2")).toInstant();
}
};
handler.setCallback(bestPriceCallbackMock);
@ -258,13 +254,13 @@ public class AwattarBridgeHandlerTest extends JavaTest {
consecutive);
when(bestpriceMock.getConfiguration()).thenReturn(new Configuration(config));
AwattarBestPriceHandler handler = new AwattarBestPriceHandler(bestpriceMock, timeZoneProviderMock) {
protected ZonedDateTime getStartTime(int start, ZoneId zoneId) {
return ZonedDateTime.of(2024, 6, 15, 0, 0, 0, 0, zoneId);
}
Clock clock = Clock.fixed(
ZonedDateTime.of(2024, 6, 15, currentHour, currentMinute, 0, 0, ZoneId.of("GMT+2")).toInstant(),
ZoneId.of("GMT+2"));
protected Instant getNow() {
return ZonedDateTime.of(2024, 6, 15, currentHour, currentMinute, 0, 0, ZoneId.of("GMT+2")).toInstant();
AwattarBestPriceHandler handler = new AwattarBestPriceHandler(bestpriceMock, clock) {
protected ZonedDateTime getStartTime(int start, ZoneId zoneId) {
return ZonedDateTime.of(2024, 6, 15, 0, 0, 0, 0, clock.getZone());
}
};