Search in sources :

Example 1 with ExpiringCache

use of org.openhab.core.cache.ExpiringCache in project openhab-addons by openhab.

the class SmartherBridgeHandler method unregisterNotification.

@Override
public synchronized void unregisterNotification(String plantId) throws SmartherGatewayException {
    if (!config.isUseNotifications()) {
        return;
    }
    final ExpiringCache<List<Location>> localLocationCache = this.locationCache;
    if (localLocationCache != null) {
        List<Location> locations = localLocationCache.getValue();
        final long remainingModules = getThing().getThings().stream().map(t -> (SmartherModuleHandler) t.getHandler()).filter(h -> h.getPlantId().equals(plantId)).count();
        if (locations != null && remainingModules == 0) {
            final Optional<Location> maybeLocation = locations.stream().filter(l -> l.getPlantId().equals(plantId)).findFirst();
            if (maybeLocation.isPresent()) {
                Location location = maybeLocation.get();
                final String subscriptionId = location.getSubscriptionId();
                if (location.hasSubscription() && (subscriptionId != null)) {
                    // Call gateway to unregister plant subscription
                    unsubscribePlant(plantId, subscriptionId);
                    logger.debug("Bridge[{}] Notification unregistered: [plantId={}, subscriptionId={}]", thing.getUID(), plantId, subscriptionId);
                    // Remove the subscription from notifications list
                    List<String> notifications = config.removeNotification(subscriptionId);
                    // Save the updated notifications list back to bridge config
                    Configuration configuration = editConfiguration();
                    configuration.put(PROPERTY_NOTIFICATIONS, notifications);
                    updateConfiguration(configuration);
                    // Update the local locationCache with the removed data
                    locations.stream().forEach(l -> {
                        if (l.getPlantId().equals(plantId)) {
                            l.unsetSubscription();
                        }
                    });
                    localLocationCache.putValue(locations);
                }
            }
        }
    }
}
Also used : URISyntaxException(java.net.URISyntaxException) SmartherGatewayException(org.openhab.binding.bticinosmarther.internal.api.exception.SmartherGatewayException) LoggerFactory(org.slf4j.LoggerFactory) OnOffType(org.openhab.core.library.types.OnOffType) Plant(org.openhab.binding.bticinosmarther.internal.api.dto.Plant) Program(org.openhab.binding.bticinosmarther.internal.api.dto.Program) StringUtil(org.openhab.binding.bticinosmarther.internal.util.StringUtil) InetAddress(java.net.InetAddress) HttpClient(org.eclipse.jetty.client.HttpClient) Location(org.openhab.binding.bticinosmarther.internal.api.dto.Location) Future(java.util.concurrent.Future) AccessTokenRefreshListener(org.openhab.core.auth.client.oauth2.AccessTokenRefreshListener) Nullable(org.eclipse.jdt.annotation.Nullable) Configuration(org.openhab.core.config.core.Configuration) Duration(java.time.Duration) Subscription(org.openhab.binding.bticinosmarther.internal.api.dto.Subscription) URI(java.net.URI) Notification(org.openhab.binding.bticinosmarther.internal.api.dto.Notification) SmartherNotificationHandler(org.openhab.binding.bticinosmarther.internal.account.SmartherNotificationHandler) NonNullByDefault(org.eclipse.jdt.annotation.NonNullByDefault) SmartherBindingConstants(org.openhab.binding.bticinosmarther.internal.SmartherBindingConstants) ModuleStatus(org.openhab.binding.bticinosmarther.internal.api.dto.ModuleStatus) OAuthResponseException(org.openhab.core.auth.client.oauth2.OAuthResponseException) Collection(java.util.Collection) Collectors(java.util.stream.Collectors) Channel(org.openhab.core.thing.Channel) List(java.util.List) SmartherAuthorizationException(org.openhab.binding.bticinosmarther.internal.api.exception.SmartherAuthorizationException) SmartherBridgeConfiguration(org.openhab.binding.bticinosmarther.internal.config.SmartherBridgeConfiguration) Optional(java.util.Optional) BaseBridgeHandler(org.openhab.core.thing.binding.BaseBridgeHandler) ExpiringCache(org.openhab.core.cache.ExpiringCache) BridgeStatus(org.openhab.binding.bticinosmarther.internal.model.BridgeStatus) OAuthException(org.openhab.core.auth.client.oauth2.OAuthException) ThingHandlerService(org.openhab.core.thing.binding.ThingHandlerService) SmartherAccountHandler(org.openhab.binding.bticinosmarther.internal.account.SmartherAccountHandler) ArrayList(java.util.ArrayList) SmartherApi(org.openhab.binding.bticinosmarther.internal.api.SmartherApi) ModuleSettings(org.openhab.binding.bticinosmarther.internal.model.ModuleSettings) ChannelUID(org.openhab.core.thing.ChannelUID) DecimalType(org.openhab.core.library.types.DecimalType) ThingStatus(org.openhab.core.thing.ThingStatus) Command(org.openhab.core.types.Command) Logger(org.slf4j.Logger) ThingUID(org.openhab.core.thing.ThingUID) State(org.openhab.core.types.State) RefreshType(org.openhab.core.types.RefreshType) IOException(java.io.IOException) ThingStatusDetail(org.openhab.core.thing.ThingStatusDetail) UnknownHostException(java.net.UnknownHostException) TimeUnit(java.util.concurrent.TimeUnit) SmartherModuleDiscoveryService(org.openhab.binding.bticinosmarther.internal.discovery.SmartherModuleDiscoveryService) Sender(org.openhab.binding.bticinosmarther.internal.api.dto.Sender) AccessTokenResponse(org.openhab.core.auth.client.oauth2.AccessTokenResponse) OAuthClientService(org.openhab.core.auth.client.oauth2.OAuthClientService) Module(org.openhab.binding.bticinosmarther.internal.api.dto.Module) OAuthFactory(org.openhab.core.auth.client.oauth2.OAuthFactory) Collections(java.util.Collections) Bridge(org.openhab.core.thing.Bridge) Configuration(org.openhab.core.config.core.Configuration) SmartherBridgeConfiguration(org.openhab.binding.bticinosmarther.internal.config.SmartherBridgeConfiguration) List(java.util.List) ArrayList(java.util.ArrayList) Location(org.openhab.binding.bticinosmarther.internal.api.dto.Location)

