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 8 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,8 @@
*/
package org.openhab.binding.sagercaster.internal;

import java.util.Set;

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

Expand All @@ -35,7 +37,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 +56,8 @@ 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 = Set.of("G", "K", "L", "R", "S", "T", "U", "W");
}
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 All @@ -105,9 +104,8 @@ public class SagerWeatherCaster {

@Activate
public SagerWeatherCaster() {
InputStream input = Thread.currentThread().getContextClassLoader()
.getResourceAsStream("/sagerForecaster.properties");
try {
try (InputStream input = Thread.currentThread().getContextClassLoader()
.getResourceAsStream("/sagerForecaster.properties")) {
forecaster.load(input);
} catch (IOException e) {
logger.warn("Error during Sager Forecaster startup", e);
Expand All @@ -120,50 +118,50 @@ public String[] getUsedDirections() {

public void setBearing(int newBearing, int oldBearing) {
int windEvol = sagerWindTrend(oldBearing, newBearing);
if ((windEvol != this.windEvolution) || (newBearing != currentBearing)) {
this.currentBearing = newBearing;
this.windEvolution = windEvol;
if ((windEvol != windEvolution) || (newBearing != currentBearing)) {
currentBearing = newBearing;
windEvolution = windEvol;
updatePrediction();
}
}

public void setPressure(double newPressure, double oldPressure) {
int newSagerPressure = sagerPressureLevel(newPressure);
int pressEvol = sagerPressureTrend(newPressure, oldPressure);
if ((pressEvol != this.pressureEvolution) || (newSagerPressure != sagerPressure)) {
this.sagerPressure = newSagerPressure;
this.pressureEvolution = pressEvol;
if ((pressEvol != pressureEvolution) || (newSagerPressure != sagerPressure)) {
sagerPressure = newSagerPressure;
pressureEvolution = pressEvol;
updatePrediction();
}
}

public void setCloudLevel(int cloudiness) {
this.cloudLevel = cloudiness;
cloudLevel = cloudiness;
sagerNubesUpdate();
}

public void setRaining(boolean raining) {
this.raining = raining;
public void setRaining(boolean isRaining) {
raining = isRaining;
sagerNubesUpdate();
}

public void setBeaufort(int beaufortIndex) {
if (currentBeaufort != beaufortIndex) {
this.currentBeaufort = beaufortIndex;
currentBeaufort = beaufortIndex;
updatePrediction();
}
}

public int getBeaufort() {
return this.currentBeaufort;
return currentBeaufort;
}

public int getWindEvolution() {
return this.windEvolution;
return windEvolution;
}

public int getPressureEvolution() {
return this.pressureEvolution;
return pressureEvolution;
}

private void sagerNubesUpdate() {
Expand All @@ -182,50 +180,43 @@ private void sagerNubesUpdate() {
result = 5; // raining
}
if (result != nubes) {
this.nubes = result;
nubes = result;
updatePrediction();
}
}

private static int sagerPressureLevel(double current) {
int result = 1;
if (current > 1029.46) {
result = 1;
return 1;
} else if (current > 1019.3) {
result = 2;
return 2;
} else if (current > 1012.53) {
result = 3;
return 3;
} else if (current > 1005.76) {
result = 4;
return 4;
} else if (current > 999) {
result = 5;
return 5;
} else if (current > 988.8) {
result = 6;
return 6;
} else if (current > 975.28) {
result = 7;
} else {
result = 8;
return 7;
}
return result;
return 8;
}

private static int sagerPressureTrend(double current, double historic) {
double evol = current - historic;
int result = 0;

if (evol > 1.4) {
result = 1; // Rising Rapidly
return 1; // Rising Rapidly
} else if (evol > 0.68) {
result = 2; // Rising Slowly
return 2; // Rising Slowly
} else if (evol > -0.68) {
result = 3; // Normal
return 3; // Normal
} else if (evol > -1.4) {
result = 4; // Decreasing Slowly
} else {
result = 5; // Decreasing Rapidly
return 4; // Decreasing Slowly
}

return result;
return 5; // Decreasing Rapidly
}

private static int sagerWindTrend(double historic, double position) {
Expand All @@ -241,7 +232,7 @@ private static int sagerWindTrend(double historic, double position) {

private String getCompass() {
double step = 360.0 / NTZDIRECTIONS.length;
double b = Math.floor((this.currentBearing + (step / 2.0)) / step);
double b = Math.floor((currentBearing + (step / 2.0)) / step);
return NTZDIRECTIONS[(int) (b % NTZDIRECTIONS.length)];
}

Expand Down Expand Up @@ -335,36 +326,32 @@ public String getForecast() {
if (prevision.isPresent()) {
char forecast = prevision.get().zForecast;
return Character.toString(forecast);
} else {
return "-";
}
return "-";
}

public String getWindVelocity() {
if (prevision.isPresent()) {
char windVelocity = prevision.get().zWindVelocity;
return Character.toString(windVelocity);
} else {
return "-";
}
return "-";
}

public String getWindDirection() {
if (prevision.isPresent()) {
int direction = prevision.get().zWindDirection;
return String.valueOf(direction);
} else {
return "-";
}
return "-";
}

public String getWindDirection2() {
if (prevision.isPresent()) {
int direction = prevision.get().zWindDirection2;
return String.valueOf(direction);
} else {
return "-";
}
return "-";
}

public void setLatitude(double latitude) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,9 @@

import static org.openhab.binding.sagercaster.internal.SagerCasterBindingConstants.*;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

Expand All @@ -28,8 +27,8 @@
import org.openhab.core.config.discovery.DiscoveryService;
import org.openhab.core.i18n.LocationProvider;
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 @@ -43,20 +42,23 @@
@NonNullByDefault
@Component(service = DiscoveryService.class, configurationPid = "discovery.sagercaster")
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 @Nullable PointType previousLocation;
private static final ThingUID SAGER_CASTER_THING = new ThingUID(THING_TYPE_SAGERCASTER, LOCAL);

private final Logger logger = LoggerFactory.getLogger(SagerCasterDiscoveryService.class);
private final LocationProvider locationProvider;

private static final ThingUID sagerCasterThing = new ThingUID(THING_TYPE_SAGERCASTER, LOCAL);
private @Nullable ScheduledFuture<?> discoveryJob;
private @Nullable PointType previousLocation;

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

@Override
Expand All @@ -82,8 +84,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 +101,19 @@ protected void startBackgroundDiscovery() {

@Override
protected void stopBackgroundDiscovery() {
ScheduledFuture<?> localJob = 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(SAGER_CASTER_THING).withLabel("Local Weather Forecast")
lolodomo marked this conversation as resolved.
Show resolved Hide resolved
.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 @@ -37,11 +37,10 @@ public void setObservationPeriod(long eldestAge) {
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());
}
values.keySet().stream().filter(key -> key < now - eldestAge).findFirst().ifPresent(eldest -> {
agedValue = Optional.ofNullable(values.get(eldest));
values.entrySet().removeIf(map -> map.getKey() <= eldest);
});
}

public Optional<T> getAgedValue() {
Expand Down
Loading