Merge branch 'dev' into 'master'

Dev

See merge request sa4-2020/the-sanmarinoes/backend!99
This commit is contained in:
Claudio Maggioni 2020-04-28 09:34:16 +02:00
commit 9f7319a25b
113 changed files with 3946 additions and 695 deletions

View file

@ -9,6 +9,7 @@ version = '0.0.1-SNAPSHOT'
sourceCompatibility = '11' sourceCompatibility = '11'
repositories { repositories {
mavenCentral() mavenCentral()
} }
dependencies { dependencies {
compile 'org.hibernate.javax.persistence:hibernate-jpa-2.1-api:1.0.0.Final' compile 'org.hibernate.javax.persistence:hibernate-jpa-2.1-api:1.0.0.Final'
@ -39,6 +40,13 @@ dependencies {
// Fixes https://stackoverflow.com/a/60455550 // Fixes https://stackoverflow.com/a/60455550
testImplementation group: 'org.apache.httpcomponents', name: 'httpclient', version: '4.5.11' testImplementation group: 'org.apache.httpcomponents', name: 'httpclient', version: '4.5.11'
} }
gradle.projectsEvaluated {
tasks.withType(JavaCompile) {
options.compilerArgs << "-Xlint:unchecked" << "-Xlint:deprecation"
}
}
test { test {
useJUnitPlatform() useJUnitPlatform()
} }

View file

@ -1,5 +1,6 @@
#Sun Apr 12 12:33:03 CEST 2020
distributionUrl=https\://services.gradle.org/distributions/gradle-6.2.2-all.zip
distributionBase=GRADLE_USER_HOME distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-6.2.2-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists zipStorePath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME

View file

@ -1,40 +1,45 @@
<!-- vim: set ts=2 sw=2 et tw=80: --> <!-- vim: set ts=2 sw=2 et tw=80: -->
<html> <html>
<head> <head>
<meta charset="utf-8"> <meta charset="utf-8">
</head> </head>
<body> <body>
<div id="malusa"> <div id="malusa">
<h1>Waiting for authentication...</h1> <h1>Waiting for authentication...</h1>
</div> </div>
<script> <script>
let malusa = document.getElementById("malusa"); let malusa = document.getElementById("malusa");
let connection = new WebSocket("ws://localhost:8080/sensor-socket"); let token = localStorage.getItem("token");
if (!token) {
token = prompt("insert authentication token");
localStorage.setItem("token", token);
}
let connection = new WebSocket("ws://localhost:8080/sensor-socket?token=" + token);
console.log("***CREATED WEBSOCKET"); console.log("***CREATED WEBSOCKET");
let authentica
connection.onopen = function(evt) { connection.onopen = function(evt) {
console.log("***ONOPEN", evt); malusa.innerHTML = "<h1>Socket is now authenticated!</h1>" +
connection.send(JSON.stringify({token: prompt("insert authentication token")})); "<img src='https://maggioni.xyz/astley.gif'>";
}; };
connection.onmessage = function(evt) { connection.onmessage = function(evt) {
console.log("***ONMESSAGE", evt); console.log("***ONMESSAGE", evt);
let data = JSON.parse(evt.data); let data = JSON.parse(evt.data);
let a = document.getElementById("giovanni");
if (a) a.remove();
if (data.authenticated) { malusa.innerHTML += "<pre id=\"giovanni\">" + JSON.stringify(JSON.parse(evt.data), null, 2) + "</pre>";
malusa.innerHTML = "<h1>Socket is now authenticated!</h1>" +
"<img src='https://maggioni.xyz/astley.gif'>";
} else if (data.authenticated === false) {
malusa.innerHTML = "<h1>Authentication error</h1>";
} else {
malusa.innerHTML += "<p><pre>" + JSON.stringify(JSON.parse(evt.data), null, 2) + "</pre></p>";
}
}; };
connection.onerror = function(evt) { connection.onerror = function(evt) {
console.error("***ONERROR", evt); console.error("***ONERROR", evt);
}; };
</script>
</body>
</script>
</body>
</html> </html>

View file

@ -1,5 +1,9 @@
package ch.usi.inf.sa4.sanmarinoes.smarthut.config; package ch.usi.inf.sa4.sanmarinoes.smarthut.config;
import ch.usi.inf.sa4.sanmarinoes.smarthut.dto.AutomationFastUpdateRequest;
import ch.usi.inf.sa4.sanmarinoes.smarthut.models.DimmableState;
import ch.usi.inf.sa4.sanmarinoes.smarthut.models.State;
import ch.usi.inf.sa4.sanmarinoes.smarthut.models.SwitchableState;
import com.google.gson.*; import com.google.gson.*;
import java.lang.reflect.Type; import java.lang.reflect.Type;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
@ -20,12 +24,39 @@ public class GsonConfig {
return converter; return converter;
} }
public static Gson gson() { private static GsonBuilder configureBuilder() {
final GsonBuilder builder = new GsonBuilder(); final GsonBuilder builder = new GsonBuilder();
builder.registerTypeAdapter(Json.class, new SpringfoxJsonToGsonAdapter()); builder.registerTypeAdapter(Json.class, new SpringfoxJsonToGsonAdapter());
RuntimeTypeAdapterFactory<State> runtimeTypeAdapterFactory =
RuntimeTypeAdapterFactory.of(State.class, "kind")
.registerSubtype(SwitchableState.class, "switchableState")
.registerSubtype(DimmableState.class, "dimmableState");
RuntimeTypeAdapterFactory<AutomationFastUpdateRequest.TriggerDTO>
runtimeTypeAdapterFactoryII =
RuntimeTypeAdapterFactory.of(
AutomationFastUpdateRequest.TriggerDTO.class, "kind")
.registerSubtype(
AutomationFastUpdateRequest.BooleanTriggerDTO.class,
"booleanTrigger")
.registerSubtype(
AutomationFastUpdateRequest.RangeTriggerDTO.class,
"rangeTrigger");
builder.registerTypeAdapterFactory(runtimeTypeAdapterFactory);
builder.registerTypeAdapterFactory(runtimeTypeAdapterFactoryII);
return builder;
}
public static Gson gson() {
final GsonBuilder builder = configureBuilder();
builder.addSerializationExclusionStrategy(new AnnotationExclusionStrategy()); builder.addSerializationExclusionStrategy(new AnnotationExclusionStrategy());
return builder.create(); return builder.create();
} }
public static Gson socketGson() {
final GsonBuilder builder = configureBuilder();
builder.addSerializationExclusionStrategy(new SocketAnnotationExclusionStrategy());
return builder.create();
}
} }
/** GSON type adapter needed to avoid serializing twice Springfox Swagger JSON output */ /** GSON type adapter needed to avoid serializing twice Springfox Swagger JSON output */
@ -48,3 +79,16 @@ class AnnotationExclusionStrategy implements ExclusionStrategy {
return false; return false;
} }
} }
/** GSON exclusion strategy to exclude attributes with @SocketGsonExclude */
class SocketAnnotationExclusionStrategy implements ExclusionStrategy {
@Override
public boolean shouldSkipField(FieldAttributes f) {
return f.getAnnotation(SocketGsonExclude.class) != null;
}
@Override
public boolean shouldSkipClass(Class<?> clazz) {
return false;
}
}

View file

@ -1,6 +1,6 @@
package ch.usi.inf.sa4.sanmarinoes.smarthut.config; package ch.usi.inf.sa4.sanmarinoes.smarthut.config;
import ch.usi.inf.sa4.sanmarinoes.smarthut.models.JWTUserDetailsService; import ch.usi.inf.sa4.sanmarinoes.smarthut.service.JWTUserDetailsService;
import io.jsonwebtoken.ExpiredJwtException; import io.jsonwebtoken.ExpiredJwtException;
import java.io.IOException; import java.io.IOException;
import javax.servlet.FilterChain; import javax.servlet.FilterChain;

View file

@ -0,0 +1,315 @@
package ch.usi.inf.sa4.sanmarinoes.smarthut.config;
/*
* Copyright (C) 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.JsonPrimitive;
import com.google.gson.TypeAdapter;
import com.google.gson.TypeAdapterFactory;
import com.google.gson.internal.Streams;
import com.google.gson.reflect.TypeToken;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* Adapts values whose runtime type may differ from their declaration type. This is necessary when a
* field's type is not the same type that GSON should create when deserializing that field. For
* example, consider these types:
*
* <pre>{@code
* abstract class Shape {
* int x;
* int y;
* }
* class Circle extends Shape {
* int radius;
* }
* class Rectangle extends Shape {
* int width;
* int height;
* }
* class Diamond extends Shape {
* int width;
* int height;
* }
* class Drawing {
* Shape bottomShape;
* Shape topShape;
* }
* }</pre>
*
* <p>Without additional type information, the serialized JSON is ambiguous. Is the bottom shape in
* this drawing a rectangle or a diamond?
*
* <pre>{@code
* {
* "bottomShape": {
* "width": 10,
* "height": 5,
* "x": 0,
* "y": 0
* },
* "topShape": {
* "radius": 2,
* "x": 4,
* "y": 1
* }
* }
* }</pre>
*
* This class addresses this problem by adding type information to the serialized JSON and honoring
* that type information when the JSON is deserialized:
*
* <pre>{@code
* {
* "bottomShape": {
* "type": "Diamond",
* "width": 10,
* "height": 5,
* "x": 0,
* "y": 0
* },
* "topShape": {
* "type": "Circle",
* "radius": 2,
* "x": 4,
* "y": 1
* }
* }
* }</pre>
*
* Both the type field name ({@code "type"}) and the type labels ({@code "Rectangle"}) are
* configurable.
*
* <h3>Registering Types</h3>
*
* Create a {@code RuntimeTypeAdapterFactory} by passing the base type and type field name to the
* {@link #of} factory method. If you don't supply an explicit type field name, {@code "type"} will
* be used.
*
* <pre>{@code
* RuntimeTypeAdapterFactory<Shape> shapeAdapterFactory
* = RuntimeTypeAdapterFactory.of(Shape.class, "type");
* }</pre>
*
* Next register all of your subtypes. Every subtype must be explicitly registered. This protects
* your application from injection attacks. If you don't supply an explicit type label, the type's
* simple name will be used.
*
* <pre>{@code
* shapeAdapterFactory.registerSubtype(Rectangle.class, "Rectangle");
* shapeAdapterFactory.registerSubtype(Circle.class, "Circle");
* shapeAdapterFactory.registerSubtype(Diamond.class, "Diamond");
* }</pre>
*
* Finally, register the type adapter factory in your application's GSON builder:
*
* <pre>{@code
* Gson gson = new GsonBuilder()
* .registerTypeAdapterFactory(shapeAdapterFactory)
* .create();
* }</pre>
*
* Like {@code GsonBuilder}, this API supports chaining:
*
* <pre>{@code
* RuntimeTypeAdapterFactory<Shape> shapeAdapterFactory = RuntimeTypeAdapterFactory.of(Shape.class)
* .registerSubtype(Rectangle.class)
* .registerSubtype(Circle.class)
* .registerSubtype(Diamond.class);
* }</pre>
*
* <h3>Serialization and deserialization</h3>
*
* In order to serialize and deserialize a polymorphic object, you must specify the base type
* explicitly.
*
* <pre>{@code
* Diamond diamond = new Diamond();
* String json = gson.toJson(diamond, Shape.class);
* }</pre>
*
* And then:
*
* <pre>{@code
* Shape shape = gson.fromJson(json, Shape.class);
* }</pre>
*/
public final class RuntimeTypeAdapterFactory<T> implements TypeAdapterFactory {
private final Class<?> baseType;
private final String typeFieldName;
private final Map<String, Class<?>> labelToSubtype = new LinkedHashMap<String, Class<?>>();
private final Map<Class<?>, String> subtypeToLabel = new LinkedHashMap<Class<?>, String>();
private final boolean maintainType;
private RuntimeTypeAdapterFactory(
Class<?> baseType, String typeFieldName, boolean maintainType) {
if (typeFieldName == null || baseType == null) {
throw new NullPointerException();
}
this.baseType = baseType;
this.typeFieldName = typeFieldName;
this.maintainType = maintainType;
}
/**
* Creates a new runtime type adapter using for {@code baseType} using {@code typeFieldName} as
* the type field name. Type field names are case sensitive. {@code maintainType} flag decide if
* the type will be stored in pojo or not.
*/
public static <T> RuntimeTypeAdapterFactory<T> of(
Class<T> baseType, String typeFieldName, boolean maintainType) {
return new RuntimeTypeAdapterFactory<T>(baseType, typeFieldName, maintainType);
}
/**
* Creates a new runtime type adapter using for {@code baseType} using {@code typeFieldName} as
* the type field name. Type field names are case sensitive.
*/
public static <T> RuntimeTypeAdapterFactory<T> of(Class<T> baseType, String typeFieldName) {
return new RuntimeTypeAdapterFactory<T>(baseType, typeFieldName, false);
}
/**
* Creates a new runtime type adapter for {@code baseType} using {@code "type"} as the type
* field name.
*/
public static <T> RuntimeTypeAdapterFactory<T> of(Class<T> baseType) {
return new RuntimeTypeAdapterFactory<T>(baseType, "type", false);
}
/**
* Registers {@code type} identified by {@code label}. Labels are case sensitive.
*
* @throws IllegalArgumentException if either {@code type} or {@code label} have already been
* registered on this type adapter.
*/
public RuntimeTypeAdapterFactory<T> registerSubtype(Class<? extends T> type, String label) {
if (type == null || label == null) {
throw new NullPointerException();
}
if (subtypeToLabel.containsKey(type) || labelToSubtype.containsKey(label)) {
throw new IllegalArgumentException("types and labels must be unique");
}
labelToSubtype.put(label, type);
subtypeToLabel.put(type, label);
return this;
}
/**
* Registers {@code type} identified by its {@link Class#getSimpleName simple name}. Labels are
* case sensitive.
*
* @throws IllegalArgumentException if either {@code type} or its simple name have already been
* registered on this type adapter.
*/
public RuntimeTypeAdapterFactory<T> registerSubtype(Class<? extends T> type) {
return registerSubtype(type, type.getSimpleName());
}
public <R> TypeAdapter<R> create(Gson gson, TypeToken<R> type) {
if (type.getRawType() != baseType) {
return null;
}
final Map<String, TypeAdapter<?>> labelToDelegate =
new LinkedHashMap<String, TypeAdapter<?>>();
final Map<Class<?>, TypeAdapter<?>> subtypeToDelegate =
new LinkedHashMap<Class<?>, TypeAdapter<?>>();
for (Map.Entry<String, Class<?>> entry : labelToSubtype.entrySet()) {
TypeAdapter<?> delegate =
gson.getDelegateAdapter(this, TypeToken.get(entry.getValue()));
labelToDelegate.put(entry.getKey(), delegate);
subtypeToDelegate.put(entry.getValue(), delegate);
}
return new TypeAdapter<R>() {
@Override
public R read(JsonReader in) throws IOException {
JsonElement jsonElement = Streams.parse(in);
JsonElement labelJsonElement;
if (maintainType) {
labelJsonElement = jsonElement.getAsJsonObject().get(typeFieldName);
} else {
labelJsonElement = jsonElement.getAsJsonObject().remove(typeFieldName);
}
if (labelJsonElement == null) {
throw new JsonParseException(
"cannot deserialize "
+ baseType
+ " because it does not define a field named "
+ typeFieldName);
}
String label = labelJsonElement.getAsString();
@SuppressWarnings("unchecked") // registration requires that subtype extends T
TypeAdapter<R> delegate = (TypeAdapter<R>) labelToDelegate.get(label);
if (delegate == null) {
throw new JsonParseException(
"cannot deserialize "
+ baseType
+ " subtype named "
+ label
+ "; did you forget to register a subtype?");
}
return delegate.fromJsonTree(jsonElement);
}
@Override
public void write(JsonWriter out, R value) throws IOException {
Class<?> srcType = value.getClass();
String label = subtypeToLabel.get(srcType);
@SuppressWarnings("unchecked") // registration requires that subtype extends T
TypeAdapter<R> delegate = (TypeAdapter<R>) subtypeToDelegate.get(srcType);
if (delegate == null) {
throw new JsonParseException(
"cannot serialize "
+ srcType.getName()
+ "; did you forget to register a subtype?");
}
JsonObject jsonObject = delegate.toJsonTree(value).getAsJsonObject();
if (maintainType) {
Streams.write(jsonObject, out);
return;
}
JsonObject clone = new JsonObject();
if (jsonObject.has(typeFieldName)) {
throw new JsonParseException(
"cannot serialize "
+ srcType.getName()
+ " because it already defines a field named "
+ typeFieldName);
}
clone.add(typeFieldName, new JsonPrimitive(label));
for (Map.Entry<String, JsonElement> e : jsonObject.entrySet()) {
clone.add(e.getKey(), e.getValue());
}
Streams.write(clone, out);
}
}.nullSafe();
}
}

View file

@ -0,0 +1,10 @@
package ch.usi.inf.sa4.sanmarinoes.smarthut.config;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface SocketGsonExclude {}

View file

@ -68,13 +68,21 @@ public class SpringFoxConfig {
.or(PathSelectors.regex("/room.*")::apply) .or(PathSelectors.regex("/room.*")::apply)
.or(PathSelectors.regex("/device.*")::apply) .or(PathSelectors.regex("/device.*")::apply)
.or(PathSelectors.regex("/buttonDimmer.*")::apply) .or(PathSelectors.regex("/buttonDimmer.*")::apply)
.or(PathSelectors.regex("/thermostat.*")::apply)
.or(PathSelectors.regex("/dimmableLight.*")::apply) .or(PathSelectors.regex("/dimmableLight.*")::apply)
.or(PathSelectors.regex("/knobDimmer.*")::apply) .or(PathSelectors.regex("/knobDimmer.*")::apply)
.or(PathSelectors.regex("/regularLight.*")::apply) .or(PathSelectors.regex("/regularLight.*")::apply)
.or(PathSelectors.regex("/securityCamera.*")::apply)
.or(PathSelectors.regex("/sensor.*")::apply) .or(PathSelectors.regex("/sensor.*")::apply)
.or(PathSelectors.regex("/smartPlug.*")::apply) .or(PathSelectors.regex("/smartPlug.*")::apply)
.or(PathSelectors.regex("/scene.*")::apply)
.or(PathSelectors.regex("/switchableState.*")::apply)
.or(PathSelectors.regex("/dimmableState.*")::apply)
.or(PathSelectors.regex("/switch.*")::apply) .or(PathSelectors.regex("/switch.*")::apply)
.or(PathSelectors.regex("/motionSensor.*")::apply) .or(PathSelectors.regex("/motionSensor.*")::apply)
.or(PathSelectors.regex("/curtains.*")::apply)
.or(PathSelectors.regex("/user.*")::apply)
.or(PathSelectors.regex("/automation.*")::apply)
.or(PathSelectors.regex("/auth/profile.*")::apply); .or(PathSelectors.regex("/auth/profile.*")::apply);
} }

View file