Example 2 with ExpiringCache

use of org.openhab.core.cache.ExpiringCache in project openhab-addons by openhab.

the class SmartherBridgeHandler method registerNotification.

@Override
public synchronized void registerNotification(String plantId) throws SmartherGatewayException {
    if (!config.isUseNotifications()) {
        return;
    }
    final ExpiringCache<List<Location>> localLocationCache = this.locationCache;
    if (localLocationCache != null) {
        List<Location> locations = localLocationCache.getValue();
        if (locations != null) {
            final Optional<Location> maybeLocation = locations.stream().filter(l -> l.getPlantId().equals(plantId)).findFirst();
            if (maybeLocation.isPresent()) {
                Location location = maybeLocation.get();
                if (!location.hasSubscription()) {
                    // Validate notification Url (must be non-null and https)
                    final String notificationUrl = config.getNotificationUrl();
                    if (isValidNotificationUrl(notificationUrl)) {
                        // Call gateway to register plant subscription
                        String subscriptionId = subscribePlant(plantId, config.getNotificationUrl());
                        logger.debug("Bridge[{}] Notification registered: [plantId={}, subscriptionId={}]", thing.getUID(), plantId, subscriptionId);
                        // Add the new subscription to notifications list
                        List<String> notifications = config.addNotification(subscriptionId);
                        // Save the updated notifications list back to bridge config
                        Configuration configuration = editConfiguration();
                        configuration.put(PROPERTY_NOTIFICATIONS, notifications);
                        updateConfiguration(configuration);
                        // Update the local locationCache with the added data
                        locations.stream().forEach(l -> {
                            if (l.getPlantId().equals(plantId)) {
                                l.setSubscription(subscriptionId, config.getNotificationUrl());
                            }
                        });
                        localLocationCache.putValue(locations);
                    } else {
                        logger.warn("Bridge[{}] Invalid notification Url [{}]: must be non-null, public https address", thing.getUID(), notificationUrl);
                    }
                }
            }
        }
    }
}
Also used : URISyntaxException(java.net.URISyntaxException) SmartherGatewayException(org.openhab.binding.bticinosmarther.internal.api.exception.SmartherGatewayException) LoggerFactory(org.slf4j.LoggerFactory) OnOffType(org.openhab.core.library.types.OnOffType) Plant(org.openhab.binding.bticinosmarther.internal.api.dto.Plant) Program(org.openhab.binding.bticinosmarther.internal.api.dto.Program) StringUtil(org.openhab.binding.bticinosmarther.internal.util.StringUtil) InetAddress(java.net.InetAddress) HttpClient(org.eclipse.jetty.client.HttpClient) Location(org.openhab.binding.bticinosmarther.internal.api.dto.Location) Future(java.util.concurrent.Future) AccessTokenRefreshListener(org.openhab.core.auth.client.oauth2.AccessTokenRefreshListener) Nullable(org.eclipse.jdt.annotation.Nullable) Configuration(org.openhab.core.config.core.Configuration) Duration(java.time.Duration) Subscription(org.openhab.binding.bticinosmarther.internal.api.dto.Subscription) URI(java.net.URI) Notification(org.openhab.binding.bticinosmarther.internal.api.dto.Notification) SmartherNotificationHandler(org.openhab.binding.bticinosmarther.internal.account.SmartherNotificationHandler) NonNullByDefault(org.eclipse.jdt.annotation.NonNullByDefault) SmartherBindingConstants(org.openhab.binding.bticinosmarther.internal.SmartherBindingConstants) ModuleStatus(org.openhab.binding.bticinosmarther.internal.api.dto.ModuleStatus) OAuthResponseException(org.openhab.core.auth.client.oauth2.OAuthResponseException) Collection(java.util.Collection) Collectors(java.util.stream.Collectors) Channel(org.openhab.core.thing.Channel) List(java.util.List) SmartherAuthorizationException(org.openhab.binding.bticinosmarther.internal.api.exception.SmartherAuthorizationException) SmartherBridgeConfiguration(org.openhab.binding.bticinosmarther.internal.config.SmartherBridgeConfiguration) Optional(java.util.Optional) BaseBridgeHandler(org.openhab.core.thing.binding.BaseBridgeHandler) ExpiringCache(org.openhab.core.cache.ExpiringCache) BridgeStatus(org.openhab.binding.bticinosmarther.internal.model.BridgeStatus) OAuthException(org.openhab.core.auth.client.oauth2.OAuthException) ThingHandlerService(org.openhab.core.thing.binding.ThingHandlerService) SmartherAccountHandler(org.openhab.binding.bticinosmarther.internal.account.SmartherAccountHandler) ArrayList(java.util.ArrayList) SmartherApi(org.openhab.binding.bticinosmarther.internal.api.SmartherApi) ModuleSettings(org.openhab.binding.bticinosmarther.internal.model.ModuleSettings) ChannelUID(org.openhab.core.thing.ChannelUID) DecimalType(org.openhab.core.library.types.DecimalType) ThingStatus(org.openhab.core.thing.ThingStatus) Command(org.openhab.core.types.Command) Logger(org.slf4j.Logger) ThingUID(org.openhab.core.thing.ThingUID) State(org.openhab.core.types.State) RefreshType(org.openhab.core.types.RefreshType) IOException(java.io.IOException) ThingStatusDetail(org.openhab.core.thing.ThingStatusDetail) UnknownHostException(java.net.UnknownHostException) TimeUnit(java.util.concurrent.TimeUnit) SmartherModuleDiscoveryService(org.openhab.binding.bticinosmarther.internal.discovery.SmartherModuleDiscoveryService) Sender(org.openhab.binding.bticinosmarther.internal.api.dto.Sender) AccessTokenResponse(org.openhab.core.auth.client.oauth2.AccessTokenResponse) OAuthClientService(org.openhab.core.auth.client.oauth2.OAuthClientService) Module(org.openhab.binding.bticinosmarther.internal.api.dto.Module) OAuthFactory(org.openhab.core.auth.client.oauth2.OAuthFactory) Collections(java.util.Collections) Bridge(org.openhab.core.thing.Bridge) Configuration(org.openhab.core.config.core.Configuration) SmartherBridgeConfiguration(org.openhab.binding.bticinosmarther.internal.config.SmartherBridgeConfiguration) List(java.util.List) ArrayList(java.util.ArrayList) Location(org.openhab.binding.bticinosmarther.internal.api.dto.Location)

