Search in sources :

Example 1 with SmartherGatewayException

use of org.openhab.binding.bticinosmarther.internal.api.exception.SmartherGatewayException 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 SmartherGatewayException

use of org.openhab.binding.bticinosmarther.internal.api.exception.SmartherGatewayException 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 SmartherGatewayException

use of org.openhab.binding.bticinosmarther.internal.api.exception.SmartherGatewayException in project openhab-addons by openhab.

the class SmartherApi method getModulePrograms.

/**
 * Returns the automatic mode programs registered for the given chronothermostat module.
 *
 * @param plantId
 *            the identifier of the plant
 * @param moduleId
 *            the identifier of the chronothermostat module inside the plant
 *
 * @return the list of registered programs, or an empty {@link List} in case of no programs found
 *
 * @throws {@link SmartherGatewayException}
 *             in case of communication issues with the API gateway
 */
public List<Program> getModulePrograms(String plantId, String moduleId) throws SmartherGatewayException {
    try {
        final ContentResponse response = requestModule(GET, plantId, moduleId, PATH_PROGRAMS, null);
        final ModuleStatus moduleStatus = ModelUtil.gsonInstance().fromJson(response.getContentAsString(), ModuleStatus.class);
        final Chronothermostat chronothermostat = moduleStatus.toChronothermostat();
        return (chronothermostat != null) ? chronothermostat.getPrograms() : Collections.emptyList();
    } catch (JsonSyntaxException e) {
        throw new SmartherGatewayException(e.getMessage());
    }
}
Also used : SmartherGatewayException(org.openhab.binding.bticinosmarther.internal.api.exception.SmartherGatewayException) JsonSyntaxException(com.google.gson.JsonSyntaxException) ContentResponse(org.eclipse.jetty.client.api.ContentResponse) ModuleStatus(org.openhab.binding.bticinosmarther.internal.api.dto.ModuleStatus) Chronothermostat(org.openhab.binding.bticinosmarther.internal.api.dto.Chronothermostat)

Example 4 with SmartherGatewayException

use of org.openhab.binding.bticinosmarther.internal.api.exception.SmartherGatewayException in project openhab-addons by openhab.

the class SmartherApi method subscribePlant.

/**
 * Subscribes a plant to the C2C Webhook to start receiving modules status notifications.
 *
 * @param plantId
 *            the identifier of the plant to be subscribed
 * @param notificationUrl
 *            the url notifications will have to be sent to for the given plant
 *
 * @return the identifier this subscription has been registered under
 *
 * @throws {@link SmartherGatewayException}
 *             in case of communication issues with the API gateway
 */
public String subscribePlant(String plantId, String notificationUrl) throws SmartherGatewayException {
    try {
        // Prepare request payload
        Map<String, Object> rootMap = new IdentityHashMap<String, Object>();
        rootMap.put(ATTR_ENDPOINT_URL, notificationUrl);
        final String jsonPayload = ModelUtil.gsonInstance().toJson(rootMap);
        // Send request to server
        final ContentResponse response = requestBasic(POST, String.format(PATH_SUBSCRIBE, plantId), jsonPayload);
        // Handle response payload
        final Subscription subscription = ModelUtil.gsonInstance().fromJson(response.getContentAsString(), Subscription.class);
        return subscription.getSubscriptionId();
    } catch (JsonSyntaxException e) {
        throw new SmartherGatewayException(e.getMessage());
    }
}
Also used : SmartherGatewayException(org.openhab.binding.bticinosmarther.internal.api.exception.SmartherGatewayException) JsonSyntaxException(com.google.gson.JsonSyntaxException) ContentResponse(org.eclipse.jetty.client.api.ContentResponse) IdentityHashMap(java.util.IdentityHashMap) Subscription(org.openhab.binding.bticinosmarther.internal.api.dto.Subscription)

Example 5 with SmartherGatewayException

use of org.openhab.binding.bticinosmarther.internal.api.exception.SmartherGatewayException in project openhab-addons by openhab.

the class SmartherApi method setModuleStatus.

/**
 * Sends new settings to be applied to a given chronothermostat module.
 *
 * @param settings
 *            the module settings to be applied
 *
 * @return {@code true} if the settings have been successfully applied, {@code false} otherwise
 *
 * @throws {@link SmartherGatewayException}
 *             in case of communication issues with the API gateway
 */
public boolean setModuleStatus(ModuleSettings settings) throws SmartherGatewayException {
    // Prepare request payload
    Map<String, Object> rootMap = new IdentityHashMap<>();
    rootMap.put(ATTR_FUNCTION, settings.getFunction().getValue());
    rootMap.put(ATTR_MODE, settings.getMode().getValue());
    switch(settings.getMode()) {
        case AUTOMATIC:
            // {"function":"heating","mode":"automatic","programs":[{"number":0}]}
            Map<String, Integer> programMap = new IdentityHashMap<String, Integer>();
            programMap.put(ATTR_NUMBER, Integer.valueOf(settings.getProgram()));
            List<Map<String, Integer>> programsList = new ArrayList<>();
            programsList.add(programMap);
            rootMap.put(ATTR_PROGRAMS, programsList);
            break;
        case MANUAL:
            // {"function":"heating","mode":"manual","setPoint":{"value":0.0,"unit":"C"},"activationTime":"X"}
            QuantityType<Temperature> newTemperature = settings.getSetPointTemperature(SIUnits.CELSIUS);
            if (newTemperature == null) {
                throw new SmartherGatewayException("Invalid temperature unit transformation");
            }
            Map<String, Object> setPointMap = new IdentityHashMap<String, Object>();
            setPointMap.put(ATTR_VALUE, newTemperature.doubleValue());
            setPointMap.put(ATTR_UNIT, MeasureUnit.CELSIUS.getValue());
            rootMap.put(ATTR_SETPOINT, setPointMap);
            rootMap.put(ATTR_ACTIVATION_TIME, settings.getActivationTime());
            break;
        case BOOST:
            // {"function":"heating","mode":"boost","activationTime":"X"}
            rootMap.put(ATTR_ACTIVATION_TIME, settings.getActivationTime());
            break;
        case OFF:
            // {"function":"heating","mode":"off"}
            break;
        case PROTECTION:
            // {"function":"heating","mode":"protection"}
            break;
    }
    final String jsonPayload = ModelUtil.gsonInstance().toJson(rootMap);
    // Send request to server
    final ContentResponse response = requestModule(POST, settings.getPlantId(), settings.getModuleId(), jsonPayload);
    return (response.getStatus() == HttpStatus.OK_200);
}
Also used : Temperature(javax.measure.quantity.Temperature) ContentResponse(org.eclipse.jetty.client.api.ContentResponse) IdentityHashMap(java.util.IdentityHashMap) ArrayList(java.util.ArrayList) SmartherGatewayException(org.openhab.binding.bticinosmarther.internal.api.exception.SmartherGatewayException) Map(java.util.Map) IdentityHashMap(java.util.IdentityHashMap)

Aggregations

SmartherGatewayException (org.openhab.binding.bticinosmarther.internal.api.exception.SmartherGatewayException)10 ContentResponse (org.eclipse.jetty.client.api.ContentResponse)6 ModuleStatus (org.openhab.binding.bticinosmarther.internal.api.dto.ModuleStatus)6 JsonSyntaxException (com.google.gson.JsonSyntaxException)5 IOException (java.io.IOException)4 ArrayList (java.util.ArrayList)4 Subscription (org.openhab.binding.bticinosmarther.internal.api.dto.Subscription)4 SmartherAuthorizationException (org.openhab.binding.bticinosmarther.internal.api.exception.SmartherAuthorizationException)4 ModuleSettings (org.openhab.binding.bticinosmarther.internal.model.ModuleSettings)4 Collections (java.util.Collections)3 IdentityHashMap (java.util.IdentityHashMap)3 List (java.util.List)3 NonNullByDefault (org.eclipse.jdt.annotation.NonNullByDefault)3 Nullable (org.eclipse.jdt.annotation.Nullable)3 HttpClient (org.eclipse.jetty.client.HttpClient)3 SmartherBindingConstants (org.openhab.binding.bticinosmarther.internal.SmartherBindingConstants)3 Module (org.openhab.binding.bticinosmarther.internal.api.dto.Module)3 Plant (org.openhab.binding.bticinosmarther.internal.api.dto.Plant)3 Program (org.openhab.binding.bticinosmarther.internal.api.dto.Program)3 SmartherBridgeConfiguration (org.openhab.binding.bticinosmarther.internal.config.SmartherBridgeConfiguration)3