@ -1,6 +1,6 @@
package ch.usi.inf.sa4.sanmarinoes.smarthut.config; package ch.usi.inf.sa4.sanmarinoes.smarthut.config;
import ch.usi.inf.sa4.sanmarinoes.smarthut.models.JWTUserDetailsService; import ch.usi.inf.sa4.sanmarinoes.smarthut.service.JWTUserDetailsService;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
@ -51,6 +51,7 @@ public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
// dont authenticate this particular request // dont authenticate this particular request
.authorizeRequests() .authorizeRequests()
.antMatchers( .antMatchers(
"/security_camera_videos/**",
"/sensor-socket", "/sensor-socket",
"/auth/login", "/auth/login",
"/swagger-ui.html", "/swagger-ui.html",

View file

@ -8,6 +8,8 @@ import ch.usi.inf.sa4.sanmarinoes.smarthut.error.UserNotFoundException;
import ch.usi.inf.sa4.sanmarinoes.smarthut.models.*; import ch.usi.inf.sa4.sanmarinoes.smarthut.models.*;
import java.security.Principal; import java.security.Principal;
import javax.validation.Valid; import javax.validation.Valid;
import ch.usi.inf.sa4.sanmarinoes.smarthut.service.JWTUserDetailsService;
import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException; import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.DisabledException; import org.springframework.security.authentication.DisabledException;

View file

@ -0,0 +1,118 @@
package ch.usi.inf.sa4.sanmarinoes.smarthut.controller;
import ch.usi.inf.sa4.sanmarinoes.smarthut.dto.AutomationFastUpdateRequest;
import ch.usi.inf.sa4.sanmarinoes.smarthut.dto.AutomationSaveRequest;
import ch.usi.inf.sa4.sanmarinoes.smarthut.error.NotFoundException;
import ch.usi.inf.sa4.sanmarinoes.smarthut.models.*;
import java.security.Principal;
import java.util.List;
import java.util.stream.Collectors;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
@EnableAutoConfiguration
@RequestMapping("/automation")
public class AutomationController {
@Autowired private AutomationRepository automationRepository;
@Autowired private ScenePriorityRepository sceneRepository;
@Autowired private TriggerRepository<Trigger<?>> triggerRepository;
@Autowired private UserRepository userService;
@GetMapping
public List<Automation> getAll(
@RequestParam(value = "hostId", required = false) Long hostId,
final Principal principal)
throws NotFoundException {
final Long userId = userService.findByUsername(principal.getName()).getId();
return automationRepository.findAllByUserId(userId);
}
@GetMapping("/{id}")
public Automation get(@PathVariable long id) throws NotFoundException {
return automationRepository.findById(id).orElseThrow(NotFoundException::new);
}
private Automation save(Automation newRL, AutomationSaveRequest s, Principal principal) {
final Long userId = userService.findByUsername(principal.getName()).getId();
newRL.setName(s.getName());
newRL.setUserId(userId);
return automationRepository.save(newRL);
}
@PostMapping
public Automation create(
@Valid @RequestBody AutomationSaveRequest automationSaveRequest, Principal principal) {
return save(new Automation(), automationSaveRequest, principal);
}
@PutMapping
public Automation update(
@Valid @RequestBody AutomationSaveRequest automation, Principal principal)
throws NotFoundException {
return save(
automationRepository
.findById(automation.getId())
.orElseThrow(NotFoundException::new),
automation,
principal);
}
@PutMapping("/fast")
public Automation fastUpdate(
@Valid @RequestBody AutomationFastUpdateRequest req, Principal principal)
throws NotFoundException {
final Automation a =
automationRepository
.findByIdAndUserId(
req.getId(),
userService.findByUsername(principal.getName()).getId())
.orElseThrow(NotFoundException::new);
a.setName(req.getName());
automationRepository.save(a);
triggerRepository.deleteAllByAutomationId(a.getId());
sceneRepository.deleteAllByAutomationId(a.getId());
Iterable<Trigger<?>> tt =
triggerRepository.saveAll(
req.getTriggers()
.stream()
.map(AutomationFastUpdateRequest.TriggerDTO::toModel)
.map(t -> t.setAutomationId(a.getId()))
.collect(Collectors.toList()));
Iterable<ScenePriority> ss =
sceneRepository.saveAll(
req.getScenes()
.stream()
.map(AutomationFastUpdateRequest.ScenePriorityDTO::toModel)
.map(t -> t.setAutomationId(a.getId()))
.collect(Collectors.toList()));
a.getScenes().clear();
a.getTriggers().clear();
ss.forEach(t -> a.getScenes().add(t));
tt.forEach(t -> a.getTriggers().add(t));
return a;
}
@DeleteMapping("/{id}")
public void delete(@PathVariable long id) {
automationRepository.deleteById(id);
}
}

View file

@ -0,0 +1,61 @@
package ch.usi.inf.sa4.sanmarinoes.smarthut.controller;
import ch.usi.inf.sa4.sanmarinoes.smarthut.dto.BooleanTriggerSaveRequest;
import ch.usi.inf.sa4.sanmarinoes.smarthut.error.NotFoundException;
import ch.usi.inf.sa4.sanmarinoes.smarthut.models.BooleanTrigger;
import ch.usi.inf.sa4.sanmarinoes.smarthut.models.BooleanTriggerRepository;
import java.util.List;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@EnableAutoConfiguration
@RequestMapping("/booleanTrigger")
public class BooleanTriggerController {
@Autowired BooleanTriggerRepository booleanTriggerRepository;
@GetMapping("/{automationId}")
public List<BooleanTrigger<?>> getAll(@PathVariable long automationId) {
return booleanTriggerRepository.findAllByAutomationId(automationId);
}
private BooleanTrigger<?> save(BooleanTrigger<?> newRL, BooleanTriggerSaveRequest s) {
newRL.setDeviceId(s.getDeviceId());
newRL.setAutomationId(s.getAutomationId());
newRL.setOn(s.isOn());
return booleanTriggerRepository.save(newRL);
}
@PostMapping
public BooleanTrigger<?> create(
@Valid @RequestBody BooleanTriggerSaveRequest booleanTriggerSaveRequest) {
return save(new BooleanTrigger<>(), booleanTriggerSaveRequest);
}
@PutMapping
public BooleanTrigger<?> update(
@Valid @RequestBody BooleanTriggerSaveRequest booleanTriggerSaveRequest)
throws NotFoundException {
return save(
booleanTriggerRepository
.findById(booleanTriggerSaveRequest.getId())
.orElseThrow(NotFoundException::new),
booleanTriggerSaveRequest);
}
@DeleteMapping("/{id}")
public void delete(@PathVariable long id) {
booleanTriggerRepository.deleteById(id);
}
}

View file

@ -1,13 +1,11 @@
package ch.usi.inf.sa4.sanmarinoes.smarthut.controller; package ch.usi.inf.sa4.sanmarinoes.smarthut.controller;
import static ch.usi.inf.sa4.sanmarinoes.smarthut.utils.Utils.toList;
import ch.usi.inf.sa4.sanmarinoes.smarthut.dto.ButtonDimmerDimRequest; import ch.usi.inf.sa4.sanmarinoes.smarthut.dto.ButtonDimmerDimRequest;
import ch.usi.inf.sa4.sanmarinoes.smarthut.dto.GenericDeviceSaveReguest; import ch.usi.inf.sa4.sanmarinoes.smarthut.dto.GenericDeviceSaveReguest;
import ch.usi.inf.sa4.sanmarinoes.smarthut.error.NotFoundException; import ch.usi.inf.sa4.sanmarinoes.smarthut.error.NotFoundException;
import ch.usi.inf.sa4.sanmarinoes.smarthut.models.*; import ch.usi.inf.sa4.sanmarinoes.smarthut.models.*;
import ch.usi.inf.sa4.sanmarinoes.smarthut.service.DeviceService;
import java.security.Principal; import java.security.Principal;
import java.util.List;
import java.util.Set; import java.util.Set;
import javax.validation.Valid; import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
@ -18,42 +16,36 @@ import org.springframework.web.bind.annotation.*;
@EnableAutoConfiguration @EnableAutoConfiguration
@RequestMapping("/buttonDimmer") @RequestMapping("/buttonDimmer")
public class ButtonDimmerController public class ButtonDimmerController
extends InputDeviceConnectionController<ButtonDimmer, DimmableLight> { extends InputDeviceConnectionController<ButtonDimmer, Dimmable> {
private DeviceService deviceService;
private ButtonDimmerRepository buttonDimmerRepository; private ButtonDimmerRepository buttonDimmerRepository;
private DimmableLightRepository dimmableLightRepository;
@Autowired @Autowired
protected ButtonDimmerController( protected ButtonDimmerController(
ButtonDimmerRepository inputRepository, DimmableLightRepository outputRepository) { ButtonDimmerRepository inputRepository,
super( DimmableRepository<Dimmable> outputRepository,
inputRepository, DeviceService deviceService) {
outputRepository, super(inputRepository, outputRepository, DimmableLight.BUTTON_DIMMER_DIMMABLE_CONNECTOR);
DimmableLight.BUTTON_DIMMER_DIMMABLE_LIGHT_CONNECTOR); this.deviceService = deviceService;
this.buttonDimmerRepository = inputRepository; this.buttonDimmerRepository = inputRepository;
this.dimmableLightRepository = outputRepository;
}
@GetMapping
public List<ButtonDimmer> findAll() {
return toList(buttonDimmerRepository.findAll());
}
@GetMapping("/{id}")
public ButtonDimmer findById(@PathVariable("id") long id) throws NotFoundException {
return buttonDimmerRepository.findById(id).orElseThrow(NotFoundException::new);
} }
@PostMapping @PostMapping
public ButtonDimmer create(@Valid @RequestBody final GenericDeviceSaveReguest bd) { public ButtonDimmer create(
@Valid @RequestBody final GenericDeviceSaveReguest bd, final Principal principal)
throws NotFoundException {
deviceService.throwIfRoomNotOwned(bd.getRoomId(), principal.getName());
ButtonDimmer newBD = new ButtonDimmer(); ButtonDimmer newBD = new ButtonDimmer();
newBD.setName(bd.getName()); newBD.setName(bd.getName());
newBD.setRoomId(bd.getRoomId()); newBD.setRoomId(bd.getRoomId());
return buttonDimmerRepository.save(newBD); return deviceService.saveAsOwner(newBD, principal.getName());
} }
@PutMapping("/dim") @PutMapping("/dim")
public Set<DimmableLight> dim( public Set<Dimmable> dim(
@Valid @RequestBody final ButtonDimmerDimRequest bd, final Principal principal) @Valid @RequestBody final ButtonDimmerDimRequest bd, final Principal principal)
throws NotFoundException { throws NotFoundException {
final ButtonDimmer buttonDimmer = final ButtonDimmer buttonDimmer =
@ -70,27 +62,14 @@ public class ButtonDimmerController
break; break;
} }
dimmableLightRepository.saveAll(buttonDimmer.getOutputs()); deviceService.saveAllAsOwner(buttonDimmer.getOutputs(), principal.getName(), false);
return buttonDimmer.getOutputs(); return buttonDimmer.getOutputs();
} }
@PostMapping("/{id}/lights")
public Set<? extends OutputDevice> addLight(
@PathVariable("id") long inputId, @RequestParam("lightId") Long lightId)
throws NotFoundException {
return addOutput(inputId, lightId);
}
@DeleteMapping("/{id}/lights")
public Set<? extends OutputDevice> removeLight(
@PathVariable("id") long inputId, @RequestParam("lightId") Long lightId)
throws NotFoundException {
return removeOutput(inputId, lightId);
}
@DeleteMapping("/{id}") @DeleteMapping("/{id}")
public void delete(@PathVariable("id") long id) { public void delete(@PathVariable("id") long id, final Principal principal)
buttonDimmerRepository.deleteById(id); throws NotFoundException {
deviceService.delete(id, principal.getName());
} }
} }

View file

@ -0,0 +1,73 @@
package ch.usi.inf.sa4.sanmarinoes.smarthut.controller;
import ch.usi.inf.sa4.sanmarinoes.smarthut.dto.DimmableSaveRequest;
import ch.usi.inf.sa4.sanmarinoes.smarthut.error.DuplicateStateException;
import ch.usi.inf.sa4.sanmarinoes.smarthut.error.NotFoundException;
import ch.usi.inf.sa4.sanmarinoes.smarthut.models.*;
import ch.usi.inf.sa4.sanmarinoes.smarthut.service.DeviceService;
import java.security.Principal;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.web.bind.annotation.*;
@RestController
@EnableAutoConfiguration
@RequestMapping("/curtains")
public class CurtainsController {
@Autowired private DeviceService deviceService;
@Autowired private CurtainsRepository curtainsService;
@Autowired private SceneRepository sceneRepository;
@Autowired private StateRepository<State<?>> stateRepository;
private Curtains save(Curtains newRL, DimmableSaveRequest s, final Principal principal) {
newRL.setName(s.getName());
newRL.setRoomId(s.getRoomId());
newRL.setIntensity(s.getIntensity());
return deviceService.saveAsOwner(newRL, principal.getName());
}
@PostMapping
public Curtains create(
@Valid @RequestBody DimmableSaveRequest curtain, final Principal principal)
throws NotFoundException {
deviceService.throwIfRoomNotOwned(curtain.getRoomId(), principal.getName());
return save(new Curtains(), curtain, principal);
}
@PutMapping
public Curtains update(
@Valid @RequestBody DimmableSaveRequest curtain, final Principal principal)
throws NotFoundException {
return save(
curtainsService.findById(curtain.getId()).orElseThrow(NotFoundException::new),
curtain,
principal);
}
@DeleteMapping("/{id}")
public void delete(@PathVariable("id") long id, final Principal principal)
throws NotFoundException {
deviceService.delete(id, principal.getName());
}
@PostMapping("/{id}/state")
public State<? extends Dimmable> sceneBinding(
@PathVariable("id") long deviceId,
@RequestParam long sceneId,
final Principal principal)
throws NotFoundException, DuplicateStateException {
Curtains c =
curtainsService
.findByIdAndUsername(deviceId, principal.getName())
.orElseThrow(NotFoundException::new);
State<? extends Dimmable> s = c.cloneState();
sceneRepository.findById(sceneId).orElseThrow(NotFoundException::new);
s.setSceneId(sceneId);
if (stateRepository.countByDeviceIdAndSceneId(deviceId, sceneId) > 0)
throw new DuplicateStateException();
return stateRepository.save(s);
}
}

View file

@ -6,6 +6,7 @@ import ch.usi.inf.sa4.sanmarinoes.smarthut.error.NotFoundException;
import ch.usi.inf.sa4.sanmarinoes.smarthut.models.Device; import ch.usi.inf.sa4.sanmarinoes.smarthut.models.Device;
import ch.usi.inf.sa4.sanmarinoes.smarthut.models.DeviceRepository; import ch.usi.inf.sa4.sanmarinoes.smarthut.models.DeviceRepository;
import ch.usi.inf.sa4.sanmarinoes.smarthut.models.RoomRepository; import ch.usi.inf.sa4.sanmarinoes.smarthut.models.RoomRepository;
import ch.usi.inf.sa4.sanmarinoes.smarthut.service.DeviceService;
import java.security.Principal; import java.security.Principal;
import java.util.List; import java.util.List;
import javax.validation.Valid; import javax.validation.Valid;
@ -18,12 +19,15 @@ import org.springframework.web.bind.annotation.*;
@RequestMapping("/device") @RequestMapping("/device")
public class DeviceController { public class DeviceController {
@Autowired private DeviceService deviceService;
@Autowired private DeviceRepository<Device> deviceRepository; @Autowired private DeviceRepository<Device> deviceRepository;
@Autowired private RoomRepository roomRepository; @Autowired private RoomRepository roomRepository;
@GetMapping @GetMapping
public List<Device> getAll(final Principal user) { public List<Device> getAll(
return deviceRepository.findAllByUsername(user.getName()); @RequestParam(value = "hostId", required = false) Long hostId, final Principal user)
throws NotFoundException {
return deviceService.findAll(hostId, user.getName());
} }
@PutMapping @PutMapping
@ -43,7 +47,7 @@ public class DeviceController {
d.setRoomId(deviceSaveRequest.getRoomId()); d.setRoomId(deviceSaveRequest.getRoomId());
d.setName(deviceSaveRequest.getName()); d.setName(deviceSaveRequest.getName());
deviceRepository.save(d); deviceService.saveAsOwner(d, principal.getName());
return d; return d;
} }
} }

View file

@ -1,13 +1,11 @@
package ch.usi.inf.sa4.sanmarinoes.smarthut.controller; package ch.usi.inf.sa4.sanmarinoes.smarthut.controller;
import static ch.usi.inf.sa4.sanmarinoes.smarthut.utils.Utils.toList; import ch.usi.inf.sa4.sanmarinoes.smarthut.dto.DimmableSaveRequest;
import ch.usi.inf.sa4.sanmarinoes.smarthut.error.DuplicateStateException;
import ch.usi.inf.sa4.sanmarinoes.smarthut.dto.DimmableLightSaveRequest;
import ch.usi.inf.sa4.sanmarinoes.smarthut.error.NotFoundException; import ch.usi.inf.sa4.sanmarinoes.smarthut.error.NotFoundException;
import ch.usi.inf.sa4.sanmarinoes.smarthut.models.DimmableLight; import ch.usi.inf.sa4.sanmarinoes.smarthut.models.*;
import ch.usi.inf.sa4.sanmarinoes.smarthut.models.DimmableLightRepository; import ch.usi.inf.sa4.sanmarinoes.smarthut.service.DeviceService;
import java.security.Principal; import java.security.Principal;
import java.util.List;
import javax.validation.Valid; import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
@ -16,46 +14,92 @@ import org.springframework.web.bind.annotation.*;
@RestController @RestController
@EnableAutoConfiguration @EnableAutoConfiguration
@RequestMapping("/dimmableLight") @RequestMapping("/dimmableLight")
public class DimmableLightController { public class DimmableLightController extends GuestEnabledController<DimmableLight> {
@Autowired private DimmableLightRepository dimmableLightService; private DimmableLightRepository dimmableLightRepository;
private SceneRepository sceneRepository;
private StateRepository<State<?>> stateRepository;
private DeviceService deviceService;
@GetMapping @Autowired
public List<DimmableLight> findAll() { public DimmableLightController(
return toList(dimmableLightService.findAll()); UserRepository userRepository,
DimmableLightRepository dimmableLightRepository,
SceneRepository sceneRepository,
StateRepository<State<?>> stateRepository,
DeviceService deviceService) {
super(userRepository, dimmableLightRepository);
this.dimmableLightRepository = dimmableLightRepository;
this.sceneRepository = sceneRepository;
this.stateRepository = stateRepository;
this.deviceService = deviceService;
} }
@GetMapping("/{id}") private DimmableLight save(
public DimmableLight findById(@PathVariable("id") long id) throws NotFoundException { DimmableLight initial, DimmableSaveRequest dl, String username, Long hostId)
return dimmableLightService.findById(id).orElseThrow(NotFoundException::new); throws NotFoundException {
}
private DimmableLight save(DimmableLight initial, DimmableLightSaveRequest dl) {
initial.setIntensity(dl.getIntensity()); initial.setIntensity(dl.getIntensity());
initial.setName(dl.getName()); initial.setName(dl.getName());
initial.setRoomId(dl.getRoomId()); initial.setRoomId(dl.getRoomId());
return dimmableLightService.save(initial); if (hostId == null) {
return deviceService.saveAsOwner(initial, username);
} else {
return deviceService.saveAsGuest(initial, username, hostId);
}
} }
/*
Assume that only the host can create a device
Here save always as host, but remember to propagate change to guests (DeviceService.saveAsOwner())
*/
@PostMapping @PostMapping
public DimmableLight create(@Valid @RequestBody DimmableLightSaveRequest dl) { public DimmableLight create(
return save(new DimmableLight(), dl); @Valid @RequestBody DimmableSaveRequest dl, final Principal principal)
throws NotFoundException {
deviceService.throwIfRoomNotOwned(dl.getRoomId(), principal.getName());
return save(new DimmableLight(), dl, principal.getName(), null);
} }
/*
Logic for saving either as owner or guest is handled in method save of this controller
*/
@PutMapping @PutMapping
public DimmableLight update( public DimmableLight update(
@Valid @RequestBody DimmableLightSaveRequest sp, final Principal principal) @Valid @RequestBody DimmableSaveRequest sp, final Principal principal, Long hostId)
throws NotFoundException { throws NotFoundException {
return save( return save(
dimmableLightService fetchIfOwnerOrGuest(principal, sp.getId(), hostId),
.findByIdAndUsername(sp.getId(), principal.getName()) sp,
.orElseThrow(NotFoundException::new), principal.getName(),
sp); hostId);
} }
@DeleteMapping("/{id}") @DeleteMapping("/{id}")
public void delete(@PathVariable("id") long id) { public void delete(@PathVariable("id") long id, final Principal principal)
dimmableLightService.deleteById(id); throws NotFoundException {
deviceService.delete(id, principal.getName());
}
// the full url should be: "/dimmableLight/{id}/state?sceneId={sceneId}
// however it is not necessary to specify the query in the mapping
@PostMapping("/{id}/state")
public State<? extends Dimmable> sceneBinding(
@PathVariable("id") long deviceId,
@RequestParam long sceneId,
final Principal principal)
throws NotFoundException, DuplicateStateException {
DimmableLight d =
dimmableLightRepository
.findByIdAndUsername(deviceId, principal.getName())
.orElseThrow(NotFoundException::new);
State<? extends Dimmable> s = d.cloneState();
sceneRepository.findById(sceneId).orElseThrow(NotFoundException::new);
s.setSceneId(sceneId);
if (stateRepository.countByDeviceIdAndSceneId(deviceId, sceneId) > 0)
throw new DuplicateStateException();
return stateRepository.save(s);
} }
} }

View file

@ -0,0 +1,33 @@
package ch.usi.inf.sa4.sanmarinoes.smarthut.controller;
import ch.usi.inf.sa4.sanmarinoes.smarthut.dto.DimmableStateSaveRequest;
import ch.usi.inf.sa4.sanmarinoes.smarthut.error.NotFoundException;
import ch.usi.inf.sa4.sanmarinoes.smarthut.models.DimmableState;
import ch.usi.inf.sa4.sanmarinoes.smarthut.models.DimmableStateRepository;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.web.bind.annotation.*;
@RestController
@EnableAutoConfiguration
@RequestMapping("/dimmableState")
public class DimmableStateController {
@Autowired private DimmableStateRepository dimmableStateRepository;
@PutMapping
public DimmableState<?> update(@Valid @RequestBody DimmableStateSaveRequest ss)
throws NotFoundException {
final DimmableState<?> initial =
dimmableStateRepository.findById(ss.getId()).orElseThrow(NotFoundException::new);
initial.setIntensity(ss.getIntensity());
dimmableStateRepository.save(initial);
return initial;
}
@DeleteMapping("/{id}")
public void delete(@PathVariable("id") long id) {
dimmableStateRepository.deleteById(id);
}
}

View file