Example 3 with ExpiringCache

use of org.openhab.core.cache.ExpiringCache in project openhab-addons by openhab.

the class SmartherBridgeHandler method initialize.

// ===========================================================================
// 
// Bridge thing lifecycle management methods
// 
// ===========================================================================
@Override
public void initialize() {
    logger.debug("Bridge[{}] Initialize handler", thing.getUID());
    this.config = getConfigAs(SmartherBridgeConfiguration.class);
    if (StringUtil.isBlank(config.getSubscriptionKey())) {
        updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, "The 'Subscription Key' property is not set or empty. If you have an older thing please recreate it.");
        return;
    }
    if (StringUtil.isBlank(config.getClientId())) {
        updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, "The 'Client Id' property is not set or empty. If you have an older thing please recreate it.");
        return;
    }
    if (StringUtil.isBlank(config.getClientSecret())) {
        updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, "The 'Client Secret' property is not set or empty. If you have an older thing please recreate it.");
        return;
    }
    // Initialize OAuth2 authentication support
    final OAuthClientService localOAuthService = oAuthFactory.createOAuthClientService(thing.getUID().getAsString(), SMARTHER_API_TOKEN_URL, SMARTHER_AUTHORIZE_URL, config.getClientId(), config.getClientSecret(), SMARTHER_API_SCOPES, false);
    localOAuthService.addAccessTokenRefreshListener(SmartherBridgeHandler.this);
    this.oAuthService = localOAuthService;
    // Initialize Smarther Api
    final SmartherApi localSmartherApi = new SmartherApi(localOAuthService, config.getSubscriptionKey(), scheduler, httpClient);
    this.smartherApi = localSmartherApi;
    // Initialize locations (plant Ids) local cache
    final ExpiringCache<List<Location>> localLocationCache = new ExpiringCache<>(Duration.ofMinutes(config.getStatusRefreshPeriod()), this::locationCacheAction);
    this.locationCache = localLocationCache;
    // Initialize bridge local status
    final BridgeStatus localBridgeStatus = new BridgeStatus();
    this.bridgeStatus = localBridgeStatus;
    updateStatus(ThingStatus.UNKNOWN);
    schedulePoll();
    logger.debug("Bridge[{}] Finished initializing!", thing.getUID());
}
Also used : SmartherApi(org.openhab.binding.bticinosmarther.internal.api.SmartherApi) ExpiringCache(org.openhab.core.cache.ExpiringCache) OAuthClientService(org.openhab.core.auth.client.oauth2.OAuthClientService) List(java.util.List) ArrayList(java.util.ArrayList) BridgeStatus(org.openhab.binding.bticinosmarther.internal.model.BridgeStatus) SmartherBridgeConfiguration(org.openhab.binding.bticinosmarther.internal.config.SmartherBridgeConfiguration)

