86 lines
2.7 KiB
Java
86 lines
2.7 KiB
Java
package ch.usi.inf.sa4.sanmarinoes.smarthut.service;
|
|
|
|
import ch.usi.inf.sa4.sanmarinoes.smarthut.models.Sensor;
|
|
import ch.usi.inf.sa4.sanmarinoes.smarthut.models.SensorRepository;
|
|
import ch.usi.inf.sa4.sanmarinoes.smarthut.socket.SensorSocketEndpoint;
|
|
import java.math.BigDecimal;
|
|
import java.math.RoundingMode;
|
|
import java.util.Random;
|
|
import org.springframework.beans.factory.annotation.Autowired;
|
|
import org.springframework.stereotype.Component;
|
|
|
|
@Component
|
|
public class SensorService {
|
|
|
|
private final SensorRepository sensorRepository;
|
|
|
|
private final DeviceService deviceService;
|
|
|
|
private final ThermostatService thermostatService;
|
|
|
|
private final SensorSocketEndpoint endpoint;
|
|
|
|
private final Random ran = new Random();
|
|
|
|
@Autowired
|
|
public SensorService(
|
|
SensorRepository sensorRepository,
|
|
DeviceService deviceService,
|
|
ThermostatService thermostatService,
|
|
SensorSocketEndpoint endpoint) {
|
|
this.sensorRepository = sensorRepository;
|
|
this.deviceService = deviceService;
|
|
this.thermostatService = thermostatService;
|
|
this.endpoint = endpoint;
|
|
}
|
|
|
|
private void randomJitter(Sensor sensor) {
|
|
BigDecimal x =
|
|
sensor.getTypical()
|
|
.subtract(
|
|
sensor.getError()
|
|
.divide(BigDecimal.valueOf(2), RoundingMode.CEILING))
|
|
.add(
|
|
BigDecimal.valueOf(
|
|
ran.nextDouble() * sensor.getError().doubleValue() * 2));
|
|
|
|
updateValueFromSensor(sensor, x);
|
|
}
|
|
|
|
public void sensorFakeUpdate() {
|
|
sensorRepository.findAll().forEach(this::randomJitter);
|
|
thermostatService.updateStates();
|
|
}
|
|
|
|
/**
|
|
* Updates the sensor with new measurement and propagates update through websocket
|
|
*
|
|
* @param sensor the sensor to update
|
|
* @return the updated sensor
|
|
*/
|
|
public Sensor update(Sensor sensor) {
|
|
sensor =
|
|
deviceService.saveAsOwner(
|
|
sensor, sensorRepository.findUser(sensor.getId()).getUsername());
|
|
endpoint.queueDeviceUpdate(
|
|
sensor, sensorRepository.findUser(sensor.getId()), false, null, false);
|
|
return sensor;
|
|
}
|
|
|
|
public Sensor updateValueFromSensor(Sensor sensor, BigDecimal value) {
|
|
sensor.setValue(value);
|
|
return update(sensor);
|
|
}
|
|
|
|
public Sensor updateSimulationFromSensor(Sensor sensor, BigDecimal error, BigDecimal typical) {
|
|
if (error != null) {
|
|
sensor.setError(error);
|
|
}
|
|
|
|
if (typical != null) {
|
|
sensor.setTypical(typical);
|
|
}
|
|
return update(sensor);
|
|
}
|
|
}
|