@ -0,0 +1,59 @@
package ch.usi.inf.sa4.sanmarinoes.smarthut.controller;
import static ch.usi.inf.sa4.sanmarinoes.smarthut.utils.Utils.toList;
import ch.usi.inf.sa4.sanmarinoes.smarthut.dto.GuestPermissionsRequest;
import ch.usi.inf.sa4.sanmarinoes.smarthut.error.NotFoundException;
import ch.usi.inf.sa4.sanmarinoes.smarthut.models.User;
import ch.usi.inf.sa4.sanmarinoes.smarthut.models.UserRepository;
import java.security.Principal;
import java.util.List;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.web.bind.annotation.*;
@RestController
@EnableAutoConfiguration
@RequestMapping("/user")
public class GuestController {
@Autowired private UserRepository userRepository;
@GetMapping
public List<User> findAll() {
return toList(userRepository.findAll());
}
@PostMapping("/guest")
public User addUserAsGuest(@RequestParam("userId") long id, final Principal principal)
throws NotFoundException {
User guest = userRepository.findById(id).orElseThrow(NotFoundException::new);
User host = userRepository.findByUsername(principal.getName());
host.addGuest(guest);
guest.addHost(host);
userRepository.save(guest);
return userRepository.save(host);
}
@PutMapping("/permissions")
public User updatePermissions(
@Valid @RequestBody GuestPermissionsRequest g, final Principal principal) {
final User currentUser = userRepository.findByUsername(principal.getName());
currentUser.setCameraEnabled(g.isCameraEnabled());
return userRepository.save(currentUser);
}
@DeleteMapping("/guest")
public void removeUserAsGuest(@RequestParam("userId") long id, final Principal principal)
throws NotFoundException {
User guest = userRepository.findById(id).orElseThrow(NotFoundException::new);
User host = userRepository.findByUsername(principal.getName());
host.removeGuest(guest);
guest.getHosts().remove(host);
userRepository.save(host);
userRepository.save(guest);
}
}

View file

@ -0,0 +1,37 @@
package ch.usi.inf.sa4.sanmarinoes.smarthut.controller;
import static ch.usi.inf.sa4.sanmarinoes.smarthut.utils.Utils.returnIfGuest;
import ch.usi.inf.sa4.sanmarinoes.smarthut.error.NotFoundException;
import ch.usi.inf.sa4.sanmarinoes.smarthut.models.*;
import java.security.Principal;
public abstract class GuestEnabledController<T extends Device> {
private UserRepository userRepository;
private DeviceRepository<T> deviceRepository;
public GuestEnabledController(
final UserRepository userRepository, final DeviceRepository<T> deviceRepository) {
this.userRepository = userRepository;
this.deviceRepository = deviceRepository;
}
protected T fetchIfOwnerOrGuest(final Principal principal, Long id, Long hostId)
throws NotFoundException {
if (hostId == null) {
return deviceRepository
.findByIdAndUsername(id, principal.getName())
.orElseThrow(NotFoundException::new);
} else {
/*
* Slightly less extremely verbose check through various repositories to control user/guest authorization.
*/
T device =
deviceRepository
.findByIdAndUserId(id, hostId)
.orElseThrow(NotFoundException::new);
return returnIfGuest(userRepository, device, hostId, principal);
}
}
}

View file

@ -1,8 +1,19 @@
package ch.usi.inf.sa4.sanmarinoes.smarthut.controller; package ch.usi.inf.sa4.sanmarinoes.smarthut.controller;
import static ch.usi.inf.sa4.sanmarinoes.smarthut.utils.Utils.toList;
import ch.usi.inf.sa4.sanmarinoes.smarthut.error.NotFoundException; import ch.usi.inf.sa4.sanmarinoes.smarthut.error.NotFoundException;
import ch.usi.inf.sa4.sanmarinoes.smarthut.models.*; import ch.usi.inf.sa4.sanmarinoes.smarthut.models.*;
import ch.usi.inf.sa4.sanmarinoes.smarthut.service.DeviceService;
import java.security.Principal;
import java.util.ArrayList;
import java.util.List;
import java.util.Set; import java.util.Set;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
/** /**
* An abstract controller for an input device that has output connected to it. Aids to create the * An abstract controller for an input device that has output connected to it. Aids to create the
@ -14,16 +25,18 @@ import java.util.Set;
public abstract class InputDeviceConnectionController< public abstract class InputDeviceConnectionController<
I extends InputDevice, O extends OutputDevice> { I extends InputDevice, O extends OutputDevice> {
private class IOPair { private class Connection {
private final I input; private final I input;
private final O output; private final List<O> outputs;
private IOPair(I input, O output) { private Connection(I input, List<O> outputs) {
this.input = input; this.input = input;
this.output = output; this.outputs = outputs;
} }
} }
@Autowired private DeviceService deviceService;
private DeviceRepository<I> inputRepository; private DeviceRepository<I> inputRepository;
private DeviceRepository<O> outputReposiory; private DeviceRepository<O> outputReposiory;
@ -46,31 +59,39 @@ public abstract class InputDeviceConnectionController<
this.connector = connector; this.connector = connector;
} }
private IOPair checkConnectionIDs(Long inputId, Long outputId) throws NotFoundException { private Connection checkConnectionIDs(Long inputId, List<Long> outputs, String username)
throws NotFoundException {
final I input = final I input =
inputRepository inputRepository
.findById(inputId) .findByIdAndUsername(inputId, username)
.orElseThrow(() -> new NotFoundException("input device")); .orElseThrow(() -> new NotFoundException("input device"));
final O output = final List<O> outputDevices = new ArrayList<>();
for (final Long outputId : outputs) {
outputDevices.add(
outputReposiory outputReposiory
.findById(outputId) .findByIdAndUsername(outputId, username)
.orElseThrow(() -> new NotFoundException("output device")); .orElseThrow(() -> new NotFoundException("output device")));
return new IOPair(input, output); }
return new Connection(input, outputDevices);
} }
/** /**
* Implements the output device connection creation (add) route * Implements the output device connection creation (add) route
* *
* @param inputId input device id * @param inputId input device id
* @param outputId output device id * @param outputs output device id list
* @return the list of output devices attached to the input device of id inputId * @return the list of output devices attached to the input device of id inputId
* @throws NotFoundException if inputId or outputId are not valid * @throws NotFoundException if inputId or outputId are not valid
*/ */
protected Set<? extends OutputDevice> addOutput(Long inputId, Long outputId) protected Set<? extends OutputDevice> addOutput(
throws NotFoundException { Long inputId, List<Long> outputs, String username) throws NotFoundException {
final IOPair pair = checkConnectionIDs(inputId, outputId); final Connection pair = checkConnectionIDs(inputId, outputs, username);
connector.connect(pair.input, pair.output, true);
outputReposiory.save(pair.output); for (final O o : pair.outputs) {
connector.connect(pair.input, o, true);
}
deviceService.saveAllAsOwner(pair.outputs, username, false);
return pair.input.getOutputs(); return pair.input.getOutputs();
} }
@ -78,15 +99,37 @@ public abstract class InputDeviceConnectionController<
* Implements the output device connection destruction (remove) route * Implements the output device connection destruction (remove) route
* *
* @param inputId input device id * @param inputId input device id
* @param outputId output device id * @param outputs output device id list
* @return the list of output devices attached to the input device of id inputId * @return the list of output devices attached to the input device of id inputId
* @throws NotFoundException if inputId or outputId are not valid * @throws NotFoundException if inputId or outputId are not valid
*/ */
protected Set<? extends OutputDevice> removeOutput(Long inputId, Long outputId) protected Set<? extends OutputDevice> removeOutput(
throws NotFoundException { Long inputId, List<Long> outputs, String username) throws NotFoundException {
final IOPair pair = checkConnectionIDs(inputId, outputId); final Connection pair = checkConnectionIDs(inputId, outputs, username);
connector.connect(pair.input, pair.output, false);
outputReposiory.save(pair.output); for (final O o : pair.outputs) {
connector.connect(pair.input, o, false);
}
deviceService.saveAllAsOwner(pair.outputs, username, false);
return pair.input.getOutputs(); return pair.input.getOutputs();
} }
@PostMapping("/{id}/lights")
public List<OutputDevice> addLight(
@PathVariable("id") long inputId,
@RequestBody List<Long> lightId,
final Principal principal)
throws NotFoundException {
return toList(addOutput(inputId, lightId, principal.getName()));
}
@DeleteMapping("/{id}/lights")
public List<OutputDevice> removeLight(
@PathVariable("id") long inputId,
@RequestBody List<Long> lightId,
final Principal principal)
throws NotFoundException {
return toList(removeOutput(inputId, lightId, principal.getName()));
}
} }

View file

@ -1,13 +1,11 @@
package ch.usi.inf.sa4.sanmarinoes.smarthut.controller; package ch.usi.inf.sa4.sanmarinoes.smarthut.controller;
import static ch.usi.inf.sa4.sanmarinoes.smarthut.utils.Utils.toList;
import ch.usi.inf.sa4.sanmarinoes.smarthut.dto.GenericDeviceSaveReguest; import ch.usi.inf.sa4.sanmarinoes.smarthut.dto.GenericDeviceSaveReguest;
import ch.usi.inf.sa4.sanmarinoes.smarthut.dto.KnobDimmerDimRequest; import ch.usi.inf.sa4.sanmarinoes.smarthut.dto.KnobDimmerDimRequest;
import ch.usi.inf.sa4.sanmarinoes.smarthut.error.NotFoundException; import ch.usi.inf.sa4.sanmarinoes.smarthut.error.NotFoundException;
import ch.usi.inf.sa4.sanmarinoes.smarthut.models.*; import ch.usi.inf.sa4.sanmarinoes.smarthut.models.*;
import ch.usi.inf.sa4.sanmarinoes.smarthut.service.DeviceService;
import java.security.Principal; import java.security.Principal;
import java.util.List;
import java.util.Set; import java.util.Set;
import javax.validation.Valid; import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
@ -17,44 +15,32 @@ import org.springframework.web.bind.annotation.*;
@RestController @RestController
@EnableAutoConfiguration @EnableAutoConfiguration
@RequestMapping("/knobDimmer") @RequestMapping("/knobDimmer")
public class KnobDimmerController public class KnobDimmerController extends InputDeviceConnectionController<KnobDimmer, Dimmable> {
extends InputDeviceConnectionController<KnobDimmer, DimmableLight> {
@Autowired private DeviceService deviceService;
@Autowired private KnobDimmerRepository knobDimmerRepository; @Autowired private KnobDimmerRepository knobDimmerRepository;
@Autowired private DimmableLightRepository dimmableLightRepository;
@Autowired @Autowired
protected KnobDimmerController( protected KnobDimmerController(
KnobDimmerRepository inputRepository, DimmableLightRepository outputRepository) { KnobDimmerRepository inputRepository, DimmableRepository<Dimmable> outputRepository) {
super( super(inputRepository, outputRepository, Dimmable.KNOB_DIMMER_DIMMABLE_CONNECTOR);
inputRepository,
outputRepository,
DimmableLight.KNOB_DIMMER_DIMMABLE_LIGHT_CONNECTOR);
this.knobDimmerRepository = inputRepository; this.knobDimmerRepository = inputRepository;
this.dimmableLightRepository = outputRepository;
}
@GetMapping
public List<KnobDimmer> findAll() {
return toList(knobDimmerRepository.findAll());
}
@GetMapping("/{id}")
public KnobDimmer findById(@PathVariable("id") long id) throws NotFoundException {
return knobDimmerRepository.findById(id).orElseThrow(NotFoundException::new);
} }
@PostMapping @PostMapping
public KnobDimmer create(@Valid @RequestBody GenericDeviceSaveReguest kd) { public KnobDimmer create(
@Valid @RequestBody GenericDeviceSaveReguest kd, final Principal principal)
throws NotFoundException {
deviceService.throwIfRoomNotOwned(kd.getRoomId(), principal.getName());
KnobDimmer newKD = new KnobDimmer(); KnobDimmer newKD = new KnobDimmer();
newKD.setName(kd.getName()); newKD.setName(kd.getName());
newKD.setRoomId(kd.getRoomId()); newKD.setRoomId(kd.getRoomId());
return knobDimmerRepository.save(newKD); return deviceService.saveAsOwner(newKD, principal.getName());
} }
@PutMapping("/dimTo") @PutMapping("/dimTo")
public Set<DimmableLight> dimTo( public Set<Dimmable> dimTo(
@Valid @RequestBody final KnobDimmerDimRequest bd, final Principal principal) @Valid @RequestBody final KnobDimmerDimRequest bd, final Principal principal)
throws NotFoundException { throws NotFoundException {
final KnobDimmer dimmer = final KnobDimmer dimmer =
@ -63,27 +49,14 @@ public class KnobDimmerController
.orElseThrow(NotFoundException::new); .orElseThrow(NotFoundException::new);
dimmer.setLightIntensity(bd.getIntensity()); dimmer.setLightIntensity(bd.getIntensity());
dimmableLightRepository.saveAll(dimmer.getOutputs()); deviceService.saveAllAsOwner(dimmer.getOutputs(), principal.getName(), false);
return dimmer.getOutputs(); return dimmer.getOutputs();
} }
@PostMapping("/{id}/lights")
public Set<? extends OutputDevice> addLight(
@PathVariable("id") long inputId, @RequestParam("lightId") Long lightId)
throws NotFoundException {
return addOutput(inputId, lightId);
}
@DeleteMapping("/{id}/lights")
public Set<? extends OutputDevice> removeLight(
@PathVariable("id") long inputId, @RequestParam("lightId") Long lightId)
throws NotFoundException {
return removeOutput(inputId, lightId);
}
@DeleteMapping("/{id}") @DeleteMapping("/{id}")
public void delete(@PathVariable("id") long id) { public void delete(@PathVariable("id") long id, final Principal principal)
knobDimmerRepository.deleteById(id); throws NotFoundException {
deviceService.delete(id, principal.getName());
} }
} }

View file

