All Downloads are FREE. Search and download functionalities are using the official Maven repository.

io.github.zeroone3010.yahueapi.SensorFactory Maven / Gradle / Ivy

There is a newer version: 3.0.0-rc
Show newest version
package io.github.zeroone3010.yahueapi;

import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.zeroone3010.yahueapi.domain.SensorDto;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Map;
import java.util.function.Supplier;

final class SensorFactory {
  private final Hue hue;
  private final ObjectMapper objectMapper;

  SensorFactory(final Hue hue, final ObjectMapper objectMapper) {
    this.hue = hue;
    this.objectMapper = objectMapper;
  }

  Sensor buildSensor(final String id, final SensorDto sensor, final String bridgeUri) {
    if (sensor == null) {
      throw new HueApiException("Sensor " + id + " cannot be found.");
    }

    final URL url = buildSensorUrl(bridgeUri, id);

    final SensorType type = SensorType.parseTypeString(sensor.getType());
    final Supplier> stateProvider = createStateProvider(url, id);
    switch (type) {
      case PRESENCE:
        return new PresenceSensorImpl(id, sensor, url, stateProvider);
      case TEMPERATURE:
        return new TemperatureSensorImpl(id, sensor, url, stateProvider);
      case DAYLIGHT:
        return new DaylightSensorImpl(id, sensor, url, stateProvider);
      case SWITCH:
        return new SwitchImpl(id, sensor, url, stateProvider);
      case AMBIENT_LIGHT:
        return new AmbientLightSensorImpl(id, sensor, url, stateProvider);
      default:
        return new BasicSensor(id, sensor, url, stateProvider);
    }
  }

  private Supplier> createStateProvider(final URL url, final String id) {
    return () -> {
      if (hue.isCaching()) {
        return hue.getRaw().getSensors().get(id).getState();
      }
      try {
        return objectMapper.readValue(url, SensorDto.class).getState();
      } catch (IOException e) {
        throw new HueApiException(e);
      }
    };
  }

  private static URL buildSensorUrl(final String bridgeUri, final String sensorId) {
    try {
      return new URL(bridgeUri + "sensors/" + sensorId);
    } catch (final MalformedURLException e) {
      throw new HueApiException(e);
    }
  }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy