Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[sagercaster] Enhance binding internals #11295

Merged
merged 9 commits into from
Oct 21, 2021
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,11 @@
*/
package org.openhab.binding.sagercaster.internal;

import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

import org.eclipse.jdt.annotation.NonNullByDefault;
import org.openhab.core.thing.ThingTypeUID;

Expand All @@ -35,7 +40,6 @@ public class SagerCasterBindingConstants {
public static final String CONFIG_PERIOD = "observation-period";

// List of all Channel Groups Group Channel ids
public static final String GROUP_INPUT = "input";
public static final String GROUP_OUTPUT = "output";

// Output channel ids
Expand All @@ -55,4 +59,9 @@ public class SagerCasterBindingConstants {
public static final String CHANNEL_TEMPERATURE = "temperature";
public static final String CHANNEL_PRESSURE = "pressure";
public static final String CHANNEL_WIND_ANGLE = "wind-angle";

// Some algorythms constants
public final static String FORECAST_PENDING = "0";
public final static Set<String> SHOWERS = Collections
.unmodifiableSet(new HashSet<>(Arrays.asList("G", "K", "L", "R", "S", "T", "U", "W")));
clinique marked this conversation as resolved.
Show resolved Hide resolved
}
Original file line number Diff line number Diff line change
Expand Up @@ -58,9 +58,8 @@ public boolean supportsThingType(ThingTypeUID thingTypeUID) {
protected @Nullable ThingHandler createHandler(Thing thing) {
ThingTypeUID thingTypeUID = thing.getThingTypeUID();

if (thingTypeUID.equals(THING_TYPE_SAGERCASTER)) {
return new SagerCasterHandler(thing, stateDescriptionProvider, sagerWeatherCaster);
}
return null;
return thingTypeUID.equals(THING_TYPE_SAGERCASTER)
? new SagerCasterHandler(thing, stateDescriptionProvider, sagerWeatherCaster)
: null;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -76,8 +76,6 @@
@Component(service = SagerWeatherCaster.class, scope = ServiceScope.SINGLETON)
@NonNullByDefault
public class SagerWeatherCaster {
private final Properties forecaster = new Properties();

// Northern Polar Zone & Northern Tropical Zone
private final static String[] NPZDIRECTIONS = { "S", "SW", "W", "NW", "N", "NE", "E", "SE" };
// Northern Temperate Zone
Expand All @@ -88,9 +86,10 @@ public class SagerWeatherCaster {
private final static String[] STZDIRECTIONS = { "S", "SE", "E", "NE", "N", "NW", "W", "SW" };

private final Logger logger = LoggerFactory.getLogger(SagerWeatherCaster.class);
private final Properties forecaster = new Properties();

private Optional<Prevision> prevision = Optional.empty();
private @NonNullByDefault({}) String[] usedDirections;
private String[] usedDirections = NTZDIRECTIONS; // Defaulted to Northern Zone

private int currentBearing = -1;
private int windEvolution = -1; // Whether the wind during the last 6 hours has changed its direction by
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
import org.openhab.core.library.types.PointType;
import org.openhab.core.thing.ThingTypeUID;
import org.openhab.core.thing.ThingUID;
import org.osgi.service.component.annotations.Activate;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Reference;
import org.slf4j.Logger;
Expand All @@ -46,17 +47,19 @@ public class SagerCasterDiscoveryService extends AbstractDiscoveryService {
private final Logger logger = LoggerFactory.getLogger(SagerCasterDiscoveryService.class);
private static final int DISCOVER_TIMEOUT_SECONDS = 30;
private static final int LOCATION_CHANGED_CHECK_INTERVAL = 60;
private @NonNullByDefault({}) LocationProvider locationProvider;
private @NonNullByDefault({}) ScheduledFuture<?> sagerCasterDiscoveryJob;
private final LocationProvider locationProvider;
private @Nullable ScheduledFuture<?> discoveryJob;
private @Nullable PointType previousLocation;

private static final ThingUID sagerCasterThing = new ThingUID(THING_TYPE_SAGERCASTER, LOCAL);

/**
* Creates a SagerCasterDiscoveryService with enabled autostart.
*/
public SagerCasterDiscoveryService() {
@Activate
public SagerCasterDiscoveryService(final @Reference LocationProvider locationProvider) {
super(new HashSet<>(Arrays.asList(new ThingTypeUID(BINDING_ID, "-"))), DISCOVER_TIMEOUT_SECONDS, true);
this.locationProvider = locationProvider;
}

@Override
Expand All @@ -82,8 +85,8 @@ protected void startScan() {

@Override
protected void startBackgroundDiscovery() {
if (sagerCasterDiscoveryJob == null) {
sagerCasterDiscoveryJob = scheduler.scheduleWithFixedDelay(() -> {
if (discoveryJob == null) {
discoveryJob = scheduler.scheduleWithFixedDelay(() -> {
PointType currentLocation = locationProvider.getLocation();
if (currentLocation != null && !Objects.equals(currentLocation, previousLocation)) {
logger.debug("Location has been changed from {} to {}: Creating new discovery results",
Expand All @@ -99,28 +102,19 @@ protected void startBackgroundDiscovery() {

@Override
protected void stopBackgroundDiscovery() {
ScheduledFuture<?> localJob = this.discoveryJob;
logger.debug("Stopping Sager Weathercaster background discovery");
if (sagerCasterDiscoveryJob != null && !sagerCasterDiscoveryJob.isCancelled()) {
if (sagerCasterDiscoveryJob.cancel(true)) {
sagerCasterDiscoveryJob = null;
if (localJob != null && !localJob.isCancelled()) {
if (localJob.cancel(true)) {
discoveryJob = null;
logger.debug("Stopped SagerCaster device background discovery");
}
}
}

public void createResults(PointType location) {
String propGeolocation;
propGeolocation = String.format("%s,%s", location.getLatitude(), location.getLongitude());
thingDiscovered(DiscoveryResultBuilder.create(sagerCasterThing).withLabel("Local Sager Weathercaster")
String propGeolocation = String.format("%s,%s", location.getLatitude(), location.getLongitude());
thingDiscovered(DiscoveryResultBuilder.create(sagerCasterThing).withLabel("Local Weather Forecast")
.withRepresentationProperty(CONFIG_LOCATION).withProperty(CONFIG_LOCATION, propGeolocation).build());
}

@Reference
protected void setLocationProvider(LocationProvider locationProvider) {
this.locationProvider = locationProvider;
}

protected void unsetLocationProvider(LocationProvider locationProvider) {
this.locationProvider = null;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -38,10 +38,10 @@ public void put(T newValue) {
long now = System.currentTimeMillis();
values.put(now, newValue);
Optional<Long> eldestKey = values.keySet().stream().filter(key -> key < now - eldestAge).findFirst();
if (eldestKey.isPresent()) {
agedValue = Optional.ofNullable(values.get(eldestKey.get()));
values.entrySet().removeIf(map -> map.getKey() <= eldestKey.get());
}
eldestKey.ifPresent(eldest -> {
agedValue = Optional.ofNullable(values.get(eldest));
values.entrySet().removeIf(map -> map.getKey() <= eldest);
});
}

public Optional<T> getAgedValue() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,16 +17,11 @@

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.TimeUnit;

import javax.measure.quantity.Angle;
import javax.measure.quantity.Dimensionless;
import javax.measure.quantity.Pressure;
import javax.measure.quantity.Temperature;

Expand Down Expand Up @@ -56,10 +51,6 @@
*/
@NonNullByDefault
public class SagerCasterHandler extends BaseThingHandler {
private final static String FORECAST_PENDING = "0";
private final static Set<String> SHOWERS = Collections
.unmodifiableSet(new HashSet<>(Arrays.asList("G", "K", "L", "R", "S", "T", "U", "W")));

private final Logger logger = LoggerFactory.getLogger(SagerCasterHandler.class);
private final SagerWeatherCaster sagerWeatherCaster;
private final WindDirectionStateDescriptionProvider stateDescriptionProvider;
Expand All @@ -82,7 +73,7 @@ public void initialize() {
int observationPeriod = ((BigDecimal) getConfig().get(CONFIG_PERIOD)).intValue();
String latitude = location.split(",")[0];
sagerWeatherCaster.setLatitude(Double.parseDouble(latitude));
long period = TimeUnit.SECONDS.toMillis(observationPeriod);
long period = TimeUnit.HOURS.toMillis(observationPeriod);
pressureCache.setObservationPeriod(period);
bearingCache.setObservationPeriod(period);
temperatureCache.setObservationPeriod(period);
Expand Down Expand Up @@ -116,8 +107,7 @@ public void handleCommand(ChannelUID channelUID, Command command) {
case CHANNEL_CLOUDINESS:
logger.debug("Octa cloud level changed, updating forecast");
if (command instanceof QuantityType) {
@SuppressWarnings("unchecked")
QuantityType<Dimensionless> cloudiness = (QuantityType<Dimensionless>) command;
QuantityType<?> cloudiness = (QuantityType<?>) command;
scheduler.submit(() -> {
sagerWeatherCaster.setCloudLevel(cloudiness.intValue());
postNewForecast();
Expand All @@ -127,7 +117,7 @@ public void handleCommand(ChannelUID channelUID, Command command) {
case CHANNEL_IS_RAINING:
logger.debug("Rain status updated, updating forecast");
if (command instanceof OnOffType) {
OnOffType isRaining = ((OnOffType) command);
OnOffType isRaining = (OnOffType) command;
scheduler.submit(() -> {
sagerWeatherCaster.setRaining(isRaining == OnOffType.ON);
postNewForecast();
Expand All @@ -139,13 +129,13 @@ public void handleCommand(ChannelUID channelUID, Command command) {
case CHANNEL_RAIN_QTTY:
logger.debug("Rain status updated, updating forecast");
if (command instanceof QuantityType) {
QuantityType<?> newQtty = ((QuantityType<?>) command);
QuantityType<?> newQtty = (QuantityType<?>) command;
scheduler.submit(() -> {
sagerWeatherCaster.setRaining(newQtty.doubleValue() > 0);
postNewForecast();
});
} else if (command instanceof DecimalType) {
DecimalType newQtty = ((DecimalType) command);
DecimalType newQtty = (DecimalType) command;
scheduler.submit(() -> {
sagerWeatherCaster.setRaining(newQtty.doubleValue() > 0);
postNewForecast();
Expand Down Expand Up @@ -175,18 +165,12 @@ public void handleCommand(ChannelUID channelUID, Command command) {
.toUnit(HECTO(SIUnits.PASCAL));
if (newPressure != null) {
pressureCache.put(newPressure);
Optional<QuantityType<Pressure>> agedPressure = pressureCache.getAgedValue();
if (agedPressure.isPresent()) {
scheduler.submit(() -> {
sagerWeatherCaster.setPressure(newPressure.doubleValue(),
agedPressure.get().doubleValue());
updateChannelString(GROUP_OUTPUT, CHANNEL_PRESSURETREND,
String.valueOf(sagerWeatherCaster.getPressureEvolution()));
postNewForecast();
});
} else {
updateChannelString(GROUP_OUTPUT, CHANNEL_FORECAST, FORECAST_PENDING);
}
pressureCache.getAgedValue().ifPresentOrElse(pressure -> scheduler.submit(() -> {
sagerWeatherCaster.setPressure(newPressure.doubleValue(), pressure.doubleValue());
updateChannelString(GROUP_OUTPUT, CHANNEL_PRESSURETREND,
String.valueOf(sagerWeatherCaster.getPressureEvolution()));
postNewForecast();
}), () -> updateChannelString(GROUP_OUTPUT, CHANNEL_FORECAST, FORECAST_PENDING));
}
}
break;
Expand All @@ -200,12 +184,12 @@ public void handleCommand(ChannelUID channelUID, Command command) {
temperatureCache.put(newTemperature);
currentTemp = newTemperature.intValue();
Optional<QuantityType<Temperature>> agedTemperature = temperatureCache.getAgedValue();
if (agedTemperature.isPresent()) {
double delta = newTemperature.doubleValue() - agedTemperature.get().doubleValue();
agedTemperature.ifPresent(temperature -> {
double delta = newTemperature.doubleValue() - temperature.doubleValue();
String trend = (delta > 3) ? "1"
: (delta > 0.3) ? "2" : (delta > -0.3) ? "3" : (delta > -3) ? "4" : "5";
updateChannelString(GROUP_OUTPUT, CHANNEL_TEMPERATURETREND, trend);
}
});
}
}
break;
Expand All @@ -216,14 +200,14 @@ public void handleCommand(ChannelUID channelUID, Command command) {
QuantityType<Angle> newAngle = (QuantityType<Angle>) command;
bearingCache.put(newAngle);
Optional<QuantityType<Angle>> agedAngle = bearingCache.getAgedValue();
if (agedAngle.isPresent()) {
agedAngle.ifPresent(angle -> {
scheduler.submit(() -> {
sagerWeatherCaster.setBearing(newAngle.intValue(), agedAngle.get().intValue());
sagerWeatherCaster.setBearing(newAngle.intValue(), angle.intValue());
updateChannelString(GROUP_OUTPUT, CHANNEL_WINDEVOLUTION,
String.valueOf(sagerWeatherCaster.getWindEvolution()));
postNewForecast();
});
}
});
}
break;
default:
Expand Down Expand Up @@ -270,14 +254,14 @@ private void postNewForecast() {
updateChannelDecimal(GROUP_OUTPUT, CHANNEL_VELOCITY_BEAUFORT, predictedBeaufort);
}

protected void updateChannelString(String group, String channelId, String value) {
private void updateChannelString(String group, String channelId, String value) {
ChannelUID id = new ChannelUID(getThing().getUID(), group, channelId);
if (isLinked(id)) {
updateState(id, new StringType(value));
}
}

protected void updateChannelDecimal(String group, String channelId, int value) {
private void updateChannelDecimal(String group, String channelId, int value) {
ChannelUID id = new ChannelUID(getThing().getUID(), group, channelId);
if (isLinked(id)) {
updateState(id, new DecimalType(value));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
xmlns:binding="https://openhab.org/schemas/binding/v1.0.0"
xsi:schemaLocation="https://openhab.org/schemas/binding/v1.0.0 https://openhab.org/schemas/binding-1.0.0.xsd">

<name>SagerCaster Binding</name>
<description>The Sager Weathercaster is a scientific instrument for accurate prediction of the weather.</description>
<name>@text/bindingName</name>
<description>@text/bindingDescription</description>

</binding:binding>
Loading