@ -1,14 +1,13 @@
package ch.usi.inf.sa4.sanmarinoes.smarthut.controller; package ch.usi.inf.sa4.sanmarinoes.smarthut.controller;
import static ch.usi.inf.sa4.sanmarinoes.smarthut.utils.Utils.toList;
import ch.usi.inf.sa4.sanmarinoes.smarthut.dto.GenericDeviceSaveReguest; import ch.usi.inf.sa4.sanmarinoes.smarthut.dto.GenericDeviceSaveReguest;
import ch.usi.inf.sa4.sanmarinoes.smarthut.error.NotFoundException; import ch.usi.inf.sa4.sanmarinoes.smarthut.error.NotFoundException;
import ch.usi.inf.sa4.sanmarinoes.smarthut.models.MotionSensor; import ch.usi.inf.sa4.sanmarinoes.smarthut.models.MotionSensor;
import ch.usi.inf.sa4.sanmarinoes.smarthut.models.MotionSensorRepository; import ch.usi.inf.sa4.sanmarinoes.smarthut.models.MotionSensorRepository;
import ch.usi.inf.sa4.sanmarinoes.smarthut.service.DeviceService;
import ch.usi.inf.sa4.sanmarinoes.smarthut.service.MotionSensorService;
import ch.usi.inf.sa4.sanmarinoes.smarthut.socket.SensorSocketEndpoint; import ch.usi.inf.sa4.sanmarinoes.smarthut.socket.SensorSocketEndpoint;
import java.security.Principal; import java.security.Principal;
import java.util.List;
import javax.validation.Valid; import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
@ -19,43 +18,21 @@ import org.springframework.web.bind.annotation.*;
@RequestMapping("/motionSensor") @RequestMapping("/motionSensor")
public class MotionSensorController { public class MotionSensorController {
@Autowired private MotionSensorRepository motionSensorService; @Autowired private DeviceService deviceService;
@Autowired private MotionSensorService motionSensorService;
@Autowired private MotionSensorRepository motionSensorRepository;
@Autowired private SensorSocketEndpoint sensorSocketEndpoint; @Autowired private SensorSocketEndpoint sensorSocketEndpoint;
@GetMapping
public List<MotionSensor> findAll() {
return toList(motionSensorService.findAll());
}
@GetMapping("/{id}")
public MotionSensor findById(@PathVariable("id") long id) throws NotFoundException {
return motionSensorService.findById(id).orElseThrow(NotFoundException::new);
}
@PostMapping @PostMapping
public MotionSensor create(@Valid @RequestBody GenericDeviceSaveReguest ms) { public MotionSensor create(
@Valid @RequestBody GenericDeviceSaveReguest ms, final Principal principal)
throws NotFoundException {
deviceService.throwIfRoomNotOwned(ms.getRoomId(), principal.getName());
MotionSensor newMS = new MotionSensor(); MotionSensor newMS = new MotionSensor();
newMS.setName(ms.getName()); newMS.setName(ms.getName());
newMS.setRoomId(ms.getRoomId()); newMS.setRoomId(ms.getRoomId());
return motionSensorService.save(newMS); return deviceService.saveAsOwner(newMS, principal.getName());
}
/**
* 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")
@ -65,15 +42,17 @@ public class MotionSensorController {
final Principal principal) final Principal principal)
throws NotFoundException { throws NotFoundException {
return updateDetectionFromMotionSensor( return motionSensorService.updateDetectionFromMotionSensor(
motionSensorService motionSensorRepository
.findByIdAndUsername(sensorId, principal.getName()) .findByIdAndUsername(sensorId, principal.getName())
.orElseThrow(NotFoundException::new), .orElseThrow(NotFoundException::new),
detected); detected,
principal.getName());
} }
@DeleteMapping("/{id}") @DeleteMapping("/{id}")
public void delete(@PathVariable("id") long id) { public void delete(@PathVariable("id") long id, final Principal principal)
motionSensorService.deleteById(id); throws NotFoundException {
deviceService.delete(id, principal.getName());
} }
} }

View file

@ -0,0 +1,62 @@
package ch.usi.inf.sa4.sanmarinoes.smarthut.controller;
import ch.usi.inf.sa4.sanmarinoes.smarthut.dto.RangeTriggerSaveRequest;
import ch.usi.inf.sa4.sanmarinoes.smarthut.error.NotFoundException;
import ch.usi.inf.sa4.sanmarinoes.smarthut.models.RangeTrigger;
import ch.usi.inf.sa4.sanmarinoes.smarthut.models.RangeTriggerRepository;
import java.util.List;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@EnableAutoConfiguration
@RequestMapping("/rangeTrigger")
public class RangeTriggerController {
@Autowired RangeTriggerRepository rangeTriggerRepository;
@GetMapping("/{automationId}")
public List<RangeTrigger<?>> getAll(@PathVariable long automationId) {
return rangeTriggerRepository.findAllByAutomationId(automationId);
}
private RangeTrigger<?> save(RangeTrigger<?> newRL, RangeTriggerSaveRequest s) {
newRL.setDeviceId(s.getDeviceId());
newRL.setAutomationId(s.getAutomationId());
newRL.setOperator(s.getOperator());
newRL.setRange(s.getRange());
return rangeTriggerRepository.save(newRL);
}
@PostMapping
public RangeTrigger<?> create(
@Valid @RequestBody RangeTriggerSaveRequest booleanTriggerSaveRequest) {
return save(new RangeTrigger<>(), booleanTriggerSaveRequest);
}
@PutMapping
public RangeTrigger<?> update(
@Valid @RequestBody RangeTriggerSaveRequest booleanTriggerSaveRequest)
throws NotFoundException {
return save(
rangeTriggerRepository
.findById(booleanTriggerSaveRequest.getId())
.orElseThrow(NotFoundException::new),
booleanTriggerSaveRequest);
}
@DeleteMapping("/{id}")
public void delete(@PathVariable long id) {
rangeTriggerRepository.deleteById(id);
}
}

View file

@ -2,10 +2,11 @@ package ch.usi.inf.sa4.sanmarinoes.smarthut.controller;
import static ch.usi.inf.sa4.sanmarinoes.smarthut.utils.Utils.toList; import static ch.usi.inf.sa4.sanmarinoes.smarthut.utils.Utils.toList;
import ch.usi.inf.sa4.sanmarinoes.smarthut.dto.RegularLightSaveRequest; import ch.usi.inf.sa4.sanmarinoes.smarthut.dto.SwitchableSaveRequest;
import ch.usi.inf.sa4.sanmarinoes.smarthut.error.DuplicateStateException;
import ch.usi.inf.sa4.sanmarinoes.smarthut.error.NotFoundException; import ch.usi.inf.sa4.sanmarinoes.smarthut.error.NotFoundException;
import ch.usi.inf.sa4.sanmarinoes.smarthut.models.RegularLight; import ch.usi.inf.sa4.sanmarinoes.smarthut.models.*;
import ch.usi.inf.sa4.sanmarinoes.smarthut.models.RegularLightRepository; import ch.usi.inf.sa4.sanmarinoes.smarthut.service.DeviceService;
import java.security.Principal; import java.security.Principal;
import java.util.List; import java.util.List;
import javax.validation.Valid; import javax.validation.Valid;
@ -18,51 +19,99 @@ import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
@RestController @RestController
@EnableAutoConfiguration @EnableAutoConfiguration
@RequestMapping("/regularLight") @RequestMapping("/regularLight")
public class RegularLightController { public class RegularLightController extends GuestEnabledController<RegularLight> {
@Autowired private RegularLightRepository regularLightService; private RegularLightRepository regularLightRepository;
private SceneRepository sceneRepository;
private StateRepository<State<?>> stateRepository;
private DeviceService deviceService;
@Autowired
public RegularLightController(
UserRepository userRepository,
RegularLightRepository regularLightRepository,
SceneRepository sceneRepository,
StateRepository<State<?>> stateRepository,
DeviceService deviceService) {
super(userRepository, regularLightRepository);
this.regularLightRepository = regularLightRepository;
this.sceneRepository = sceneRepository;
this.stateRepository = stateRepository;
this.deviceService = deviceService;
}
@GetMapping @GetMapping
public List<RegularLight> findAll() { public List<RegularLight> findAll() {
return toList(regularLightService.findAll()); return toList(regularLightRepository.findAll());
} }
@GetMapping("/{id}") @GetMapping("/{id}")
public RegularLight findById(@PathVariable("id") long id) throws NotFoundException { public RegularLight findById(@PathVariable("id") long id) throws NotFoundException {
return regularLightService.findById(id).orElseThrow(NotFoundException::new); return regularLightRepository.findById(id).orElseThrow(NotFoundException::new);
} }
private RegularLight save(RegularLight newRL, RegularLightSaveRequest rl) { private RegularLight save(
newRL.setName(rl.getName()); RegularLight initial, SwitchableSaveRequest rl, String username, Long hostId)
newRL.setRoomId(rl.getRoomId()); throws NotFoundException {
newRL.setOn(rl.isOn()); initial.setName(rl.getName());
initial.setRoomId(rl.getRoomId());
initial.setOn(rl.isOn());
return regularLightService.save(newRL); if (hostId == null) {
return deviceService.saveAsOwner(initial, username);
} else {
return deviceService.saveAsGuest(initial, username, hostId);
}
} }
@PostMapping @PostMapping
public RegularLight create(@Valid @RequestBody RegularLightSaveRequest rl) { public RegularLight create(
return save(new RegularLight(), rl); @Valid @RequestBody SwitchableSaveRequest rl, final Principal principal)
throws NotFoundException {
deviceService.throwIfRoomNotOwned(rl.getRoomId(), principal.getName());
return save(new RegularLight(), rl, principal.getName(), null);
} }
@PutMapping @PutMapping
public RegularLight update( public RegularLight update(
@Valid @RequestBody RegularLightSaveRequest rl, final Principal principal) @Valid @RequestBody SwitchableSaveRequest rl, final Principal principal, Long hostId)
throws NotFoundException { throws NotFoundException {
return save( return save(
regularLightService fetchIfOwnerOrGuest(principal, rl.getId(), hostId),
.findByIdAndUsername(rl.getId(), principal.getName()) rl,
.orElseThrow(NotFoundException::new), principal.getName(),
rl); hostId);
} }
@DeleteMapping("/{id}") @DeleteMapping("/{id}")
public void delete(@PathVariable("id") long id) { public void delete(@PathVariable("id") long id, final Principal principal)
regularLightService.deleteById(id); throws NotFoundException {
deviceService.delete(id, principal.getName());
}
// the full url should be: "/regularLight/{id}/state?sceneId={sceneId}
// however it is not necessary to specify the query in the mapping
@PostMapping("/{id}/state")
public State<? extends Switchable> sceneBinding(
@PathVariable("id") long deviceId,
@RequestParam long sceneId,
final Principal principal)
throws NotFoundException, DuplicateStateException {
RegularLight d =
regularLightRepository
.findByIdAndUsername(deviceId, principal.getName())
.orElseThrow(NotFoundException::new);
State<? extends Switchable> s = d.cloneState();
sceneRepository.findById(sceneId).orElseThrow(NotFoundException::new);
s.setSceneId(sceneId);
if (stateRepository.countByDeviceIdAndSceneId(deviceId, sceneId) > 0)
throw new DuplicateStateException();
return stateRepository.save(s);
} }
} }

View file

@ -5,6 +5,9 @@ import static ch.usi.inf.sa4.sanmarinoes.smarthut.utils.Utils.toList;
import ch.usi.inf.sa4.sanmarinoes.smarthut.dto.RoomSaveRequest; import ch.usi.inf.sa4.sanmarinoes.smarthut.dto.RoomSaveRequest;
import ch.usi.inf.sa4.sanmarinoes.smarthut.error.NotFoundException; import ch.usi.inf.sa4.sanmarinoes.smarthut.error.NotFoundException;
import ch.usi.inf.sa4.sanmarinoes.smarthut.models.*; import ch.usi.inf.sa4.sanmarinoes.smarthut.models.*;
import ch.usi.inf.sa4.sanmarinoes.smarthut.service.DeviceService;
import ch.usi.inf.sa4.sanmarinoes.smarthut.service.ThermostatService;
import ch.usi.inf.sa4.sanmarinoes.smarthut.utils.Utils;
import java.security.Principal; import java.security.Principal;
import java.util.*; import java.util.*;
import javax.validation.Valid; import javax.validation.Valid;
@ -21,7 +24,7 @@ public class RoomController {
@Autowired private UserRepository userRepository; @Autowired private UserRepository userRepository;
@Autowired private DeviceRepository<Device> deviceRepository; @Autowired private DeviceService deviceService;
@Autowired private SwitchRepository switchRepository; @Autowired private SwitchRepository switchRepository;
@ -29,14 +32,40 @@ public class RoomController {
@Autowired private KnobDimmerRepository knobDimmerRepository; @Autowired private KnobDimmerRepository knobDimmerRepository;
@Autowired private ThermostatService thermostatService;
private <T> List<T> fetchOwnerOrGuest(
final List<T> list, Long hostId, final Principal principal) throws NotFoundException {
if (hostId == null) {
return list;
} else {
return Utils.returnIfGuest(userRepository, list, hostId, principal);
}
}
@GetMapping @GetMapping
public List<Room> findAll() { public List<Room> findAll(
return toList(roomRepository.findAll()); @RequestParam(value = "hostId", required = false) Long hostId,
final Principal principal)
throws NotFoundException {
List<Room> rooms =
toList(
hostId != null
? roomRepository.findByUserId(hostId)
: roomRepository.findByUsername(principal.getName()));
return fetchOwnerOrGuest(rooms, hostId, principal);
} }
@GetMapping("/{id}") @GetMapping("/{id}")
public @ResponseBody Room findById(@PathVariable("id") long id) throws NotFoundException { public @ResponseBody Room findById(
return roomRepository.findById(id).orElseThrow(NotFoundException::new); @PathVariable("id") long id,
final Principal principal,
@RequestParam(value = "hostId", required = false) Long hostId)
throws NotFoundException {
Room room = roomRepository.findById(id).orElseThrow(NotFoundException::new);
fetchOwnerOrGuest(null, hostId, principal);
return room;
} }
@PostMapping @PostMapping
@ -86,11 +115,16 @@ public class RoomController {
} }
@DeleteMapping("/{id}") @DeleteMapping("/{id}")
public void deleteById(@PathVariable("id") long id) { public void deleteById(@PathVariable("id") long id, final Principal principal)
throws NotFoundException {
switchRepository.deleteAllByRoomId(id); switchRepository.deleteAllByRoomId(id);
knobDimmerRepository.deleteAllByRoomId(id); knobDimmerRepository.deleteAllByRoomId(id);
buttonDimmerRepository.deleteAllByRoomId(id); buttonDimmerRepository.deleteAllByRoomId(id);
roomRepository.deleteById(id); final Room r =
roomRepository
.findByIdAndUsername(id, principal.getName())
.orElseThrow(NotFoundException::new);
roomRepository.delete(r);
} }
/** /**
@ -98,7 +132,11 @@ public class RoomController {
* id). * id).
*/ */
@GetMapping(path = "/{roomId}/devices") @GetMapping(path = "/{roomId}/devices")
public List<Device> getDevices(@PathVariable("roomId") long roomid) { public List<Device> getDevices(
return deviceRepository.findByRoomId(roomid); @PathVariable("roomId") long roomId,
final Principal principal,
@RequestParam(value = "hostId", required = false) Long hostId)
throws NotFoundException {
return deviceService.findAll(roomId, hostId, principal.getName());
} }
} }

View file

@ -0,0 +1,107 @@
package ch.usi.inf.sa4.sanmarinoes.smarthut.controller;
import static ch.usi.inf.sa4.sanmarinoes.smarthut.utils.Utils.toList;
import ch.usi.inf.sa4.sanmarinoes.smarthut.dto.SceneSaveRequest;
import ch.usi.inf.sa4.sanmarinoes.smarthut.error.NotFoundException;
import ch.usi.inf.sa4.sanmarinoes.smarthut.models.*;
import ch.usi.inf.sa4.sanmarinoes.smarthut.service.SceneService;
import java.security.Principal;
import java.util.List;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
@RestController
@EnableAutoConfiguration
@RequestMapping("/scene")
public class SceneController {
@Autowired private SceneRepository sceneRepository;
@Autowired private SceneService sceneService;
@Autowired private UserRepository userService;
@Autowired private StateRepository<State<?>> stateService;
@GetMapping
public List<Scene> findAll(Principal principal) {
return toList(sceneRepository.findByUsername(principal.getName()));
}
@GetMapping("/{id}")
public @ResponseBody Scene findById(@PathVariable("id") long id, Principal principal)
throws NotFoundException {
return sceneRepository
.findByIdAndUsername(id, principal.getName())
.orElseThrow(NotFoundException::new);
}
@PostMapping
public @ResponseBody Scene create(
@Valid @RequestBody SceneSaveRequest s, final Principal principal) {
final String username = principal.getName();
final Long userId = userService.findByUsername(username).getId();
final Scene newScene = new Scene();
newScene.setUserId(userId);
newScene.setName(s.getName());
newScene.setGuestAccessEnabled(s.isGuestAccessEnabled());
return sceneRepository.save(newScene);
}
@PostMapping("/{id}/apply")
public @ResponseBody List<Device> apply(@PathVariable("id") long id, final Principal principal)
throws NotFoundException {
final Scene newScene =
sceneRepository
.findByIdAndUsername(id, principal.getName())
.orElseThrow(NotFoundException::new);
return sceneService.apply(newScene);
}
@PutMapping("/{id}")
public @ResponseBody Scene update(
@PathVariable("id") long id, @RequestBody SceneSaveRequest s, final Principal principal)
throws NotFoundException {
final Scene newScene =
sceneRepository
.findByIdAndUsername(id, principal.getName())
.orElseThrow(NotFoundException::new);
if (s.getName() != null) {
newScene.setName(s.getName());
}
newScene.setGuestAccessEnabled(s.isGuestAccessEnabled());
return sceneRepository.save(newScene);
}
@DeleteMapping("/{id}")
public void deleteById(@PathVariable("id") long id) {
stateService.deleteAllBySceneId(id);
sceneRepository.deleteById(id);
}
/**
* Returns a List<State> of all Devices that are associated to a given scene (identified by its
* id).
*/
@GetMapping(path = "/{sceneId}/states")
public List<State<?>> getDevices(@PathVariable("sceneId") long sceneId) {
Iterable<State<?>> states = stateService.findBySceneId(sceneId);
return toList(states);
}
}

View file

@ -0,0 +1,63 @@
package ch.usi.inf.sa4.sanmarinoes.smarthut.controller;
import ch.usi.inf.sa4.sanmarinoes.smarthut.dto.ScenePrioritySaveRequest;
import ch.usi.inf.sa4.sanmarinoes.smarthut.error.NotFoundException;
import ch.usi.inf.sa4.sanmarinoes.smarthut.models.ScenePriority;
import ch.usi.inf.sa4.sanmarinoes.smarthut.models.ScenePriorityRepository;
import java.util.List;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@EnableAutoConfiguration
@RequestMapping("/scenePriority")
public class ScenePriorityController {
@Autowired ScenePriorityRepository scenePriorityRepository;
@GetMapping("/{automationId}")
public List<ScenePriority> getByAutomationId(@PathVariable long automationId)
throws NotFoundException {
return scenePriorityRepository.findAllByAutomationId(automationId);
}
private ScenePriority save(ScenePriority newRL, ScenePrioritySaveRequest s) {
newRL.setPriority(s.getPriority());
newRL.setAutomationId(s.getAutomationId());
newRL.setSceneId(s.getSceneId());
return scenePriorityRepository.save(newRL);
}
@PostMapping
public ScenePriority create(
@Valid @RequestBody ScenePrioritySaveRequest scenePrioritySaveRequest) {
return save(new ScenePriority(), scenePrioritySaveRequest);
}
@PutMapping
public ScenePriority update(
@Valid @RequestBody ScenePrioritySaveRequest scenePrioritySaveRequest)
throws NotFoundException {
return save(
scenePriorityRepository
.findById(scenePrioritySaveRequest.getSceneId())
.orElseThrow(NotFoundException::new),
scenePrioritySaveRequest);
}
@DeleteMapping("/{id}")
public void delete(@PathVariable long id) {
scenePriorityRepository.deleteBySceneId(id);
}
}

View file

@ -0,0 +1,85 @@
package ch.usi.inf.sa4.sanmarinoes.smarthut.controller;
import ch.usi.inf.sa4.sanmarinoes.smarthut.dto.SwitchableSaveRequest;
import ch.usi.inf.sa4.sanmarinoes.smarthut.error.DuplicateStateException;
import ch.usi.inf.sa4.sanmarinoes.smarthut.error.NotFoundException;
import ch.usi.inf.sa4.sanmarinoes.smarthut.models.*;
import ch.usi.inf.sa4.sanmarinoes.smarthut.service.DeviceService;
import java.security.Principal;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
@EnableAutoConfiguration
@RequestMapping("/securityCamera")
public class SecurityCameraController {
@Autowired private DeviceService deviceService;
@Autowired private SecurityCameraRepository securityCameraService;
@Autowired private SceneRepository sceneRepository;
@Autowired private StateRepository<State<?>> stateRepository;
@Autowired private RoomRepository roomRepository;
private SecurityCamera save(
SecurityCamera newSC, SwitchableSaveRequest sc, final Principal principal) {
newSC.setName(sc.getName());
newSC.setRoomId(sc.getRoomId());
newSC.setOn(sc.isOn());
return deviceService.saveAsOwner(newSC, principal.getName());
}
@PostMapping
public SecurityCamera create(
@Valid @RequestBody SwitchableSaveRequest sc, final Principal principal)
throws NotFoundException {
deviceService.throwIfRoomNotOwned(sc.getRoomId(), principal.getName());
return save(new SecurityCamera(), sc, principal);
}
@PutMapping
public SecurityCamera update(
@Valid @RequestBody SwitchableSaveRequest sc, final Principal principal)
throws NotFoundException {
return save(
securityCameraService
.findByIdAndUsername(sc.getId(), principal.getName())
.orElseThrow(NotFoundException::new),
sc,
principal);
}
@DeleteMapping("/{id}")
public void delete(@PathVariable("id") long id, final Principal principal)
throws NotFoundException {
deviceService.delete(id, principal.getName());
}
@PostMapping("/{id}/state")
public State<? extends Switchable> sceneBinding(
@PathVariable("id") long deviceId,
@RequestParam long sceneId,
final Principal principal)
throws NotFoundException, DuplicateStateException {
SecurityCamera d =
securityCameraService
.findByIdAndUsername(deviceId, principal.getName())
.orElseThrow(NotFoundException::new);
State<? extends Switchable> s = d.cloneState();
sceneRepository.findById(sceneId).orElseThrow(NotFoundException::new);
s.setSceneId(sceneId);
if (stateRepository.countByDeviceIdAndSceneId(deviceId, sceneId) > 0)
throw new DuplicateStateException();
return stateRepository.save(s);
}
}

View file

@ -1,15 +1,14 @@
package ch.usi.inf.sa4.sanmarinoes.smarthut.controller; package ch.usi.inf.sa4.sanmarinoes.smarthut.controller;
import static ch.usi.inf.sa4.sanmarinoes.smarthut.utils.Utils.toList;
import ch.usi.inf.sa4.sanmarinoes.smarthut.dto.SensorSaveRequest; import ch.usi.inf.sa4.sanmarinoes.smarthut.dto.SensorSaveRequest;
import ch.usi.inf.sa4.sanmarinoes.smarthut.error.NotFoundException; import ch.usi.inf.sa4.sanmarinoes.smarthut.error.NotFoundException;
import ch.usi.inf.sa4.sanmarinoes.smarthut.models.*; import ch.usi.inf.sa4.sanmarinoes.smarthut.models.*;
import ch.usi.inf.sa4.sanmarinoes.smarthut.service.DeviceService;
import ch.usi.inf.sa4.sanmarinoes.smarthut.service.SensorService;
import ch.usi.inf.sa4.sanmarinoes.smarthut.socket.SensorSocketEndpoint; import ch.usi.inf.sa4.sanmarinoes.smarthut.socket.SensorSocketEndpoint;
import java.math.BigDecimal; import java.math.BigDecimal;
import java.security.Principal; import java.security.Principal;
import java.util.*; import java.util.*;
import java.util.List;
import javax.validation.Valid; import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.*; import org.springframework.boot.autoconfigure.*;
@ -20,45 +19,26 @@ import org.springframework.web.bind.annotation.*;
@RequestMapping("/sensor") @RequestMapping("/sensor")
public class SensorController { public class SensorController {
@Autowired private DeviceService deviceService;
@Autowired private SensorRepository sensorRepository; @Autowired private SensorRepository sensorRepository;
@Autowired private SensorSocketEndpoint sensorSocketEndpoint; @Autowired private SensorSocketEndpoint sensorSocketEndpoint;
@GetMapping @Autowired private SensorService sensorService;
public List<Sensor> findAll() {
return toList(sensorRepository.findAll());
}
@GetMapping("/{id}")
public Sensor findById(@PathVariable("id") long id) throws NotFoundException {
return sensorRepository.findById(id).orElseThrow(NotFoundException::new);
}
@PostMapping @PostMapping
public Sensor create(@Valid @RequestBody SensorSaveRequest s) { public Sensor create(@Valid @RequestBody SensorSaveRequest s, final Principal principal)
throws NotFoundException {
deviceService.throwIfRoomNotOwned(s.getRoomId(), principal.getName());
Sensor newSensor = new Sensor(); Sensor newSensor = new Sensor();
newSensor.setSensor(s.getSensor()); newSensor.setSensor(s.getSensor());
newSensor.setName(s.getName()); newSensor.setName(s.getName());
newSensor.setRoomId(s.getRoomId()); newSensor.setRoomId(s.getRoomId());
newSensor.setValue(s.getValue()); newSensor.setValue(s.getValue());
return sensorRepository.save(newSensor); return deviceService.saveAsOwner(newSensor, principal.getName());
}
/**
* 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")
@ -67,7 +47,7 @@ public class SensorController {
@RequestParam("value") BigDecimal value, @RequestParam("value") BigDecimal value,
final Principal principal) final Principal principal)
throws NotFoundException { throws NotFoundException {
return updateValueFromSensor( return sensorService.updateValueFromSensor(
sensorRepository sensorRepository
.findByIdAndUsername(sensorId, principal.getName()) .findByIdAndUsername(sensorId, principal.getName())
.orElseThrow(NotFoundException::new), .orElseThrow(NotFoundException::new),
@ -75,7 +55,8 @@ public class SensorController {
} }
@DeleteMapping("/{id}") @DeleteMapping("/{id}")
public void deleteById(@PathVariable("id") long id) { public void deleteById(@PathVariable("id") long id, final Principal principal)
sensorRepository.deleteById(id); throws NotFoundException {
deviceService.delete(id, principal.getName());
} }
} }

View file

@ -1,13 +1,11 @@
package ch.usi.inf.sa4.sanmarinoes.smarthut.controller; package ch.usi.inf.sa4.sanmarinoes.smarthut.controller;
import static ch.usi.inf.sa4.sanmarinoes.smarthut.utils.Utils.toList; import ch.usi.inf.sa4.sanmarinoes.smarthut.dto.SwitchableSaveRequest;
import ch.usi.inf.sa4.sanmarinoes.smarthut.error.DuplicateStateException;
import ch.usi.inf.sa4.sanmarinoes.smarthut.dto.SmartPlugSaveRequest;
import ch.usi.inf.sa4.sanmarinoes.smarthut.error.NotFoundException; import ch.usi.inf.sa4.sanmarinoes.smarthut.error.NotFoundException;
import ch.usi.inf.sa4.sanmarinoes.smarthut.models.*; import ch.usi.inf.sa4.sanmarinoes.smarthut.models.*;
import ch.usi.inf.sa4.sanmarinoes.smarthut.service.DeviceService;
import java.security.Principal; import java.security.Principal;
import java.util.*;
import java.util.List;
import javax.validation.Valid; import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.*; import org.springframework.boot.autoconfigure.*;
@ -18,40 +16,36 @@ import org.springframework.web.bind.annotation.*;
@RequestMapping("/smartPlug") @RequestMapping("/smartPlug")
public class SmartPlugController { public class SmartPlugController {
@Autowired private DeviceService deviceService;
@Autowired private SmartPlugRepository smartPlugRepository; @Autowired private SmartPlugRepository smartPlugRepository;
@Autowired private SceneRepository sceneRepository;
@Autowired private StateRepository<State<?>> stateRepository;
@GetMapping private SmartPlug save(SmartPlug newSP, SwitchableSaveRequest sp, final Principal principal) {
public List<SmartPlug> findAll() {
return toList(smartPlugRepository.findAll());
}
@GetMapping("/{id}")
public SmartPlug findById(@PathVariable("id") long id) throws NotFoundException {
return smartPlugRepository.findById(id).orElseThrow(NotFoundException::new);
}
private SmartPlug save(SmartPlug newSP, SmartPlugSaveRequest sp) {
newSP.setOn(sp.isOn()); newSP.setOn(sp.isOn());
newSP.setId(sp.getId()); newSP.setId(sp.getId());
newSP.setName(sp.getName()); newSP.setName(sp.getName());
newSP.setRoomId(sp.getRoomId()); newSP.setRoomId(sp.getRoomId());
return smartPlugRepository.save(newSP); return deviceService.saveAsOwner(newSP, principal.getName());
} }
@PostMapping @PostMapping
public SmartPlug create(@Valid @RequestBody SmartPlugSaveRequest sp) { public SmartPlug create(@Valid @RequestBody SwitchableSaveRequest sp, final Principal principal)
return save(new SmartPlug(), sp); throws NotFoundException {
deviceService.throwIfRoomNotOwned(sp.getRoomId(), principal.getName());
return save(new SmartPlug(), sp, principal);
} }
@PutMapping @PutMapping
public SmartPlug update(@Valid @RequestBody SmartPlugSaveRequest sp, final Principal principal) public SmartPlug update(@Valid @RequestBody SwitchableSaveRequest sp, final Principal principal)
throws NotFoundException { throws NotFoundException {
return save( return save(
smartPlugRepository smartPlugRepository
.findByIdAndUsername(sp.getId(), principal.getName()) .findByIdAndUsername(sp.getId(), principal.getName())
.orElseThrow(NotFoundException::new), .orElseThrow(NotFoundException::new),
sp); sp,
principal);
} }
@DeleteMapping("/{id}/meter") @DeleteMapping("/{id}/meter")
@ -67,7 +61,27 @@ public class SmartPlugController {
} }
@DeleteMapping("/{id}") @DeleteMapping("/{id}")
public void deleteById(@PathVariable("id") long id) { public void deleteById(@PathVariable("id") long id, final Principal principal)
smartPlugRepository.deleteById(id); throws NotFoundException {
deviceService.delete(id, principal.getName());
}
@PostMapping("/{id}/state")
public State<? extends Switchable> sceneBinding(
@PathVariable("id") long deviceId,
@RequestParam long sceneId,
final Principal principal)
throws NotFoundException, DuplicateStateException {
SmartPlug d =
smartPlugRepository
.findByIdAndUsername(deviceId, principal.getName())
.orElseThrow(NotFoundException::new);
State<? extends Switchable> s = d.cloneState();
sceneRepository.findById(sceneId).orElseThrow(NotFoundException::new);
s.setSceneId(sceneId);
if (stateRepository.countByDeviceIdAndSceneId(deviceId, sceneId) > 0)
throw new DuplicateStateException();
return stateRepository.save(s);
} }
} }

View file

@ -1,13 +1,11 @@
package ch.usi.inf.sa4.sanmarinoes.smarthut.controller; package ch.usi.inf.sa4.sanmarinoes.smarthut.controller;
import static ch.usi.inf.sa4.sanmarinoes.smarthut.utils.Utils.toList;
import ch.usi.inf.sa4.sanmarinoes.smarthut.dto.GenericDeviceSaveReguest; import ch.usi.inf.sa4.sanmarinoes.smarthut.dto.GenericDeviceSaveReguest;
import ch.usi.inf.sa4.sanmarinoes.smarthut.dto.SwitchOperationRequest; import ch.usi.inf.sa4.sanmarinoes.smarthut.dto.SwitchOperationRequest;
import ch.usi.inf.sa4.sanmarinoes.smarthut.error.NotFoundException; import ch.usi.inf.sa4.sanmarinoes.smarthut.error.NotFoundException;
import ch.usi.inf.sa4.sanmarinoes.smarthut.models.*; import ch.usi.inf.sa4.sanmarinoes.smarthut.models.*;
import ch.usi.inf.sa4.sanmarinoes.smarthut.service.DeviceService;
import java.security.Principal; import java.security.Principal;
import java.util.*;
import java.util.List; import java.util.List;
import javax.validation.Valid; import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
@ -21,6 +19,7 @@ public class SwitchController extends InputDeviceConnectionController<Switch, Sw
private SwitchRepository switchRepository; private SwitchRepository switchRepository;
private SwitchableRepository<Switchable> switchableRepository; private SwitchableRepository<Switchable> switchableRepository;
private DeviceService deviceService;
/** /**
* Contstructs the controller by requiring essential object for the controller implementation * Contstructs the controller by requiring essential object for the controller implementation
@ -30,33 +29,27 @@ public class SwitchController extends InputDeviceConnectionController<Switch, Sw
*/ */
@Autowired @Autowired
protected SwitchController( protected SwitchController(
SwitchRepository inputRepository, SwitchableRepository<Switchable> outputRepository) { SwitchRepository inputRepository,
SwitchableRepository<Switchable> outputRepository,
DeviceService deviceService) {
super(inputRepository, outputRepository, Switchable.SWITCH_SWITCHABLE_CONNECTOR); super(inputRepository, outputRepository, Switchable.SWITCH_SWITCHABLE_CONNECTOR);
this.deviceService = deviceService;
this.switchRepository = inputRepository; this.switchRepository = inputRepository;
this.switchableRepository = outputRepository;
}
@GetMapping
public List<Switch> findAll() {
return toList(switchRepository.findAll());
}
@GetMapping("/{id}")
public Switch findById(@PathVariable("id") long id) throws NotFoundException {
return switchRepository.findById(id).orElseThrow(NotFoundException::new);
} }
@PostMapping @PostMapping
public Switch create(@Valid @RequestBody GenericDeviceSaveReguest s) { public Switch create(@Valid @RequestBody GenericDeviceSaveReguest s, final Principal principal)
throws NotFoundException {
deviceService.throwIfRoomNotOwned(s.getRoomId(), principal.getName());
Switch newSwitch = new Switch(); Switch newSwitch = new Switch();
newSwitch.setName(s.getName()); newSwitch.setName(s.getName());
newSwitch.setRoomId(s.getRoomId()); newSwitch.setRoomId(s.getRoomId());
return switchRepository.save(newSwitch); return deviceService.saveAsOwner(newSwitch, principal.getName());
} }
@PutMapping("/operate") @PutMapping("/operate")
public Set<Switchable> operate( public List<Switchable> operate(
@Valid @RequestBody final SwitchOperationRequest sr, final Principal principal) @Valid @RequestBody final SwitchOperationRequest sr, final Principal principal)
throws NotFoundException { throws NotFoundException {
final Switch s = final Switch s =
@ -76,27 +69,13 @@ public class SwitchController extends InputDeviceConnectionController<Switch, Sw
break; break;
} }
switchableRepository.saveAll(s.getOutputs()); deviceService.saveAsOwner(s, principal.getName());
return deviceService.saveAllAsOwner(s.getOutputs(), principal.getName(), false);
return s.getOutputs();
}
@PostMapping("/{id}/lights")
public Set<? extends OutputDevice> addSwitchable(
@PathVariable("id") long inputId, @RequestParam("switchableId") Long switchableId)
throws NotFoundException {
return addOutput(inputId, switchableId);
}
@DeleteMapping("/{id}/lights")
public Set<? extends OutputDevice> removeSwitchable(
@PathVariable("id") long inputId, @RequestParam("switchableId") Long switchableId)
throws NotFoundException {
return removeOutput(inputId, switchableId);
} }
@DeleteMapping("/{id}") @DeleteMapping("/{id}")
public void deleteById(@PathVariable("id") long id) { public void deleteById(@PathVariable("id") long id, final Principal principal)
switchRepository.deleteById(id); throws NotFoundException {
deviceService.delete(id, principal.getName());
} }
} }