Example 4 with ExpiringCache

use of org.openhab.core.cache.ExpiringCache in project openhab-addons by openhab.

the class SmartherModuleHandler method initialize.

// ===========================================================================
// 
// Chronothermostat thing lifecycle management methods
// 
// ===========================================================================
@Override
public void initialize() {
    logger.debug("Module[{}] Initialize handler", thing.getUID());
    final Bridge localBridge = getBridge();
    if (localBridge == null) {
        updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.BRIDGE_UNINITIALIZED);
        return;
    }
    final SmartherBridgeHandler localBridgeHandler = (SmartherBridgeHandler) localBridge.getHandler();
    this.bridgeHandler = localBridgeHandler;
    if (localBridgeHandler == null) {
        updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, String.format("Missing configuration from the Smarther Bridge (UID:%s). Fix configuration or report if this problem remains.", localBridge.getBridgeUID()));
        return;
    }
    this.config = getConfigAs(SmartherModuleConfiguration.class);
    if (StringUtil.isBlank(config.getPlantId())) {
        updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, "The 'Plant Id' property is not set or empty. If you have an older thing please recreate it.");
        return;
    }
    if (StringUtil.isBlank(config.getModuleId())) {
        updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, "The 'Module Id' property is not set or empty. If you have an older thing please recreate it.");
        return;
    }
    if (config.getProgramsRefreshPeriod() <= 0) {
        updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, "The 'Programs Refresh Period' must be > 0. If you have an older thing please recreate it.");
        return;
    }
    if (config.getStatusRefreshPeriod() <= 0) {
        updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, "The 'Module Status Refresh Period' must be > 0. If you have an older thing please recreate it.");
        return;
    }
    // Initialize automatic mode programs local cache
    final ExpiringCache<List<Program>> localProgramCache = new ExpiringCache<>(Duration.ofHours(config.getProgramsRefreshPeriod()), this::programCacheAction);
    this.programCache = localProgramCache;
    // Initialize module local settings
    final ModuleSettings localModuleSettings = new ModuleSettings(config.getPlantId(), config.getModuleId());
    this.moduleSettings = localModuleSettings;
    updateStatus(ThingStatus.UNKNOWN);
    scheduleJob();
    schedulePoll();
    logger.debug("Module[{}] Finished initializing!", thing.getUID());
}
Also used : ExpiringCache(org.openhab.core.cache.ExpiringCache) ModuleSettings(org.openhab.binding.bticinosmarther.internal.model.ModuleSettings) List(java.util.List) Bridge(org.openhab.core.thing.Bridge) SmartherModuleConfiguration(org.openhab.binding.bticinosmarther.internal.config.SmartherModuleConfiguration)

Aggregations

List (java.util.List)4 ArrayList (java.util.ArrayList)3 SmartherApi (org.openhab.binding.bticinosmarther.internal.api.SmartherApi)3 SmartherBridgeConfiguration (org.openhab.binding.bticinosmarther.internal.config.SmartherBridgeConfiguration)3 BridgeStatus (org.openhab.binding.bticinosmarther.internal.model.BridgeStatus)3 ModuleSettings (org.openhab.binding.bticinosmarther.internal.model.ModuleSettings)3 OAuthClientService (org.openhab.core.auth.client.oauth2.OAuthClientService)3 IOException (java.io.IOException)2 InetAddress (java.net.InetAddress)2 URI (java.net.URI)2 URISyntaxException (java.net.URISyntaxException)2 UnknownHostException (java.net.UnknownHostException)2 Duration (java.time.Duration)2 Collection (java.util.Collection)2 Collections (java.util.Collections)2 Optional (java.util.Optional)2 Future (java.util.concurrent.Future)2 TimeUnit (java.util.concurrent.TimeUnit)2 Collectors (java.util.stream.Collectors)2 NonNullByDefault (org.eclipse.jdt.annotation.NonNullByDefault)2