Implemented fake updates

This commit is contained in:
Claudio Maggioni 2020-03-15 14:49:51 +01:00
parent cf940df6b2
commit 620c196393
8 changed files with 106 additions and 27 deletions

View File

@ -3,8 +3,10 @@ package ch.usi.inf.sa4.sanmarinoes.smarthut;
import org.springframework.boot.SpringApplication; import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories; import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.scheduling.annotation.EnableScheduling;
@SpringBootApplication @SpringBootApplication
@EnableScheduling
@EnableJpaRepositories("ch.usi.inf.sa4.sanmarinoes.smarthut.models") @EnableJpaRepositories("ch.usi.inf.sa4.sanmarinoes.smarthut.models")
public class SmarthutApplication { public class SmarthutApplication {
public static void main(String[] args) { public static void main(String[] args) {

View File

@ -42,6 +42,22 @@ public class MotionSensorController {
return motionSensorService.save(newMS); return motionSensorService.save(newMS);
} }
/**
* Updates detection status of given motion sensor and propagates update throgh socket
*
* @param sensor the motion sensor to update
* @param detected the new detection status
* @return the updated motion sensor
*/
public MotionSensor updateDetectionFromMotionSensor(MotionSensor sensor, boolean detected) {
sensor.setDetected(detected);
final MotionSensor toReturn = motionSensorService.save(sensor);
sensorSocketEndpoint.broadcast(sensor, motionSensorService.findUser(sensor.getId()));
return toReturn;
}
@PutMapping("/{id}/detect") @PutMapping("/{id}/detect")
public MotionSensor updateDetection( public MotionSensor updateDetection(
@PathVariable("id") Long sensorId, @PathVariable("id") Long sensorId,
@ -49,16 +65,11 @@ public class MotionSensorController {
final Principal principal) final Principal principal)
throws NotFoundException { throws NotFoundException {
final MotionSensor sensor = return updateDetectionFromMotionSensor(
motionSensorService motionSensorService
.findByIdAndUsername(sensorId, principal.getName()) .findByIdAndUsername(sensorId, principal.getName())
.orElseThrow(NotFoundException::new); .orElseThrow(NotFoundException::new),
sensor.setDetected(detected); detected);
final MotionSensor toReturn = motionSensorService.save(sensor);
sensorSocketEndpoint.broadcast(sensor, motionSensorService.findUser(sensorId));
return toReturn;
} }
@DeleteMapping("/{id}") @DeleteMapping("/{id}")

View File

@ -45,25 +45,33 @@ public class SensorController {
return sensorRepository.save(newSensor); return sensorRepository.save(newSensor);
} }
/**
* Updates the sensor with new measurement and propagates update through websocket
*
* @param sensor the sensor to update
* @param value the new measurement
* @return the updated sensor
*/
public Sensor updateValueFromSensor(Sensor sensor, BigDecimal value) {
sensor.setValue(value);
final Sensor toReturn = sensorRepository.save(sensor);
sensorSocketEndpoint.broadcast(sensor, sensorRepository.findUser(sensor.getId()));
return toReturn;
}
@PutMapping("/{id}/value") @PutMapping("/{id}/value")
public Sensor updateValue( public Sensor updateValue(
@PathVariable("id") Long sensorId, @PathVariable("id") Long sensorId,
@RequestParam("value") BigDecimal value, @RequestParam("value") BigDecimal value,
final Principal principal) final Principal principal)
throws NotFoundException { throws NotFoundException {
return updateValueFromSensor(
final Sensor sensor =
sensorRepository sensorRepository
.findByIdAndUsername(sensorId, principal.getName()) .findByIdAndUsername(sensorId, principal.getName())
.orElseThrow(NotFoundException::new); .orElseThrow(NotFoundException::new),
sensor.setValue(value); value);
final Sensor toReturn = sensorRepository.save(sensor);
System.out.println("sensor: " + sensor);
sensorSocketEndpoint.broadcast(sensor, sensorRepository.findUser(sensorId));
return toReturn;
} }
@DeleteMapping("/{id}") @DeleteMapping("/{id}")

View File

@ -13,11 +13,11 @@ import javax.validation.constraints.NotNull;
@Entity @Entity
public class Sensor extends InputDevice { public class Sensor extends InputDevice {
private static final Map<SensorType, Integer> TYPICAL_VALUES = public static final Map<SensorType, BigDecimal> TYPICAL_VALUES =
Map.of( Map.of(
SensorType.TEMPERATURE, 17, SensorType.TEMPERATURE, new BigDecimal(17.0),
SensorType.HUMIDITY, 40, SensorType.HUMIDITY, new BigDecimal(40.0),
SensorType.LIGHT, 1000); SensorType.LIGHT, new BigDecimal(1000));
/** Type of sensor, i.e. of the thing the sensor measures. */ /** Type of sensor, i.e. of the thing the sensor measures. */
public enum SensorType { public enum SensorType {

View File

@ -0,0 +1,62 @@
package ch.usi.inf.sa4.sanmarinoes.smarthut.scheduled;
import ch.usi.inf.sa4.sanmarinoes.smarthut.controller.MotionSensorController;
import ch.usi.inf.sa4.sanmarinoes.smarthut.controller.SensorController;
import ch.usi.inf.sa4.sanmarinoes.smarthut.models.MotionSensorRepository;
import ch.usi.inf.sa4.sanmarinoes.smarthut.models.Sensor;
import ch.usi.inf.sa4.sanmarinoes.smarthut.models.SensorRepository;
import java.math.BigDecimal;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import java.util.stream.StreamSupport;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
/** Generates fake sensor (and motion sensor) updates as required by milestone one */
@Component
public class SensorUpdateTasks {
@Autowired private SensorRepository sensorRepository;
@Autowired private MotionSensorRepository motionSensorRepository;
@Autowired private SensorController sensorController;
@Autowired private MotionSensorController motionSensorController;
/** Generates fake sensor updates every two seconds with a +/- 1.25% error */
@Scheduled(fixedRate = 2000)
public void sensorFakeUpdate() {
StreamSupport.stream(sensorRepository.findAll().spliterator(), true)
.forEach(
sensor ->
sensorController.updateValueFromSensor(
sensor,
Sensor.TYPICAL_VALUES
.get(sensor.getSensor())
.multiply(
new BigDecimal(
0.9875 + Math.random() / 40))));
}
/**
* Generate fake motion detections in all motion detectors every 20 seconds for 2 seconds at
* most
*/
@Scheduled(fixedDelay = 20000)
public void motionSensorFakeUpdate() {
StreamSupport.stream(motionSensorRepository.findAll().spliterator(), true)
.forEach(
sensor -> {
motionSensorController.updateDetectionFromMotionSensor(sensor, true);
CompletableFuture.delayedExecutor(
(long) (Math.random() * 2000), TimeUnit.MILLISECONDS)
.execute(
() ->
motionSensorController
.updateDetectionFromMotionSensor(
sensor, false));
});
}
}

View File

@ -44,8 +44,6 @@ public class AuthenticationMessageListener {
return new MessageHandler.Whole<>() { return new MessageHandler.Whole<>() {
@Override @Override
public void onMessage(final String message) { public void onMessage(final String message) {
System.out.println(message);
if (message == null) { if (message == null) {
acknowledge(false); acknowledge(false);
return; return;

View File

@ -59,7 +59,6 @@ public class SensorSocketEndpoint extends Endpoint {
*/ */
public long broadcast(Object message, User u) { public long broadcast(Object message, User u) {
final Collection<Session> sessions = authorizedClients.get(u); final Collection<Session> sessions = authorizedClients.get(u);
System.out.println(authorizedClients + " " + sessions + " " + u);
return sessions.stream() return sessions.stream()
.parallel() .parallel()
.filter(didThrow(s -> s.getBasicRemote().sendText(gson.toJson(message)))) .filter(didThrow(s -> s.getBasicRemote().sendText(gson.toJson(message))))

View File

@ -22,7 +22,6 @@ public final class Utils {
return (t) -> { return (t) -> {
try { try {
consumer.apply(t); consumer.apply(t);
System.out.println("successful");
return true; return true;
} catch (Throwable e) { } catch (Throwable e) {
System.err.println(e.getMessage()); System.err.println(e.getMessage());