View file

@ -0,0 +1,38 @@
package ch.usi.inf.sa4.sanmarinoes.smarthut.controller;
import ch.usi.inf.sa4.sanmarinoes.smarthut.dto.SwitchableStateSaveRequest;
import ch.usi.inf.sa4.sanmarinoes.smarthut.error.NotFoundException;
import ch.usi.inf.sa4.sanmarinoes.smarthut.models.SwitchableState;
import ch.usi.inf.sa4.sanmarinoes.smarthut.models.SwitchableStateRepository;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@EnableAutoConfiguration
@RequestMapping("/switchableState")
public class SwitchableStateController {
@Autowired private SwitchableStateRepository switchableStateRepository;
@PutMapping
public SwitchableState<?> update(@Valid @RequestBody SwitchableStateSaveRequest ss)
throws NotFoundException {
final SwitchableState<?> initial =
switchableStateRepository.findById(ss.getId()).orElseThrow(NotFoundException::new);
initial.setOn(ss.isOn());
switchableStateRepository.save(initial);
return initial;
}
@DeleteMapping("/{id}")
public void delete(@PathVariable("id") long id) {
switchableStateRepository.deleteById(id);
}
}

View file

@ -0,0 +1,82 @@
package ch.usi.inf.sa4.sanmarinoes.smarthut.controller;
import ch.usi.inf.sa4.sanmarinoes.smarthut.dto.ThermostatSaveRequest;
import ch.usi.inf.sa4.sanmarinoes.smarthut.error.DuplicateStateException;
import ch.usi.inf.sa4.sanmarinoes.smarthut.error.NotFoundException;
import ch.usi.inf.sa4.sanmarinoes.smarthut.models.*;
import ch.usi.inf.sa4.sanmarinoes.smarthut.service.DeviceService;
import ch.usi.inf.sa4.sanmarinoes.smarthut.service.ThermostatService;
import java.security.Principal;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.*;
import org.springframework.web.bind.annotation.*;
@RestController
@EnableAutoConfiguration
@RequestMapping("/thermostat")
public class ThermostatController {
@Autowired private DeviceService deviceService;
@Autowired private ThermostatRepository thermostatRepository;
@Autowired private ThermostatService thermostatService;
@Autowired private SceneRepository sceneRepository;
@Autowired private StateRepository<State<?>> stateRepository;
private Thermostat save(Thermostat newT, ThermostatSaveRequest t, final Principal principal) {
newT.setTargetTemperature(t.getTargetTemperature());
newT.setId(t.getId());
newT.setName(t.getName());
newT.setRoomId(t.getRoomId());
newT.setMeasuredTemperature(t.getMeasuredTemperature());
newT.setUseExternalSensors(t.isUseExternalSensors());
newT.setOn(t.isTurnOn());
newT = deviceService.saveAsOwner(newT, principal.getName());
thermostatService.populateMeasuredTemperature(newT);
return newT;
}
@PostMapping
public Thermostat create(@Valid @RequestBody ThermostatSaveRequest t, final Principal principal)
throws NotFoundException {
deviceService.throwIfRoomNotOwned(t.getRoomId(), principal.getName());
return save(new Thermostat(), t, principal);
}
@PutMapping
public Thermostat update(@Valid @RequestBody ThermostatSaveRequest t, final Principal principal)
throws NotFoundException {
return save(
thermostatRepository
.findByIdAndUsername(t.getId(), principal.getName())
.orElseThrow(NotFoundException::new),
t,
principal);
}
@DeleteMapping("/{id}")
public void deleteById(@PathVariable("id") long id, final Principal principal)
throws NotFoundException {
deviceService.delete(id, principal.getName());
}
@PostMapping("/{id}/state")
public State<? extends Switchable> sceneBinding(
@PathVariable("id") long deviceId,
@RequestParam long sceneId,
final Principal principal)
throws NotFoundException, DuplicateStateException {
Thermostat d =
thermostatRepository
.findByIdAndUsername(deviceId, principal.getName())
.orElseThrow(NotFoundException::new);
State<? extends Switchable> s = d.cloneState();
sceneRepository.findById(sceneId).orElseThrow(NotFoundException::new);
s.setSceneId(sceneId);
if (stateRepository.countByDeviceIdAndSceneId(deviceId, sceneId) > 0)
throw new DuplicateStateException();
return stateRepository.save(s);
}
}

View file

@ -0,0 +1,97 @@
package ch.usi.inf.sa4.sanmarinoes.smarthut.dto;
import ch.usi.inf.sa4.sanmarinoes.smarthut.models.BooleanTrigger;
import ch.usi.inf.sa4.sanmarinoes.smarthut.models.RangeTrigger;
import ch.usi.inf.sa4.sanmarinoes.smarthut.models.ScenePriority;
import ch.usi.inf.sa4.sanmarinoes.smarthut.models.Trigger;
import java.util.List;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
public class AutomationFastUpdateRequest {
public abstract static class TriggerDTO {
@NotNull public long deviceId;
public abstract Trigger<?> toModel();
}
public static class BooleanTriggerDTO extends TriggerDTO {
@NotNull public boolean on;
@Override
public Trigger<?> toModel() {
BooleanTrigger<?> t = new BooleanTrigger<>();
t.setDeviceId(this.deviceId);
t.setOn(this.on);
return t;
}
}
public static class RangeTriggerDTO extends TriggerDTO {
@NotNull RangeTrigger.Operator operator;
@NotNull double range;
@Override
public Trigger<?> toModel() {
RangeTrigger<?> t = new RangeTrigger<>();
t.setDeviceId(this.deviceId);
t.setOperator(this.operator);
t.setRange(this.range);
return t;
}
}
public static class ScenePriorityDTO {
@NotNull public long sceneId;
@NotNull
@Min(0)
public Integer priority;
public ScenePriority toModel() {
ScenePriority s = new ScenePriority();
s.setSceneId(sceneId);
s.setPriority(priority);
return s;
}
}
@NotNull private List<ScenePriorityDTO> scenes;
@NotNull private List<TriggerDTO> triggers;
@NotNull private long id;
@NotNull @NotEmpty private String name;
public long getId() {
return id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<ScenePriorityDTO> getScenes() {
return scenes;
}
public void setScenes(List<ScenePriorityDTO> scenes) {
this.scenes = scenes;
}
public List<TriggerDTO> getTriggers() {
return triggers;
}
public void setTriggers(List<TriggerDTO> triggers) {
this.triggers = triggers;
}
public void setId(long id) {
this.id = id;
}
}

View file

@ -0,0 +1,23 @@
package ch.usi.inf.sa4.sanmarinoes.smarthut.dto;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
public class AutomationSaveRequest {
private long id;
@NotNull @NotEmpty private String name;
public long getId() {
return id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}

View file

@ -0,0 +1,42 @@
package ch.usi.inf.sa4.sanmarinoes.smarthut.dto;
import javax.validation.constraints.NotNull;
public class BooleanTriggerSaveRequest {
private long id;
@NotNull private Long deviceId;
@NotNull private Long automationId;
private boolean on;
public long getId() {
return id;
}
public Long getDeviceId() {
return deviceId;
}
public void setDeviceId(Long deviceId) {
this.deviceId = deviceId;
}
public Long getAutomationId() {
return automationId;
}
public void setAutomationId(Long automationId) {
this.automationId = automationId;
}
public boolean isOn() {
return on;
}
public void setOn(boolean on) {
this.on = on;
}
}

View file

@ -4,10 +4,10 @@ import javax.validation.constraints.Max;
import javax.validation.constraints.Min; import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull; import javax.validation.constraints.NotNull;
public class DimmableLightSaveRequest { public class DimmableSaveRequest {
/** Device id (used only for update requests) */ /** Device id (used only for update requests) */
private Long id; private long id;
/** The light intensity value. Goes from 0 (off) to 100 (on) */ /** The light intensity value. Goes from 0 (off) to 100 (on) */
@NotNull @NotNull
@ -48,11 +48,11 @@ public class DimmableLightSaveRequest {
this.intensity = intensity; this.intensity = intensity;
} }
public Long getId() { public long getId() {
return id; return id;
} }
public void setId(Long id) { public void setId(long id) {
this.id = id; this.id = id;
} }
} }

View file

@ -0,0 +1,28 @@
package ch.usi.inf.sa4.sanmarinoes.smarthut.dto;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
public class DimmableStateSaveRequest {
/** Device id (used only for update requests) */
@NotNull private Long id;
@NotNull
@Min(0)
@Max(100)
private Integer intensity = 0;
public Integer getIntensity() {
return intensity;
}
public void setIntensity(Integer intensity) {
this.intensity = intensity;
}
public Long getId() {
return id;
}
}

View file

@ -0,0 +1,13 @@
package ch.usi.inf.sa4.sanmarinoes.smarthut.dto;
public class GuestPermissionsRequest {
private boolean cameraEnabled;
public boolean isCameraEnabled() {
return cameraEnabled;
}
public void setCameraEnabled(boolean cameraEnabled) {
this.cameraEnabled = cameraEnabled;
}
}

View file

@ -0,0 +1,57 @@
package ch.usi.inf.sa4.sanmarinoes.smarthut.dto;
import ch.usi.inf.sa4.sanmarinoes.smarthut.models.RangeTrigger;
import javax.validation.constraints.NotNull;
public class RangeTriggerSaveRequest {
private long id;
@NotNull private Long deviceId;
@NotNull private Long automationId;
@NotNull private RangeTrigger.Operator operator;
@NotNull private double range;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public Long getDeviceId() {
return deviceId;
}
public void setDeviceId(Long deviceId) {
this.deviceId = deviceId;
}
public Long getAutomationId() {
return automationId;
}
public void setAutomationId(Long automationId) {
this.automationId = automationId;
}
public RangeTrigger.Operator getOperator() {
return operator;
}
public void setOperator(RangeTrigger.Operator operator) {
this.operator = operator;
}
public double getRange() {
return range;
}
public void setRange(Double range) {
this.range = range;
}
}

View file

@ -0,0 +1,38 @@
package ch.usi.inf.sa4.sanmarinoes.smarthut.dto;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
public class ScenePrioritySaveRequest {
@NotNull private Long automationId;
@Min(0)
private Integer priority;
@NotNull private Long sceneId;
public Long getAutomationId() {
return automationId;
}
public void setAutomationId(Long automationId) {
this.automationId = automationId;
}
public Integer getPriority() {
return priority;
}
public void setPriority(Integer priority) {
this.priority = priority;
}
public Long getSceneId() {
return sceneId;
}
public void setSceneId(Long sceneId) {
this.sceneId = sceneId;
}
}

View file

@ -0,0 +1,36 @@
package ch.usi.inf.sa4.sanmarinoes.smarthut.dto;
import com.sun.istack.NotNull;
import javax.persistence.Column;
public class SceneSaveRequest {
/** Room identifier */
private long id;
/** The user given name of this room (e.g. 'Master bedroom') */
@NotNull private String name;
/** Determines whether a guest can access this scene */
@Column @NotNull private boolean guestAccessEnabled;
public boolean isGuestAccessEnabled() {
return guestAccessEnabled;
}
public void setGuestAccessEnabled(boolean guestAccessEnabled) {
this.guestAccessEnabled = guestAccessEnabled;
}
public long getId() {
return id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}

View file

@ -1,52 +0,0 @@
package ch.usi.inf.sa4.sanmarinoes.smarthut.dto;
import javax.validation.constraints.NotNull;
public class SmartPlugSaveRequest {
/** Whether the smart plug is on */
@NotNull private boolean on;
/** Device identifier */
private long id;
/**
* The room this device belongs in, as a foreign key id. To use when updating and inserting from
* a REST call.
*/
@NotNull private Long roomId;
/** The name of the device as assigned by the user (e.g. 'Master bedroom light') */
@NotNull private String name;
public void setRoomId(Long roomId) {
this.roomId = roomId;
}
public void setName(String name) {
this.name = name;
}
public long getId() {
return id;
}
public Long getRoomId() {
return roomId;
}
public String getName() {
return name;
}
public boolean isOn() {
return on;
}
public void setOn(boolean on) {
this.on = on;
}
public void setId(long id) {
this.id = id;
}
}

View file

@ -2,7 +2,7 @@ package ch.usi.inf.sa4.sanmarinoes.smarthut.dto;
import javax.validation.constraints.NotNull; import javax.validation.constraints.NotNull;
public class RegularLightSaveRequest { public class SwitchableSaveRequest {
/** The state of this switch */ /** The state of this switch */
private boolean on; private boolean on;

View file

@ -0,0 +1,23 @@
package ch.usi.inf.sa4.sanmarinoes.smarthut.dto;
import javax.validation.constraints.NotNull;
public class SwitchableStateSaveRequest {
/** Device id (used only for update requests) */
@NotNull private Long id;
@NotNull private boolean on;
public boolean isOn() {
return on;
}
public void setOn(boolean on) {
this.on = on;
}
public Long getId() {
return id;
}
}

View file

@ -0,0 +1,85 @@
package ch.usi.inf.sa4.sanmarinoes.smarthut.dto;
import java.math.BigDecimal;
import javax.validation.constraints.NotNull;
public class ThermostatSaveRequest {
/** Device identifier */
private long id;
/**
* The room this device belongs in, as a foreign key id. To use when updating and inserting from
* a REST call.
*/
@NotNull private Long roomId;
/** The name of the device as assigned by the user (e.g. 'Master bedroom light') */
@NotNull private String name;
/** Temperature to be reached */
@NotNull private BigDecimal targetTemperature;
@NotNull private boolean useExternalSensors;
@NotNull private BigDecimal measuredTemperature;
/** State of this thermostat */
@NotNull private boolean turnOn;
public boolean isTurnOn() {
return turnOn;
}
public void setTurnOn(boolean turnOn) {
this.turnOn = turnOn;
}
public boolean isUseExternalSensors() {
return useExternalSensors;
}
public void setUseExternalSensors(boolean useExternalSensors) {
this.useExternalSensors = useExternalSensors;
}
public BigDecimal getTargetTemperature() {
return this.targetTemperature;
}
public void setTargetTemperature(BigDecimal targetTemperature) {
this.targetTemperature = targetTemperature;
}
public void setRoomId(Long roomId) {
this.roomId = roomId;
}
public void setName(String name) {
this.name = name;
}
public long getId() {
return id;
}
public Long getRoomId() {
return roomId;
}
public String getName() {
return name;
}
public void setId(long id) {
this.id = id;
}
public BigDecimal getMeasuredTemperature() {
return measuredTemperature;
}
public void setMeasuredTemperature(BigDecimal measuredTemperature) {
this.measuredTemperature = measuredTemperature;
}
}

View file

@ -0,0 +1,12 @@
package ch.usi.inf.sa4.sanmarinoes.smarthut.error;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
@ResponseStatus(code = HttpStatus.BAD_REQUEST)
public class DuplicateStateException extends Exception {
public DuplicateStateException() {
super(
"Cannot create state since it has already been created for this scene and this device");
}
}

View file

@ -0,0 +1,81 @@
package ch.usi.inf.sa4.sanmarinoes.smarthut.models;
import ch.usi.inf.sa4.sanmarinoes.smarthut.config.GsonExclude;
import io.swagger.annotations.ApiModelProperty;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.*;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
@Entity
public class Automation {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id", updatable = false, nullable = false, unique = true)
@ApiModelProperty(hidden = true)
private long id;
@ManyToOne
@JoinColumn(name = "user_id", updatable = false, insertable = false)
@GsonExclude
private User user;
@NotNull
@Column(name = "user_id", nullable = false)
@GsonExclude
private Long userId;
@OneToMany(mappedBy = "automation", orphanRemoval = true)
private Set<Trigger<?>> triggers = new HashSet<>();
@OneToMany(mappedBy = "automation", cascade = CascadeType.REMOVE)
private Set<ScenePriority> scenes = new HashSet<>();
@NotNull @NotEmpty private String name;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public Set<Trigger<?>> getStates() {
return triggers;
}
public Set<ScenePriority> getScenes() {
return scenes;
}
public Set<Trigger<?>> getTriggers() {
return triggers;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public Long getUserId() {
return userId;
}
public void setUserId(Long userId) {
this.userId = userId;
}
}

View file

@ -0,0 +1,15 @@
package ch.usi.inf.sa4.sanmarinoes.smarthut.models;
import java.util.List;
import java.util.Optional;
import org.springframework.data.jpa.repository.EntityGraph;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;
public interface AutomationRepository extends CrudRepository<Automation, Long> {
@EntityGraph(attributePaths = {"scenes", "triggers"})
List<Automation> findAllByUserId(@Param("userId") long userId);
@EntityGraph(attributePaths = {"scenes", "triggers"})
Optional<Automation> findByIdAndUserId(@Param("id") long id, @Param("userId") long userId);
}

View file

@ -0,0 +1,32 @@
package ch.usi.inf.sa4.sanmarinoes.smarthut.models;
import javax.persistence.Column;
import javax.persistence.Entity;
@Entity
public class BooleanTrigger<D extends Device & BooleanTriggerable> extends Trigger<D> {
@Column(name = "switchable_on")
private boolean on;
public BooleanTrigger() {
super("booleanTrigger");
}
public boolean isOn() {
return on;
}
public void setOn(boolean on) {
this.on = on;
}
public boolean check(boolean on) {
return this.on == on;
}
@Override
public boolean triggered() {
return getDevice().readTriggerState() == isOn();
}
}

View file

@ -0,0 +1,10 @@
package ch.usi.inf.sa4.sanmarinoes.smarthut.models;
import java.util.List;
import org.springframework.data.repository.query.Param;
public interface BooleanTriggerRepository
extends TriggerRepository<BooleanTrigger<? extends Device>> {
List<BooleanTrigger<?>> findAllByAutomationId(@Param("automationId") long automationId);
}

View file

@ -0,0 +1,5 @@
package ch.usi.inf.sa4.sanmarinoes.smarthut.models;
public interface BooleanTriggerable {
boolean readTriggerState();
}

View file

@ -18,14 +18,14 @@ public class ButtonDimmer extends Dimmer {
/** Increases the current intensity level of the dimmable light by DIM_INCREMENT */ /** Increases the current intensity level of the dimmable light by DIM_INCREMENT */
public void increaseIntensity() { public void increaseIntensity() {
for (DimmableLight dl : getOutputs()) { for (Dimmable dl : getOutputs()) {
dl.setIntensity(dl.getIntensity() + DIM_INCREMENT); dl.setIntensity(dl.getIntensity() + DIM_INCREMENT);
} }
} }
/** Decreases the current intensity level of the dimmable light by DIM_INCREMENT */ /** Decreases the current intensity level of the dimmable light by DIM_INCREMENT */
public void decreaseIntensity() { public void decreaseIntensity() {
for (DimmableLight dl : getOutputs()) { for (Dimmable dl : getOutputs()) {
dl.setIntensity(dl.getIntensity() - DIM_INCREMENT); dl.setIntensity(dl.getIntensity() - DIM_INCREMENT);
} }
} }

View file

@ -23,25 +23,25 @@ public interface Connector<I extends InputDevice, O extends OutputDevice> {
void connect(I input, O output, boolean connect); void connect(I input, O output, boolean connect);
/** /**
* Produces a basic implementation of a connector, assuming there is a OneToMany relationship * Produces a basic implementation of a connector, assuming there is a ManyToMany relationship
* between J and K * between J and K
* *
* @param outputsGetter the getter method of the set of outputs on the input class * @param outputsGetter the getter method of the set of outputs on the input class
* @param inputSetter the setter method for the input id on the output class * @param inputsGetter the getter method of the set of outputs on the input class
* @param <J> the input device type * @param <J> the input device type
* @param <K> the output device type * @param <K> the output device type
* @return a Connector implementation for the pair of types J and K * @return a Connector implementation for the pair of types J and K
*/ */
static <J extends InputDevice, K extends OutputDevice> Connector<J, K> basic( static <J extends InputDevice, K extends OutputDevice> Connector<J, K> basic(
Function<J, Set<? super K>> outputsGetter, BiConsumer<K, Long> inputSetter) { Function<J, Set<? super K>> outputsGetter, Function<K, Set<? super J>> inputsGetter) {
return (i, o, connect) -> { return (i, o, connect) -> {
if (connect) { if (connect) {
outputsGetter.apply(i).add(o); outputsGetter.apply(i).add(o);
inputsGetter.apply(o).add(i);
} else { } else {
outputsGetter.apply(i).remove(o); outputsGetter.apply(i).remove(o);
inputsGetter.apply(o).remove(i);
} }
inputSetter.accept(o, connect ? i.getId() : null);
}; };
} }
} }

View file

@ -0,0 +1,14 @@
package ch.usi.inf.sa4.sanmarinoes.smarthut.models;
import javax.persistence.Entity;
/**
* Represents a curtain. The intensity represents how much the curtains are opened,
* 0 is completely closed 100 is completely open
*/
@Entity
public class Curtains extends Dimmable {
public Curtains() {
super("curtains");
}
}

View file

@ -0,0 +1,3 @@
package ch.usi.inf.sa4.sanmarinoes.smarthut.models;
public interface CurtainsRepository extends DimmableRepository<Curtains> {}

View file

@ -1,14 +1,17 @@
package ch.usi.inf.sa4.sanmarinoes.smarthut.models; package ch.usi.inf.sa4.sanmarinoes.smarthut.models;
import ch.usi.inf.sa4.sanmarinoes.smarthut.config.GsonExclude; import ch.usi.inf.sa4.sanmarinoes.smarthut.config.GsonExclude;
import ch.usi.inf.sa4.sanmarinoes.smarthut.config.SocketGsonExclude;
import com.google.gson.annotations.SerializedName; import com.google.gson.annotations.SerializedName;
import io.swagger.annotations.ApiModelProperty; import io.swagger.annotations.ApiModelProperty;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.*; import javax.persistence.*;
import javax.validation.constraints.NotNull; import javax.validation.constraints.NotNull;
/** Generic abstraction for a smart home device */ /** Generic abstraction for a smart home device */
@Entity @Entity
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS) @Inheritance(strategy = InheritanceType.JOINED)
public abstract class Device { public abstract class Device {
/** Ways a device can behave in the automation flow. For now only input/output */ /** Ways a device can behave in the automation flow. For now only input/output */
@ -30,8 +33,14 @@ public abstract class Device {
@ManyToOne @ManyToOne
@JoinColumn(name = "room_id", updatable = false, insertable = false) @JoinColumn(name = "room_id", updatable = false, insertable = false)
@GsonExclude @GsonExclude
@SocketGsonExclude
private Room room; private Room room;
@OneToMany(mappedBy = "device", orphanRemoval = true)
@GsonExclude
@SocketGsonExclude
private Set<Trigger<? extends Device>> triggers = new HashSet<>();
/** /**
* The room this device belongs in, as a foreign key id. To use when updating and inserting from * The room this device belongs in, as a foreign key id. To use when updating and inserting from
* a REST call. * a REST call.
@ -57,6 +66,41 @@ public abstract class Device {
*/ */
@Transient private final FlowType flowType; @Transient private final FlowType flowType;
@OneToMany(mappedBy = "device", orphanRemoval = true)
@GsonExclude
@SocketGsonExclude
private Set<State<?>> states = new HashSet<>();
@Transient @GsonExclude private boolean fromHost = false;
@Transient @GsonExclude private boolean fromGuest = false;
@Transient @GsonExclude private boolean deleted = false;
public boolean isFromHost() {
return fromHost;
}
public boolean isDeleted() {
return deleted;
}
public void setDeleted(boolean deleted) {
this.deleted = deleted;
}
public boolean isFromGuest() {
return fromGuest;
}
public void setFromGuest(boolean fromGuest) {
this.fromGuest = fromGuest;
}
public void setFromHost(boolean fromHost) {
this.fromHost = fromHost;
}
public long getId() { public long getId() {
return id; return id;
} }

View file

@ -2,12 +2,11 @@ package ch.usi.inf.sa4.sanmarinoes.smarthut.models;
import java.util.List; import java.util.List;
import java.util.Optional; import java.util.Optional;
import javax.transaction.Transactional;
import org.springframework.data.jpa.repository.Query; import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository; import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param; import org.springframework.data.repository.query.Param;
import javax.transaction.Transactional;
/** /**
* DeviceRepository acts as a superclass for the other repositories so to mirror in the database the * DeviceRepository acts as a superclass for the other repositories so to mirror in the database the
* class inheritance present among the various devices. * class inheritance present among the various devices.
@ -15,6 +14,10 @@ import javax.transaction.Transactional;
public interface DeviceRepository<T extends Device> extends CrudRepository<T, Long> { public interface DeviceRepository<T extends Device> extends CrudRepository<T, Long> {
List<T> findByRoomId(@Param("roomId") long roomId); List<T> findByRoomId(@Param("roomId") long roomId);
@Query(
"SELECT COUNT(d) FROM Device d JOIN d.room r JOIN r.user u WHERE d.name = ?1 AND u.username = ?2")
Integer findDuplicates(String name, String username);
/** /**
* Finds devices by their id and a username * Finds devices by their id and a username
* *
@ -26,6 +29,16 @@ public interface DeviceRepository<T extends Device> extends CrudRepository<T, Lo
@Query("SELECT d FROM Device d JOIN d.room r JOIN r.user u WHERE d.id = ?1 AND u.username = ?2") @Query("SELECT d FROM Device d JOIN d.room r JOIN r.user u WHERE d.id = ?1 AND u.username = ?2")
Optional<T> findByIdAndUsername(Long id, String username); Optional<T> findByIdAndUsername(Long id, String username);
/**
* Finds devices by their id and a user id
*
* @param id the device id
* @param userId a User's id
* @return an optional device, empty if none found
*/
@Query("SELECT d FROM Device d JOIN d.room r JOIN r.user u WHERE d.id = ?1 AND u.id = ?2")
Optional<T> findByIdAndUserId(Long id, Long userId);
/** /**
* Finds all devices belonging to a user * Finds all devices belonging to a user
* *

View file

@ -0,0 +1,95 @@
package ch.usi.inf.sa4.sanmarinoes.smarthut.models;
import ch.usi.inf.sa4.sanmarinoes.smarthut.config.GsonExclude;
import ch.usi.inf.sa4.sanmarinoes.smarthut.config.SocketGsonExclude;
import java.util.Set;
import javax.persistence.*;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
@Entity
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
public class Dimmable extends Switchable implements RangeTriggerable {
public static final Connector<KnobDimmer, Dimmable> KNOB_DIMMER_DIMMABLE_CONNECTOR =
Connector.basic(KnobDimmer::getOutputs, Dimmable::getDimmers);
public static final Connector<ButtonDimmer, Dimmable> BUTTON_DIMMER_DIMMABLE_CONNECTOR =
Connector.basic(ButtonDimmer::getOutputs, Dimmable::getDimmers);
protected Dimmable(String kind) {
super(kind);
}
@ManyToMany(mappedBy = "dimmables", cascade = CascadeType.DETACH)
@GsonExclude
@SocketGsonExclude
private Set<Dimmer> dimmers;
/** The light intensity value. Goes from 0 (off) to 100 (on) */
@NotNull
@Column(nullable = false)
@Min(0)
@Max(100)
private Integer intensity = 0;
@NotNull
@Column(nullable = false)
private Integer oldIntensity = 100;
public Integer getIntensity() {
return intensity;
}
/**
* Sets the intensity to a certain level. Out of bound values are corrected to the respective
* extremums. An intensity level of 0 turns the light off, but keeps the old intensity level
* stored.
*
* @param intensity the intensity level (may be out of bounds)
*/
public void setIntensity(Integer intensity) {
if (intensity <= 0) {
this.intensity = 0;
} else if (intensity > 100) {
this.intensity = 100;
this.oldIntensity = 100;
} else {
this.intensity = intensity;
this.oldIntensity = intensity;
}
}
@Override
public boolean isOn() {
return intensity != 0;
}
@Override
public void setOn(boolean on) {
intensity = on ? oldIntensity : 0;
}
public Set<Dimmer> getDimmers() {
return this.dimmers;
}
public void readStateAndSet(DimmableState<? extends Dimmable> state) {
setIntensity(state.getIntensity());
}
@Override
public State<? extends Dimmable> cloneState() {
final DimmableState<Dimmable> newState = new DimmableState<>();
newState.setDeviceId(getId());
newState.setDevice(this);
newState.setIntensity(getIntensity());
return newState;
}
@Override
public double readTriggerState() {
return intensity;
}
}

View file

@ -1,89 +1,11 @@
package ch.usi.inf.sa4.sanmarinoes.smarthut.models; package ch.usi.inf.sa4.sanmarinoes.smarthut.models;
import ch.usi.inf.sa4.sanmarinoes.smarthut.config.GsonExclude; import javax.persistence.*;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
/** Represent a dimmable light */ /** Represent a dimmable light */
@Entity @Entity
public class DimmableLight extends Switchable { public class DimmableLight extends Dimmable {
public static final Connector<ButtonDimmer, DimmableLight>
BUTTON_DIMMER_DIMMABLE_LIGHT_CONNECTOR =
Connector.basic(ButtonDimmer::getOutputs, DimmableLight::setDimmerId);
public static final Connector<KnobDimmer, DimmableLight> KNOB_DIMMER_DIMMABLE_LIGHT_CONNECTOR =
Connector.basic(KnobDimmer::getOutputs, DimmableLight::setDimmerId);
public DimmableLight() { public DimmableLight() {
super("dimmableLight"); super("dimmableLight");
} }
@ManyToOne
@GsonExclude
@JoinColumn(name = "dimmer_id", updatable = false, insertable = false)
private Dimmer dimmer;
@Column(name = "dimmer_id")
private Long dimmerId;
/** The light intensity value. Goes from 0 (off) to 100 (on) */
@NotNull
@Column(nullable = false)
@Min(0)
@Max(100)
private Integer intensity = 0;
@NotNull
@Column(nullable = false)
private Integer oldIntensity = 100;
public Integer getIntensity() {
return intensity;
}
/**
* Sets the intensity to a certain level. Out of bound values are corrected to the respective
* extremums. An intensity level of 0 turns the light off, but keeps the old intensity level
* stored.
*
* @param intensity the intensity level (may be out of bounds)
*/
public void setIntensity(Integer intensity) {
if (intensity <= 0) {
this.intensity = 0;
} else if (intensity > 100) {
this.intensity = 100;
this.oldIntensity = 100;
} else {
this.intensity = intensity;
this.oldIntensity = intensity;
}
}
@Override
public boolean isOn() {
return intensity != 0;
}
@Override
public void setOn(boolean on) {
intensity = on ? oldIntensity : 0;
}
public void setDimmerId(Long dimmerId) {
this.dimmerId = dimmerId;
super.setSwitchId(null);
}
@Override
public void setSwitchId(Long switchId) {
super.setSwitchId(switchId);
this.dimmerId = null;
}
} }

View file

@ -1,3 +1,3 @@
package ch.usi.inf.sa4.sanmarinoes.smarthut.models; package ch.usi.inf.sa4.sanmarinoes.smarthut.models;
public interface DimmableLightRepository extends SwitchableRepository<DimmableLight> {} public interface DimmableLightRepository extends DimmableRepository<DimmableLight> {}

View file

@ -0,0 +1,4 @@
package ch.usi.inf.sa4.sanmarinoes.smarthut.models;
public interface DimmableRepository<T extends Dimmable> extends SwitchableRepository<T> {
}

View file

@ -0,0 +1,28 @@
package ch.usi.inf.sa4.sanmarinoes.smarthut.models;
import javax.persistence.Entity;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
/** Represent a state for an IDimmable device */
@Entity
public class DimmableState<T extends Dimmable> extends State<T> {
/** The light intensity value. Goes from 0 (off) to 100 (on) */
@Min(0)
@Max(100)
private int intensity = 0;
public int getIntensity() {
return intensity;
}
public void setIntensity(int dimAmount) {
this.intensity = dimAmount;
}
@Override
public void apply() {
getDevice().readStateAndSet(this);
}
}

View file

@ -0,0 +1,3 @@
package ch.usi.inf.sa4.sanmarinoes.smarthut.models;
public interface DimmableStateRepository extends StateRepository<DimmableState<?>> {}

View file

@ -1,12 +1,10 @@
package ch.usi.inf.sa4.sanmarinoes.smarthut.models; package ch.usi.inf.sa4.sanmarinoes.smarthut.models;
import ch.usi.inf.sa4.sanmarinoes.smarthut.config.GsonExclude;
import ch.usi.inf.sa4.sanmarinoes.smarthut.config.SocketGsonExclude;
import java.util.HashSet; import java.util.HashSet;
import java.util.Set; import java.util.Set;
import javax.persistence.Entity; import javax.persistence.*;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
import javax.persistence.OneToMany;
import javax.persistence.PreRemove;
/** Represents a generic dimmer input device */ /** Represents a generic dimmer input device */
@Entity @Entity
@ -16,8 +14,14 @@ public abstract class Dimmer extends InputDevice {
super(kind); super(kind);
} }
@OneToMany(mappedBy = "dimmer") @ManyToMany(cascade = CascadeType.DETACH)
private Set<DimmableLight> lights = new HashSet<>(); @GsonExclude
@SocketGsonExclude
@JoinTable(
name = "dimmer_dimmable",
joinColumns = @JoinColumn(name = "dimmer_id"),
inverseJoinColumns = @JoinColumn(name = "dimmable_id"))
private Set<Dimmable> dimmables = new HashSet<>();
/** /**
* Get the lights connected to this dimmer * Get the lights connected to this dimmer
@ -25,19 +29,12 @@ public abstract class Dimmer extends InputDevice {
* @return duh * @return duh
*/ */
@Override @Override
public Set<DimmableLight> getOutputs() { public Set<Dimmable> getOutputs() {
return this.lights; return this.dimmables;
} }
/** Add a light to be controller by this dimmer */ /** Add a light to be controller by this dimmer */
public void addDimmableLight(DimmableLight dimmableLight) { public void addDimmable(Dimmable dimmable) {
lights.add(dimmableLight); dimmables.add(dimmable);
}
@PreRemove
private void removeLightsFromDimmer() {
for (DimmableLight dl : getOutputs()) {
dl.setDimmerId(null);
}
} }
} }

View file

@ -0,0 +1,13 @@
package ch.usi.inf.sa4.sanmarinoes.smarthut.models;
import java.util.Optional;
import org.springframework.data.jpa.repository.EntityGraph;
import org.springframework.data.repository.CrudRepository;
public interface EagerUserRepository extends CrudRepository<User, Long> {
@EntityGraph(attributePaths = {"guests"})
User findByUsername(String username);
@EntityGraph(attributePaths = {"guests"})
Optional<User> findById(Long userId);
}

View file

@ -10,7 +10,7 @@ import javax.persistence.InheritanceType;
* environment (sensor) or the user (switch / dimmer). * environment (sensor) or the user (switch / dimmer).
*/ */
@Entity @Entity
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS) @Inheritance(strategy = InheritanceType.JOINED)
public abstract class InputDevice extends Device { public abstract class InputDevice extends Device {
public InputDevice(String kind) { public InputDevice(String kind) {
super(kind, FlowType.INPUT); super(kind, FlowType.INPUT);

View file

@ -1,5 +1,6 @@
package ch.usi.inf.sa4.sanmarinoes.smarthut.models; package ch.usi.inf.sa4.sanmarinoes.smarthut.models;
import javax.persistence.Column;
import javax.persistence.Entity; import javax.persistence.Entity;
/** /**
@ -7,7 +8,9 @@ import javax.persistence.Entity;
* value, like a knob) * value, like a knob)
*/ */
@Entity @Entity
public class KnobDimmer extends Dimmer { public class KnobDimmer extends Dimmer implements RangeTriggerable {
@Column private int intensity = 0;
public KnobDimmer() { public KnobDimmer() {
super("knobDimmer"); super("knobDimmer");
@ -19,8 +22,14 @@ public class KnobDimmer extends Dimmer {
* @param intensity the intensity (must be from 0 to 100) * @param intensity the intensity (must be from 0 to 100)
*/ */
public void setLightIntensity(int intensity) { public void setLightIntensity(int intensity) {
for (DimmableLight dl : getOutputs()) { this.intensity = intensity;
for (Dimmable dl : getOutputs()) {
dl.setIntensity(intensity); dl.setIntensity(intensity);
} }
} }
@Override
public double readTriggerState() {
return intensity;
}
} }

View file

@ -5,7 +5,7 @@ import javax.persistence.Entity;
/** Represents a motion sensor device */ /** Represents a motion sensor device */
@Entity @Entity
public class MotionSensor extends InputDevice { public class MotionSensor extends InputDevice implements BooleanTriggerable {
@Column(nullable = false) @Column(nullable = false)
private boolean detected; private boolean detected;
@ -21,4 +21,9 @@ public class MotionSensor extends InputDevice {
public MotionSensor() { public MotionSensor() {
super("motionSensor"); super("motionSensor");
} }
@Override
public boolean readTriggerState() {
return detected;
}
} }

View file

@ -7,9 +7,17 @@ import javax.persistence.*;
* ...). * ...).
*/ */
@Entity @Entity
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS) @Inheritance(strategy = InheritanceType.JOINED)
public abstract class OutputDevice extends Device { public abstract class OutputDevice extends Device {
public OutputDevice(String kind) { public OutputDevice(String kind) {
super(kind, FlowType.OUTPUT); super(kind, FlowType.OUTPUT);
} }
/**
* Creates a State<?> object initialized to point at this device and with values copied from
* this device's state
*
* @return a new State<?> object
*/
public abstract State<? extends OutputDevice> cloneState();
} }

View file

@ -0,0 +1,69 @@
package ch.usi.inf.sa4.sanmarinoes.smarthut.models;
import com.google.gson.annotations.SerializedName;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.validation.constraints.NotNull;
@Entity
public class RangeTrigger<D extends Device & RangeTriggerable> extends Trigger<D> {
public RangeTrigger() {
super("rangeTrigger");
}
@Override
public boolean triggered() {
double value = getDevice().readTriggerState();
switch (operator) {
case EQUAL:
return value == range;
case LESS:
return value < range;
case GREATER:
return value > range;
case GREATER_EQUAL:
return value >= range;
case LESS_EQUAL:
return value <= range;
}
throw new IllegalStateException();
}
public enum Operator {
@SerializedName("EQUAL")
EQUAL,
@SerializedName("LESS")
LESS,
@SerializedName("GREATER")
GREATER,
@SerializedName("LESS_EQUAL")
LESS_EQUAL,
@SerializedName("GREATER_EQUAL")
GREATER_EQUAL
}
@NotNull
@Column(nullable = false)
private Operator operator;
@NotNull
@Column(nullable = false)
private double range;
public Operator getOperator() {
return operator;
}
public void setOperator(Operator operator) {
this.operator = operator;
}
public double getRange() {
return range;
}
public void setRange(Double range) {
this.range = range;
}
}

View file

@ -0,0 +1,9 @@
package ch.usi.inf.sa4.sanmarinoes.smarthut.models;
import java.util.List;
import org.springframework.data.repository.query.Param;
public interface RangeTriggerRepository extends TriggerRepository<RangeTrigger<? extends Device>> {
List<RangeTrigger<?>> findAllByAutomationId(@Param("automationId") long automationId);
}

View file

@ -0,0 +1,5 @@
package ch.usi.inf.sa4.sanmarinoes.smarthut.models;
public interface RangeTriggerable {
double readTriggerState();
}

View file

@ -6,7 +6,7 @@ import javax.validation.constraints.NotNull;
/** Represents a standard non-dimmable light */ /** Represents a standard non-dimmable light */
@Entity @Entity
public class RegularLight extends Switchable { public class RegularLight extends Switchable implements BooleanTriggerable {
/** Whether the light is on or not */ /** Whether the light is on or not */
@Column(name = "light_on", nullable = false) @Column(name = "light_on", nullable = false)
@ -27,4 +27,9 @@ public class RegularLight extends Switchable {
public void setOn(boolean on) { public void setOn(boolean on) {
this.on = on; this.on = on;
} }
@Override
public boolean readTriggerState() {
return on;
}
} }

View file

@ -1,5 +1,6 @@
package ch.usi.inf.sa4.sanmarinoes.smarthut.models; package ch.usi.inf.sa4.sanmarinoes.smarthut.models;
import java.util.List;
import java.util.Optional; import java.util.Optional;
import org.springframework.data.jpa.repository.Query; import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository; import org.springframework.data.repository.CrudRepository;
@ -15,4 +16,10 @@ public interface RoomRepository extends CrudRepository<Room, Long> {
*/ */
@Query("SELECT r FROM Room r JOIN r.user u WHERE r.id = ?1 AND u.username = ?2") @Query("SELECT r FROM Room r JOIN r.user u WHERE r.id = ?1 AND u.username = ?2")
Optional<Room> findByIdAndUsername(Long id, String username); Optional<Room> findByIdAndUsername(Long id, String username);
@Query("SELECT r FROM Room r JOIN r.user u WHERE u.username = ?1")
List<Room> findByUsername(String username);
@Query("SELECT r FROM Room r JOIN r.user u WHERE u.id = ?1")
List<Room> findByUserId(Long hostId);
} }

View file

@ -0,0 +1,92 @@
package ch.usi.inf.sa4.sanmarinoes.smarthut.models;
import ch.usi.inf.sa4.sanmarinoes.smarthut.config.GsonExclude;
import io.swagger.annotations.ApiModelProperty;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.*;
import javax.validation.constraints.NotNull;
/**
* Represent a collection of state changes to devices even in different rooms but belonging to the
* same user
*/
@Entity
public class Scene {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id", updatable = false, nullable = false, unique = true)
@ApiModelProperty(hidden = true)
private long id;
@ManyToOne
@JoinColumn(name = "user_id", updatable = false, insertable = false)
@GsonExclude
private User user;
@NotNull
@Column(name = "user_id", nullable = false)
@GsonExclude
private Long userId;
@OneToMany(mappedBy = "scene", orphanRemoval = true)
@GsonExclude
private Set<State<?>> states = new HashSet<>();
/** The user given name of this room (e.g. 'Master bedroom') */
@NotNull
@Column(nullable = false)
private String name;
/** Determines whether a guest can access this scene */
@Column private boolean guestAccessEnabled;
public boolean isGuestAccessEnabled() {
return guestAccessEnabled;
}
public void setGuestAccessEnabled(boolean guestAccessEnabled) {
this.guestAccessEnabled = guestAccessEnabled;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public Set<State<?>> getStates() {
return states;
}
public void setStates(Set<State<?>> states) {
this.states = states;
}
public Long getUserId() {
return userId;
}
public void setUserId(Long userId) {
this.userId = userId;
}
}

View file

@ -0,0 +1,97 @@
package ch.usi.inf.sa4.sanmarinoes.smarthut.models;
import ch.usi.inf.sa4.sanmarinoes.smarthut.config.GsonExclude;
import io.swagger.annotations.ApiModelProperty;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.PreRemove;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
@Entity
public class ScenePriority {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id", updatable = false, nullable = false, unique = true)
@ApiModelProperty(hidden = true)
private long id;
@ManyToOne
@JoinColumn(name = "automation_id", updatable = false, insertable = false)
@GsonExclude
private Automation automation;
@Column(name = "automation_id", nullable = false)
@NotNull
private Long automationId;
@NotNull
@Min(0)
@Column(nullable = false)
private Integer priority;
@ManyToOne
@JoinColumn(name = "scene_id", updatable = false, insertable = false)
@GsonExclude
private Scene scene;
@Column(name = "scene_id", nullable = false, updatable = false)
@NotNull
private Long sceneId;
public Integer getPriority() {
return priority;
}
public void setPriority(Integer priority) {
this.priority = priority;
}
public Automation getAutomation() {
return automation;
}
public void setAutomation(Automation automation) {
this.automation = automation;
}
public Long getAutomationId() {
return automationId;
}
public ScenePriority setAutomationId(Long automationId) {
this.automationId = automationId;
return this;
}
public Scene getScene() {
return scene;
}
public void setScene(Scene scene) {
this.scene = scene;
}
public Long getSceneId() {
return sceneId;
}
public void setSceneId(Long sceneId) {
this.sceneId = sceneId;
}
@PreRemove
public void preRemove() {
this.setAutomation(null);
this.setAutomationId(null);
this.setScene(null);
this.setSceneId(null);
}
}

View file

@ -0,0 +1,19 @@
package ch.usi.inf.sa4.sanmarinoes.smarthut.models;
import java.util.List;
import javax.transaction.Transactional;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;
public interface ScenePriorityRepository extends CrudRepository<ScenePriority, Long> {
List<ScenePriority> findAllBySceneId(@Param("sceneId") long sceneId);
@Transactional
void deleteBySceneId(@Param("sceneId") long sceneId);
List<ScenePriority> findAllByAutomationId(@Param("automationId") long automationId);
@Transactional
void deleteAllByAutomationId(Long automationId);
}

View file

@ -0,0 +1,22 @@
package ch.usi.inf.sa4.sanmarinoes.smarthut.models;
import java.util.List;
import java.util.Optional;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
public interface SceneRepository extends CrudRepository<Scene, Long> {
/**
* Finds a room by their id and a username
*
* @param id the scene id
* @param username a User's username
* @return an optional scene, empty if none found
*/
@Query("SELECT s FROM Scene s JOIN s.user u WHERE s.id = ?1 AND u.username = ?2")
Optional<Scene> findByIdAndUsername(Long id, String username);
@Query("SELECT s FROM Scene s JOIN s.user u WHERE u.username = ?1")
List<Scene> findByUsername(String username);
}

View file

@ -0,0 +1,41 @@
package ch.usi.inf.sa4.sanmarinoes.smarthut.models;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.validation.constraints.NotNull;
@Entity
public class SecurityCamera extends Switchable implements BooleanTriggerable {
public SecurityCamera() {
super("securityCamera");
this.on = false;
}
@Column(name = "camera_on", nullable = false)
@NotNull
private boolean on;
@Column(name = "video", nullable = false)
@NotNull
private String path = "/security_camera_videos/security_camera_1.mp4";
public String getPath() {
return path;
}
@Override
public boolean isOn() {
return on;
}
@Override
public void setOn(boolean on) {
this.on = on;
}
@Override
public boolean readTriggerState() {
return on;
}
}

View file

@ -0,0 +1,3 @@
package ch.usi.inf.sa4.sanmarinoes.smarthut.models;
public interface SecurityCameraRepository extends SwitchableRepository<SecurityCamera> {}

View file

@ -11,7 +11,7 @@ import javax.validation.constraints.NotNull;
/** A sensor input device that measures a quantity in a continuous scale (e.g. temperature) */ /** A sensor input device that measures a quantity in a continuous scale (e.g. temperature) */
@Entity @Entity
public class Sensor extends InputDevice { public class Sensor extends InputDevice implements RangeTriggerable {
public static final Map<SensorType, BigDecimal> TYPICAL_VALUES = public static final Map<SensorType, BigDecimal> TYPICAL_VALUES =
Map.of( Map.of(
@ -19,6 +19,11 @@ public class Sensor extends InputDevice {
SensorType.HUMIDITY, new BigDecimal(40.0), SensorType.HUMIDITY, new BigDecimal(40.0),
SensorType.LIGHT, new BigDecimal(1000)); SensorType.LIGHT, new BigDecimal(1000));
@Override
public double readTriggerState() {
return value.doubleValue();
}
/** 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 {
/** A sensor that measures temperature in degrees celsius */ /** A sensor that measures temperature in degrees celsius */

View file

@ -1,3 +1,7 @@
package ch.usi.inf.sa4.sanmarinoes.smarthut.models; package ch.usi.inf.sa4.sanmarinoes.smarthut.models;
public interface SensorRepository extends DeviceRepository<Sensor> {} import java.util.List;
public interface SensorRepository extends DeviceRepository<Sensor> {
List<Sensor> findAllBySensor(Sensor.SensorType sensor);
}

View file

@ -1,5 +1,6 @@
package ch.usi.inf.sa4.sanmarinoes.smarthut.models; package ch.usi.inf.sa4.sanmarinoes.smarthut.models;
import java.math.BigDecimal; import java.math.BigDecimal;
import javax.persistence.Column; import javax.persistence.Column;
import javax.persistence.Entity; import javax.persistence.Entity;
@ -7,7 +8,7 @@ import javax.validation.constraints.NotNull;
/** A smart plug that can be turned either on or off */ /** A smart plug that can be turned either on or off */
@Entity @Entity
public class SmartPlug extends Switchable { public class SmartPlug extends Switchable implements BooleanTriggerable {
/** The average consumption of an active plug when on in Watt */ /** The average consumption of an active plug when on in Watt */
public static final Double AVERAGE_CONSUMPTION_KW = 200.0; public static final Double AVERAGE_CONSUMPTION_KW = 200.0;
@ -44,4 +45,9 @@ public class SmartPlug extends Switchable {
public SmartPlug() { public SmartPlug() {
super("smartPlug"); super("smartPlug");
} }
@Override
public boolean readTriggerState() {
return on;
}
} }

View file

@ -0,0 +1,96 @@
package ch.usi.inf.sa4.sanmarinoes.smarthut.models;
import ch.usi.inf.sa4.sanmarinoes.smarthut.config.GsonExclude;
import io.swagger.annotations.ApiModelProperty;
import javax.persistence.*;
import javax.validation.constraints.NotNull;
/**
* Represents instructions on how to change the state of a particular device. Many states (plus
* other properties) form a Scene
*/
@Entity
@Table(uniqueConstraints = {@UniqueConstraint(columnNames = {"device_id", "scene_id"})})
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
public abstract class State<D extends OutputDevice> {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id", updatable = false, nullable = false, unique = true)
@ApiModelProperty(hidden = true)
private long id;
@ManyToOne(targetEntity = OutputDevice.class)
@JoinColumn(name = "device_id", updatable = false, insertable = false)
@GsonExclude
private D device;
/**
* The device this state belongs in, as a foreign key id. To use when updating and inserting
* from a REST call.
*/
@Column(name = "device_id", nullable = false)
@NotNull
private Long deviceId;
@ManyToOne
@JoinColumn(name = "scene_id", updatable = false, insertable = false)
@GsonExclude
private Scene scene;
@Column(name = "scene_id", nullable = false)
@NotNull
private Long sceneId;
/** Sets the state of the connected device to the state represented by this object. */
public abstract void apply();
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public D getDevice() {
return device;
}
public void setDevice(D device) {
this.device = device;
}
public Long getDeviceId() {
return deviceId;
}
public void setDeviceId(Long deviceId) {
this.deviceId = deviceId;
}
public Scene getScene() {
return scene;
}
public void setScene(Scene scene) {
this.scene = scene;
}
public Long getSceneId() {
return sceneId;
}
public void setSceneId(Long sceneId) {
this.sceneId = sceneId;
}
@PreRemove
public void removeDeviceAndScene() {
this.setScene(null);
this.setSceneId(null);
this.setDevice(null);
this.setDeviceId(null);
}
}

View file

@ -0,0 +1,16 @@
package ch.usi.inf.sa4.sanmarinoes.smarthut.models;
import java.util.List;
import javax.transaction.Transactional;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;
public interface StateRepository<T extends State<?>> extends CrudRepository<T, Long> {
@Transactional
void deleteAllBySceneId(long roomId);
List<T> findBySceneId(@Param("sceneId") long sceneId);
Integer countByDeviceIdAndSceneId(long deviceId, long sceneId);
}

View file

@ -1,17 +1,22 @@
package ch.usi.inf.sa4.sanmarinoes.smarthut.models; package ch.usi.inf.sa4.sanmarinoes.smarthut.models;
import ch.usi.inf.sa4.sanmarinoes.smarthut.config.GsonExclude;
import ch.usi.inf.sa4.sanmarinoes.smarthut.config.SocketGsonExclude;
import java.util.HashSet; import java.util.HashSet;
import java.util.Set; import java.util.Set;
import javax.persistence.Column; import javax.persistence.*;
import javax.persistence.Entity;
import javax.persistence.OneToMany;
import javax.persistence.PreRemove;
/** A switch input device */ /** A switch input device */
@Entity @Entity
public class Switch extends InputDevice { public class Switch extends InputDevice implements BooleanTriggerable {
@OneToMany(mappedBy = "switchDevice") @ManyToMany(cascade = CascadeType.DETACH)
@GsonExclude
@SocketGsonExclude
@JoinTable(
name = "switch_switchable",
joinColumns = @JoinColumn(name = "switch_id"),
inverseJoinColumns = @JoinColumn(name = "switchable_id"))
private Set<Switchable> switchables = new HashSet<>(); private Set<Switchable> switchables = new HashSet<>();
/** The state of this switch */ /** The state of this switch */
@ -53,10 +58,8 @@ public class Switch extends InputDevice {
return switchables; return switchables;
} }
@PreRemove @Override
public void removeSwitchable() { public boolean readTriggerState() {
for (Switchable s : getOutputs()) { return on;
s.setSwitchId(null);
}
} }
} }

View file

@ -1,23 +1,23 @@
package ch.usi.inf.sa4.sanmarinoes.smarthut.models; package ch.usi.inf.sa4.sanmarinoes.smarthut.models;
import ch.usi.inf.sa4.sanmarinoes.smarthut.config.GsonExclude; import ch.usi.inf.sa4.sanmarinoes.smarthut.config.GsonExclude;
import ch.usi.inf.sa4.sanmarinoes.smarthut.config.SocketGsonExclude;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.*; import javax.persistence.*;
/** A device that can be turned either on or off */ /** A device that can be turned either on or off */
@Entity @Entity
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS) @Inheritance(strategy = InheritanceType.JOINED)
public abstract class Switchable extends OutputDevice { public abstract class Switchable extends OutputDevice {
public static final Connector<Switch, Switchable> SWITCH_SWITCHABLE_CONNECTOR = public static final Connector<Switch, Switchable> SWITCH_SWITCHABLE_CONNECTOR =
Connector.basic(Switch::getOutputs, Switchable::setSwitchId); Connector.basic(Switch::getOutputs, Switchable::getSwitches);
@ManyToOne @ManyToMany(mappedBy = "switchables", cascade = CascadeType.DETACH)
@GsonExclude @GsonExclude
@JoinColumn(name = "switch_id", updatable = false, insertable = false) @SocketGsonExclude
private Switch switchDevice; private Set<Switch> inputs = new HashSet<>();
@Column(name = "switch_id")
private Long switchId;
protected Switchable(String kind) { protected Switchable(String kind) {
super(kind); super(kind);
@ -37,11 +37,20 @@ public abstract class Switchable extends OutputDevice {
*/ */
public abstract void setOn(boolean on); public abstract void setOn(boolean on);
public Long getSwitchId() { public Set<Switch> getSwitches() {
return switchId; return inputs;
} }
public void setSwitchId(Long switchId) { public void readStateAndSet(SwitchableState<? extends Switchable> state) {
this.switchId = switchId; setOn(state.isOn());
}
@Override
public State<? extends Switchable> cloneState() {
final SwitchableState<Switchable> newState = new SwitchableState<>();
newState.setDeviceId(getId());
newState.setDevice(this);
newState.setOn(isOn());
return newState;
} }
} }

View file

@ -0,0 +1,25 @@
package ch.usi.inf.sa4.sanmarinoes.smarthut.models;
import javax.persistence.Column;
import javax.persistence.Entity;
/** Represents a state for a Switchable device */
@Entity
public class SwitchableState<T extends Switchable> extends State<T> {
@Column(name = "switchable_on")
private boolean on;
public boolean isOn() {
return on;
}
public void setOn(boolean on) {
this.on = on;
}
@Override
public void apply() {
getDevice().readStateAndSet(this);
}
}

View file

@ -0,0 +1,3 @@
package ch.usi.inf.sa4.sanmarinoes.smarthut.models;
public interface SwitchableStateRepository extends StateRepository<SwitchableState<?>> {}

View file

@ -0,0 +1,129 @@
package ch.usi.inf.sa4.sanmarinoes.smarthut.models;
import com.google.gson.annotations.SerializedName;
import java.math.BigDecimal;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Transient;
import javax.validation.constraints.NotNull;
/** A thermostat capable of controlling cooling and heating. */
@Entity
public class Thermostat extends Switchable implements BooleanTriggerable {
@Override
public boolean isOn() {
return mode != Mode.OFF;
}
@Override
public void setOn(boolean on) {
mode = on ? Mode.IDLE : Mode.OFF;
computeState();
}
/**
* Computes the new thermostat state, for when the thermostat is on;
*
* @return true if the state changed, false if not;
*/
public boolean computeState() {
if (mode == Thermostat.Mode.OFF) {
return false;
}
BigDecimal measured = this.getMeasuredTemperature();
BigDecimal target = this.getTargetTemperature();
BigDecimal delta = target.subtract(measured);
if (delta.abs().doubleValue() < 0.25) {
if (this.getMode() == Thermostat.Mode.IDLE) return false;
this.setMode(Thermostat.Mode.IDLE);
} else if (delta.signum() > 0) {
if (this.getMode() == Thermostat.Mode.HEATING) return false;
this.setMode(Thermostat.Mode.HEATING);
} else {
if (this.getMode() == Thermostat.Mode.COOLING) return false;
this.setMode(Thermostat.Mode.COOLING);
}
return true;
}
@Override
public boolean readTriggerState() {
return mode != Mode.OFF;
}
public enum Mode {
@SerializedName("OFF")
OFF,
@SerializedName("IDLE")
IDLE,
@SerializedName("COOLING")
COOLING,
@SerializedName("HEATING")
HEATING
}
/** Temperature to be reached */
@Column @NotNull private BigDecimal targetTemperature;
/** The temperature detected by the embedded sensor */
@Column(nullable = false, precision = 4, scale = 1)
private BigDecimal internalSensorTemperature =
Sensor.TYPICAL_VALUES.get(Sensor.SensorType.TEMPERATURE);
/** State of this thermostat */
@Column @NotNull private Thermostat.Mode mode;
@Transient private BigDecimal measuredTemperature;
@Column private boolean useExternalSensors = false;
/** Creates a thermostat with a temperature sensor and its initial OFF state */
public Thermostat() {
super("thermostat");
this.mode = Mode.OFF;
}
public void setMode(Mode state) {
this.mode = state;
}
public Mode getMode() {
return this.mode;
}
public BigDecimal getTargetTemperature() {
return this.targetTemperature;
}
public BigDecimal getInternalSensorTemperature() {
return internalSensorTemperature;
}
public boolean isUseExternalSensors() {
return useExternalSensors;
}
public BigDecimal getMeasuredTemperature() {
return measuredTemperature;
}
public void setMeasuredTemperature(BigDecimal measuredTemperature) {
this.measuredTemperature = measuredTemperature;
}
public void setTargetTemperature(BigDecimal targetTemperature) {
this.targetTemperature = targetTemperature;
}
public void setInternalSensorTemperature(BigDecimal internalSensorTemperature) {
this.internalSensorTemperature = internalSensorTemperature;
}
public void setUseExternalSensors(boolean useExternalSensors) {
this.useExternalSensors = useExternalSensors;
}
}

View file

@ -0,0 +1,30 @@
package ch.usi.inf.sa4.sanmarinoes.smarthut.models;
import java.math.BigDecimal;
import java.util.List;
import java.util.Optional;
import javax.transaction.Transactional;
import org.springframework.data.jpa.repository.Query;
public interface ThermostatRepository extends DeviceRepository<Thermostat> {
/**
* Finds all devices belonging to a user
*
* @param username the User's username
* @return all devices of that user
*/
@Transactional
@Query("SELECT t FROM Thermostat t JOIN t.room r JOIN r.user u WHERE u.username = ?1")
List<Thermostat> findAllByUsername(String username);
/**
* Computes the average temperature of all temperature sensors in the room
*
* @param thermostatRoomId room ID of the thermostat
* @return an optional big decimal, empty if none found
*/
@Query(
"SELECT AVG(s.value) FROM Sensor s JOIN s.room r WHERE s.sensor = 'TEMPERATURE' AND r.id = ?1")
Optional<BigDecimal> getAverageTemperature(Long thermostatRoomId);
}

View file

@ -0,0 +1,101 @@
package ch.usi.inf.sa4.sanmarinoes.smarthut.models;
import ch.usi.inf.sa4.sanmarinoes.smarthut.config.GsonExclude;
import io.swagger.annotations.ApiModelProperty;
import javax.persistence.*;
import javax.validation.constraints.NotNull;
@Entity
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public abstract class Trigger<D extends Device> {
@Transient private String kind;
protected Trigger(String kind) {
this.kind = kind;
}
public String getKind() {
return kind;
}
public abstract boolean triggered();
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id", updatable = false, nullable = false, unique = true)
@ApiModelProperty(hidden = true)
private long id;
@ManyToOne(targetEntity = Device.class)
@JoinColumn(name = "device_id", updatable = false, insertable = false)
@GsonExclude
private D device;
/**
* The device this trigger belongs to, as a foreign key id. To use when updating and inserting
* from a REST call.
*/
@Column(name = "device_id", nullable = false)
@NotNull
private Long deviceId;
@ManyToOne
@JoinColumn(name = "automation_id", updatable = false, insertable = false)
@GsonExclude
private Automation automation;
@Column(name = "automation_id", nullable = false)
@NotNull
private Long automationId;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public D getDevice() {
return device;
}
public void setDevice(D device) {
this.device = device;
}
public Long getDeviceId() {
return deviceId;
}
public void setDeviceId(Long deviceId) {
this.deviceId = deviceId;
}
public Automation getAutomation() {
return automation;
}
public void setAutomation(Automation automation) {
this.automation = automation;
}
public Long getAutomationId() {
return automationId;
}
public Trigger<D> setAutomationId(Long automationId) {
this.automationId = automationId;
return this;
}
@PreRemove
public void removeDeviceAndScene() {
this.setDevice(null);
this.setDeviceId(null);
this.setAutomation(null);
this.setAutomationId(null);
}
}

View file

@ -0,0 +1,14 @@
package ch.usi.inf.sa4.sanmarinoes.smarthut.models;
import java.util.List;
import javax.transaction.Transactional;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;
public interface TriggerRepository<T extends Trigger<?>> extends CrudRepository<T, Long> {
List<T> findAllByDeviceId(@Param("deviceId") long deviceId);
@Transactional
void deleteAllByAutomationId(Long automationId);
}

View file

@ -2,7 +2,9 @@ package ch.usi.inf.sa4.sanmarinoes.smarthut.models;
import ch.usi.inf.sa4.sanmarinoes.smarthut.config.GsonExclude; import ch.usi.inf.sa4.sanmarinoes.smarthut.config.GsonExclude;
import io.swagger.annotations.ApiModelProperty; import io.swagger.annotations.ApiModelProperty;
import java.util.HashSet;
import java.util.Objects; import java.util.Objects;
import java.util.Set;
import javax.persistence.*; import javax.persistence.*;
/** A user of the Smarthut application */ /** A user of the Smarthut application */
@ -35,6 +37,23 @@ public class User {
@Column(nullable = false, unique = true) @Column(nullable = false, unique = true)
private String email; private String email;
/** Guests invited by this user */
@ManyToMany(mappedBy = "hosts", cascade = CascadeType.DETACH)
@GsonExclude
private Set<User> guests = new HashSet<>();
@ManyToMany(cascade = CascadeType.DETACH)
@JoinTable(
name = "invited",
joinColumns = @JoinColumn(name = "guest_id"),
inverseJoinColumns = @JoinColumn(name = "host_id"))
@GsonExclude
private Set<User> hosts = new HashSet<>();
/** Determines whether a guest can access security cameras */
@Column(nullable = false)
private boolean cameraEnabled;
@Column(nullable = false) @Column(nullable = false)
@GsonExclude @GsonExclude
private Boolean isEnabled = false; private Boolean isEnabled = false;
@ -87,10 +106,37 @@ public class User {
isEnabled = enabled; isEnabled = enabled;
} }
public Set<User> getGuests() {
return guests;
}
public Set<User> getHosts() {
return hosts;
}
public boolean isCameraEnabled() {
return cameraEnabled;
}
public void addGuest(User guest) {
this.guests.add(guest);
}
public void addHost(User host) {
this.hosts.add(host);
}
public void removeGuest(User guest) {
this.guests.remove(guest);
}
public void setCameraEnabled(boolean cameraEnabled) {
this.cameraEnabled = cameraEnabled;
}
@Override @Override
public String toString() { public String toString() {
return "User{" return "User{id="
+ "id="
+ id + id
+ ", name='" + ", name='"
+ name + name
@ -104,6 +150,8 @@ public class User {
+ ", email='" + ", email='"
+ email + email
+ '\'' + '\''
+ ", cameraEnabled="
+ cameraEnabled
+ ", isEnabled=" + ", isEnabled="
+ isEnabled + isEnabled
+ '}'; + '}';

View file

@ -6,5 +6,7 @@ import org.springframework.data.repository.CrudRepository;
public interface UserRepository extends CrudRepository<User, Long> { public interface UserRepository extends CrudRepository<User, Long> {
User findByUsername(String username); User findByUsername(String username);
Optional<User> findById(Long userId);
User findByEmailIgnoreCase(String email); User findByEmailIgnoreCase(String email);
} }

View file

@ -1,10 +1,10 @@
package ch.usi.inf.sa4.sanmarinoes.smarthut.scheduled; 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.*; import ch.usi.inf.sa4.sanmarinoes.smarthut.models.*;
import ch.usi.inf.sa4.sanmarinoes.smarthut.service.MotionSensorService;
import ch.usi.inf.sa4.sanmarinoes.smarthut.service.SensorService;
import ch.usi.inf.sa4.sanmarinoes.smarthut.service.ThermostatService;
import ch.usi.inf.sa4.sanmarinoes.smarthut.socket.SensorSocketEndpoint; import ch.usi.inf.sa4.sanmarinoes.smarthut.socket.SensorSocketEndpoint;
import java.math.BigDecimal;
import java.util.Collection; import java.util.Collection;
import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
@ -26,25 +26,24 @@ public class UpdateTasks {
@Autowired private SmartPlugRepository smartPlugRepository; @Autowired private SmartPlugRepository smartPlugRepository;
@Autowired private SensorController sensorController; @Autowired private SensorService sensorService;
@Autowired private MotionSensorController motionSensorController; @Autowired private ThermostatService thermostatService;
@Autowired private MotionSensorService motionSensorService;
@Autowired private SensorSocketEndpoint sensorSocketEndpoint; @Autowired private SensorSocketEndpoint sensorSocketEndpoint;
/** Generates fake sensor updates every two seconds with a +/- 1.25% error */ /** Generates fake sensor updates every two seconds with a +/- 2.5% error */
@Scheduled(fixedRate = 2000) @Scheduled(fixedRate = 2000)
public void sensorFakeUpdate() { public void sensorFakeUpdate() {
StreamSupport.stream(sensorRepository.findAll().spliterator(), true) sensorService.sensorFakeUpdate();
.forEach( }
sensor ->
sensorController.updateValueFromSensor( /** Generates fake sensor updates every two seconds with a +/- 2.5% error */
sensor, @Scheduled(fixedRate = 2000)
Sensor.TYPICAL_VALUES public void thermostatInteralSensorFakeUpdate() {
.get(sensor.getSensor()) thermostatService.fakeUpdateAll();
.multiply(
new BigDecimal(
0.9875 + Math.random() / 40))));
} }
/** /**
@ -56,14 +55,18 @@ public class UpdateTasks {
StreamSupport.stream(motionSensorRepository.findAll().spliterator(), true) StreamSupport.stream(motionSensorRepository.findAll().spliterator(), true)
.forEach( .forEach(
sensor -> { sensor -> {
motionSensorController.updateDetectionFromMotionSensor(sensor, true); final User owner = motionSensorRepository.findUser(sensor.getId());
motionSensorService.updateDetectionFromMotionSensor(
sensor, true, owner.getUsername());
CompletableFuture.delayedExecutor( CompletableFuture.delayedExecutor(
(long) (Math.random() * 2000), TimeUnit.MILLISECONDS) (long) (Math.random() * 2000), TimeUnit.MILLISECONDS)
.execute( .execute(
() -> () ->
motionSensorController motionSensorService
.updateDetectionFromMotionSensor( .updateDetectionFromMotionSensor(
sensor, false)); sensor,
false,
owner.getUsername()));
}); });
} }
@ -72,6 +75,15 @@ public class UpdateTasks {
public void smartPlugConsumptionFakeUpdate() { public void smartPlugConsumptionFakeUpdate() {
smartPlugRepository.updateTotalConsumption(SmartPlug.AVERAGE_CONSUMPTION_KW); smartPlugRepository.updateTotalConsumption(SmartPlug.AVERAGE_CONSUMPTION_KW);
final Collection<SmartPlug> c = smartPlugRepository.findByOn(true); final Collection<SmartPlug> c = smartPlugRepository.findByOn(true);
c.forEach(s -> sensorSocketEndpoint.broadcast(s, sensorRepository.findUser(s.getId()))); c.forEach(
s ->
sensorSocketEndpoint.queueDeviceUpdate(
s, sensorRepository.findUser(s.getId())));
}
/** Sends device updates through sensor socket in batch every one second */
@Scheduled(fixedDelay = 1000)
public void socketFlush() {
sensorSocketEndpoint.flushDeviceUpdates();
} }
} }

View file

@ -0,0 +1,194 @@
package ch.usi.inf.sa4.sanmarinoes.smarthut.service;
import static ch.usi.inf.sa4.sanmarinoes.smarthut.utils.Utils.toList;
import ch.usi.inf.sa4.sanmarinoes.smarthut.error.NotFoundException;
import ch.usi.inf.sa4.sanmarinoes.smarthut.models.*;
import ch.usi.inf.sa4.sanmarinoes.smarthut.socket.SensorSocketEndpoint;
import java.util.Collection;
import java.util.Comparator;
import java.util.List;
import java.util.Set;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class DeviceService {
@Autowired private DeviceRepository<Device> deviceRepository;
@Autowired private AutomationRepository automationRepository;
@Autowired private SceneRepository sceneRepository;
@Autowired private SceneService sceneService;
@Autowired private TriggerRepository<Trigger<? extends Device>> triggerRepository;
@Autowired private RoomRepository roomRepository;
@Autowired private EagerUserRepository userRepository;
@Autowired private SensorSocketEndpoint endpoint;
@Autowired private ThermostatService thermostatService;
public void throwIfRoomNotOwned(Long roomId, String username) throws NotFoundException {
roomRepository.findByIdAndUsername(roomId, username).orElseThrow(NotFoundException::new);
}
private void renameIfDuplicate(Device toCreate, String username) {
while (deviceRepository.findDuplicates(toCreate.getName(), username)
- (toCreate.getId() <= 0 ? 0 : 1)
> 0) {
toCreate.setName(toCreate.getName() + " (new)");
}
}
private void triggerTriggers(Device device) {
final long deviceId = device.getId();
List<Trigger<? extends Device>> triggers = triggerRepository.findAllByDeviceId(deviceId);
triggers.stream()
.filter(Trigger::triggered)
.map(Trigger::getAutomationId)
.map(t -> automationRepository.findById(t).orElseThrow(IllegalStateException::new))
.distinct()
.map(Automation::getScenes)
.flatMap(Collection::stream)
.distinct()
.sorted(Comparator.comparing(ScenePriority::getPriority))
.map(
t ->
sceneRepository
.findById(t.getSceneId())
.orElseThrow(IllegalStateException::new))
.forEach(sceneService::apply);
}
public List<Device> findAll(Long hostId, String username) throws NotFoundException {
return findAll(null, hostId, username);
}
public List<Device> findAll(Long roomId, Long hostId, String username)
throws NotFoundException {
try {
Iterable<Device> devices;
if (hostId == null) {
if (roomId != null) {
roomRepository
.findByIdAndUsername(roomId, username)
.orElseThrow(NotFoundException::new);
devices = deviceRepository.findByRoomId(roomId);
} else {
devices = deviceRepository.findAllByUsername(username);
}
} else {
final User guest = userRepository.findByUsername(username);
final User host =
userRepository.findById(hostId).orElseThrow(NotFoundException::new);
if (!guest.getHosts().contains(host)) {
throw new NotFoundException();
}
if (roomId != null) {
Room r = roomRepository.findById(roomId).orElseThrow(NotFoundException::new);
if (!r.getUserId().equals(hostId)) {
throw new NotFoundException();
}
devices = deviceRepository.findByRoomId(roomId);
} else {
devices = deviceRepository.findAllByUsername(host.getUsername());
}
}
for (Device d : devices) {
if (d instanceof Thermostat) {
thermostatService.populateMeasuredTemperature((Thermostat) d);
}
}
return toList(devices);
} catch (NotFoundException e) {
e.printStackTrace();
throw e;
}
}
public <T extends Device> T saveAsGuest(T device, String guestUsername, Long hostId)
throws NotFoundException {
final User currentUser = userRepository.findByUsername(guestUsername);
final User host = userRepository.findById(hostId).orElseThrow(NotFoundException::new);
if (!host.getGuests().contains(currentUser)) throw new NotFoundException();
renameIfDuplicate(device, host.getUsername());
device = deviceRepository.save(device);
final Set<User> guests = Set.copyOf(host.getGuests());
// We're telling the host that a guest has modified a device. Therefore, fromGuest becomes
// true.
device.setFromHost(false);
device.setFromGuest(true);
// broadcast device update to host
endpoint.queueDeviceUpdate(device, host);
// We're telling all guests that a higher entity has issued a device update. Therefore,
// fromHost becomes true.
device.setFromHost(true);
device.setFromGuest(false);
for (final User guest : guests) {
if (guest.equals(currentUser)) {
continue;
}
// enqueue all device updates for all other guests
endpoint.queueDeviceUpdate(device, guest);
}
return device;
}
private void propagateUpdateAsOwner(Device device, String username) {
final User user = userRepository.findByUsername(username);
final Set<User> guests = user.getGuests();
// make sure we're broadcasting from host
device.setFromHost(true);
device.setFromGuest(false);
for (final User guest : guests) {
// broadcast to endpoint the object device, with receiving user set to guest
endpoint.queueDeviceUpdate(device, guest);
}
}
public <T extends Device> List<T> saveAllAsOwner(
Iterable<T> devices, String username, boolean fromScene) {
devices.forEach(d -> renameIfDuplicate(d, username));
devices = deviceRepository.saveAll(devices);
devices.forEach((d) -> propagateUpdateAsOwner(d, username));
if (!fromScene) {
devices.forEach(this::triggerTriggers);
}
return toList(devices);
}
public <T extends Device> T saveAsOwner(T device, String username, boolean fromScene) {
renameIfDuplicate(device, username);
device = deviceRepository.save(device);
propagateUpdateAsOwner(device, username);
if (!fromScene) {
triggerTriggers(device);
}
return device;
}
public <T extends Device> T saveAsOwner(T device, String username) {
return saveAsOwner(device, username, false);
}
public void delete(Long id, String username) throws NotFoundException {
Device device =
deviceRepository
.findByIdAndUsername(id, username)
.orElseThrow(NotFoundException::new);
deviceRepository.delete(device);
propagateUpdateAsOwner(device, username);
}
}

View file

@ -1,6 +1,9 @@
package ch.usi.inf.sa4.sanmarinoes.smarthut.models; package ch.usi.inf.sa4.sanmarinoes.smarthut.service;
import java.util.Set; import java.util.Set;
import ch.usi.inf.sa4.sanmarinoes.smarthut.models.User;
import ch.usi.inf.sa4.sanmarinoes.smarthut.models.UserRepository;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.*; import org.springframework.security.core.*;
import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetails;

Some files were not shown because too many files have changed in this diff Show more