Search in sources :

Example 1 with RuleBuilder

use of org.openhab.core.automation.util.RuleBuilder in project openhab-addons by openhab.

the class Rules method postNewRule.

@SuppressWarnings({ "null" })
@POST
@Path("{username}/rules")
@Operation(summary = "Create a new rule", responses = { @ApiResponse(responseCode = "200", description = "OK") })
public Response postNewRule(@Context UriInfo uri, @PathParam("username") @Parameter(description = "username") String username, String body) {
    if (!userManagement.authorizeUser(username)) {
        return NetworkUtils.singleError(cs.gson, uri, HueResponse.UNAUTHORIZED, "Not Authorized");
    }
    HueRuleEntry newRuleData = cs.gson.fromJson(body, HueRuleEntry.class);
    if (newRuleData == null || newRuleData.name.isEmpty() || newRuleData.actions.isEmpty() || newRuleData.conditions.isEmpty()) {
        return NetworkUtils.singleError(cs.gson, uri, HueResponse.INVALID_JSON, "Invalid request: No name or actions or conditons!");
    }
    String uid = UUID.randomUUID().toString();
    RuleBuilder builder = RuleBuilder.create(uid).withName(newRuleData.name);
    String description = newRuleData.description;
    if (description != null) {
        builder.withDescription(description);
    }
    try {
        builder.withActions(createActions(uid, newRuleData.actions, Collections.emptyList(), username));
        builder = createHueRuleConditions(newRuleData.conditions, builder, Collections.emptyList(), Collections.emptyList(), itemRegistry);
        ruleRegistry.add(builder.withTags(RULES_TAG).build());
    } catch (IllegalStateException e) {
        return NetworkUtils.singleError(cs.gson, uri, HueResponse.ARGUMENTS_INVALID, e.getMessage());
    }
    return NetworkUtils.singleSuccess(cs.gson, uid, "id");
}
Also used : HueRuleEntry(org.openhab.io.hueemulation.internal.dto.HueRuleEntry) RuleBuilder(org.openhab.core.automation.util.RuleBuilder) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST) Operation(io.swagger.v3.oas.annotations.Operation)

Example 2 with RuleBuilder

use of org.openhab.core.automation.util.RuleBuilder in project openhab-addons by openhab.

the class Scenes method modifySceneLightStateApi.

@PUT
@Path("{username}/scenes/{id}/lightstates/{lightid}")
@Operation(summary = "Set scene attributes", responses = { @ApiResponse(responseCode = "200", description = "OK") })
public // 
Response modifySceneLightStateApi(// 
@Context UriInfo uri, @PathParam("username") @Parameter(description = "username") String username, @PathParam("id") @Parameter(description = "scene id") String id, @PathParam("lightid") @Parameter(description = "light id") String lightid, String body) {
    if (!userManagement.authorizeUser(username)) {
        return NetworkUtils.singleError(cs.gson, uri, HueResponse.UNAUTHORIZED, "Not Authorized");
    }
    final HueStateChange changeRequest = Objects.requireNonNull(cs.gson.fromJson(body, HueStateChange.class));
    Rule rule = ruleRegistry.remove(id);
    if (rule == null) {
        return NetworkUtils.singleError(cs.gson, uri, HueResponse.NOT_AVAILABLE, "Scene does not exist!");
    }
    RuleBuilder builder = RuleBuilder.create(rule);
    List<Action> actions = new ArrayList<>(rule.getActions());
    // Remove existing action
    actions.removeIf(action -> action.getId().equals(lightid));
    // Assign new action
    Command command = StateUtils.computeCommandByChangeRequest(changeRequest);
    if (command == null) {
        logger.warn("Failed to compute command for {}", body);
        return NetworkUtils.singleError(cs.gson, uri, HueResponse.NOT_AVAILABLE, "Cannot compute command!");
    }
    actions.add(actionFromState(lightid, command));
    builder.withActions(actions);
    try {
        ruleRegistry.add(builder.build());
    } catch (IllegalStateException e) {
        return NetworkUtils.singleError(cs.gson, uri, HueResponse.ARGUMENTS_INVALID, e.getMessage());
    }
    return NetworkUtils.successList(cs.gson, // 
    Arrays.asList(// 
    new HueSuccessGeneric(changeRequest.on, "/scenes/" + id + "/lightstates/" + lightid + "/on"), // 
    new HueSuccessGeneric(changeRequest.hue, "/scenes/" + id + "/lightstates/" + lightid + "/hue"), // 
    new HueSuccessGeneric(changeRequest.sat, "/scenes/" + id + "/lightstates/" + lightid + "/sat"), // 
    new HueSuccessGeneric(changeRequest.bri, "/scenes/" + id + "/lightstates/" + lightid + "/bri"), new HueSuccessGeneric(changeRequest.transitiontime, "/scenes/" + id + "/lightstates/" + lightid + "/transitiontime")));
}
Also used : Action(org.openhab.core.automation.Action) HueStateChange(org.openhab.io.hueemulation.internal.dto.changerequest.HueStateChange) Command(org.openhab.core.types.Command) ArrayList(java.util.ArrayList) Rule(org.openhab.core.automation.Rule) RuleBuilder(org.openhab.core.automation.util.RuleBuilder) HueSuccessGeneric(org.openhab.io.hueemulation.internal.dto.response.HueSuccessGeneric) Path(javax.ws.rs.Path) Operation(io.swagger.v3.oas.annotations.Operation) PUT(javax.ws.rs.PUT)

Example 3 with RuleBuilder

use of org.openhab.core.automation.util.RuleBuilder in project openhab-addons by openhab.

the class Schedules method postNewSchedule.

@SuppressWarnings({ "null" })
@POST
@Path("{username}/schedules")
@Operation(summary = "Create a new schedule", responses = { @ApiResponse(responseCode = "200", description = "OK") })
public Response postNewSchedule(@Context UriInfo uri, @PathParam("username") @Parameter(description = "username") String username, String body) {
    if (!userManagement.authorizeUser(username)) {
        return NetworkUtils.singleError(cs.gson, uri, HueResponse.UNAUTHORIZED, "Not Authorized");
    }
    HueScheduleEntry newScheduleData = cs.gson.fromJson(body, HueScheduleEntry.class);
    if (newScheduleData == null || newScheduleData.name.isEmpty() || newScheduleData.localtime.isEmpty()) {
        return NetworkUtils.singleError(cs.gson, uri, HueResponse.INVALID_JSON, "Invalid request: No name or localtime!");
    }
    String uid = UUID.randomUUID().toString();
    RuleBuilder builder = RuleBuilder.create(uid);
    Rule rule;
    try {
        rule = createRule(uid, builder, Collections.emptyList(), Collections.emptyList(), newScheduleData, cs.ds);
    } catch (IllegalStateException e) {
        // No stacktrace required, we just need the exception message
        return NetworkUtils.singleError(cs.gson, uri, HueResponse.ARGUMENTS_INVALID, e.getMessage());
    }
    ruleRegistry.add(rule);
    return NetworkUtils.singleSuccess(cs.gson, uid, "id");
}
Also used : RuleBuilder(org.openhab.core.automation.util.RuleBuilder) Rule(org.openhab.core.automation.Rule) HueScheduleEntry(org.openhab.io.hueemulation.internal.dto.HueScheduleEntry) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST) Operation(io.swagger.v3.oas.annotations.Operation)

Example 4 with RuleBuilder

use of org.openhab.core.automation.util.RuleBuilder in project openhab-addons by openhab.

the class Schedules method modifyScheduleApi.

@PUT
@Path("{username}/schedules/{id}")
@Operation(summary = "Set schedule attributes", responses = { @ApiResponse(responseCode = "200", description = "OK") })
public // 
Response modifyScheduleApi(// 
@Context UriInfo uri, @PathParam("username") @Parameter(description = "username") String username, @PathParam("id") @Parameter(description = "schedule id") String id, String body) {
    if (!userManagement.authorizeUser(username)) {
        return NetworkUtils.singleError(cs.gson, uri, HueResponse.UNAUTHORIZED, "Not Authorized");
    }
    final HueChangeScheduleEntry changeRequest = Objects.requireNonNull(cs.gson.fromJson(body, HueChangeScheduleEntry.class));
    Rule rule = ruleRegistry.remove(id);
    if (rule == null) {
        return NetworkUtils.singleError(cs.gson, uri, HueResponse.NOT_AVAILABLE, "Schedule does not exist!");
    }
    RuleBuilder builder = RuleBuilder.create(rule);
    try {
        ruleRegistry.add(createRule(rule.getUID(), builder, rule.getActions(), rule.getTriggers(), changeRequest, cs.ds));
    } catch (IllegalStateException e) {
        return NetworkUtils.singleError(cs.gson, uri, HueResponse.ARGUMENTS_INVALID, e.getMessage());
    }
    return NetworkUtils.successList(cs.gson, // 
    Arrays.asList(// 
    new HueSuccessGeneric(changeRequest.name, "/schedules/" + id + "/name"), // 
    new HueSuccessGeneric(changeRequest.description, "/schedules/" + id + "/description"), // 
    new HueSuccessGeneric(changeRequest.localtime, "/schedules/" + id + "/localtime"), // 
    new HueSuccessGeneric(changeRequest.status, "/schedules/" + id + "/status"), // 
    new HueSuccessGeneric(changeRequest.autodelete, "/schedules/1/autodelete"), // 
    new HueSuccessGeneric(changeRequest.command, "/schedules/1/command")));
}
Also used : Rule(org.openhab.core.automation.Rule) RuleBuilder(org.openhab.core.automation.util.RuleBuilder) HueSuccessGeneric(org.openhab.io.hueemulation.internal.dto.response.HueSuccessGeneric) HueChangeScheduleEntry(org.openhab.io.hueemulation.internal.dto.changerequest.HueChangeScheduleEntry) Path(javax.ws.rs.Path) Operation(io.swagger.v3.oas.annotations.Operation) PUT(javax.ws.rs.PUT)

Example 5 with RuleBuilder

use of org.openhab.core.automation.util.RuleBuilder in project openhab-addons by openhab.

the class Scenes method modifySceneApi.

/**
 * Either assigns a new name, description, lights to a scene or directly assign
 * a new light state for an entry to a scene
 */
@PUT
@Path("{username}/scenes/{id}")
@Operation(summary = "Set scene attributes", responses = { @ApiResponse(responseCode = "200", description = "OK") })
public // 
Response modifySceneApi(// 
@Context UriInfo uri, @PathParam("username") @Parameter(description = "username") String username, @PathParam("id") @Parameter(description = "scene id") String id, String body) {
    if (!userManagement.authorizeUser(username)) {
        return NetworkUtils.singleError(cs.gson, uri, HueResponse.UNAUTHORIZED, "Not Authorized");
    }
    final HueChangeSceneEntry changeRequest = cs.gson.fromJson(body, HueChangeSceneEntry.class);
    Rule rule = ruleRegistry.remove(id);
    if (rule == null) {
        return NetworkUtils.singleError(cs.gson, uri, HueResponse.NOT_AVAILABLE, "Scene does not exist!");
    }
    RuleBuilder builder = RuleBuilder.create(rule);
    String temp = changeRequest.name;
    if (temp != null) {
        builder.withName(temp);
    }
    temp = changeRequest.description;
    if (temp != null) {
        builder.withDescription(temp);
    }
    List<String> lights = changeRequest.lights;
    if (changeRequest.storelightstate && lights != null) {
        @SuppressWarnings("null") @NonNullByDefault({}) List<Action> actions = lights.stream().map(itemID -> itemRegistry.get(itemID)).filter(Objects::nonNull).map(item -> actionFromState(item.getUID(), item.getState())).collect(Collectors.toList());
        builder.withActions(actions);
    }
    Map<String, HueStateChange> lightStates = changeRequest.lightstates;
    if (changeRequest.storelightstate && lightStates != null) {
        List<Action> actions = new ArrayList<>(rule.getActions());
        for (Map.Entry<String, HueStateChange> entry : lightStates.entrySet()) {
            // Remove existing action
            actions.removeIf(action -> action.getId().equals(entry.getKey()));
            // Assign new action
            Command command = StateUtils.computeCommandByChangeRequest(entry.getValue());
            if (command == null) {
                logger.warn("Failed to compute command for {}", body);
                return NetworkUtils.singleError(cs.gson, uri, HueResponse.NOT_AVAILABLE, "Cannot compute command!");
            }
            actions.add(actionFromState(entry.getKey(), command));
        }
        builder.withActions(actions);
    }
    try {
        ruleRegistry.add(builder.build());
    } catch (IllegalStateException e) {
        return NetworkUtils.singleError(cs.gson, uri, HueResponse.ARGUMENTS_INVALID, e.getMessage());
    }
    List<String> lightsList = changeRequest.lights;
    return NetworkUtils.successList(cs.gson, // 
    Arrays.asList(// 
    new HueSuccessGeneric(changeRequest.name, "/scenes/" + id + "/name"), // 
    new HueSuccessGeneric(changeRequest.description, "/scenes/" + id + "/description"), new HueSuccessGeneric(lightsList != null ? String.join(",", lightsList) : null, // 
    "/scenes/" + id + "/lights")));
}
Also used : Arrays(java.util.Arrays) HueResponse(org.openhab.io.hueemulation.internal.dto.response.HueResponse) Produces(javax.ws.rs.Produces) NetworkUtils(org.openhab.io.hueemulation.internal.NetworkUtils) Path(javax.ws.rs.Path) RuleBuilder(org.openhab.core.automation.util.RuleBuilder) RegistryChangeListener(org.openhab.core.common.registry.RegistryChangeListener) LoggerFactory(org.slf4j.LoggerFactory) ConfigStore(org.openhab.io.hueemulation.internal.ConfigStore) MediaType(javax.ws.rs.core.MediaType) Consumes(javax.ws.rs.Consumes) Configuration(org.openhab.core.config.core.Configuration) HueSceneWithLightstates(org.openhab.io.hueemulation.internal.dto.HueSceneWithLightstates) Map(java.util.Map) DELETE(javax.ws.rs.DELETE) HueSuccessGeneric(org.openhab.io.hueemulation.internal.dto.response.HueSuccessGeneric) Context(javax.ws.rs.core.Context) NonNullByDefault(org.eclipse.jdt.annotation.NonNullByDefault) HueEmulationService(org.openhab.io.hueemulation.internal.HueEmulationService) Deactivate(org.osgi.service.component.annotations.Deactivate) Action(org.openhab.core.automation.Action) UUID(java.util.UUID) Collectors(java.util.stream.Collectors) Objects(java.util.Objects) Parameter(io.swagger.v3.oas.annotations.Parameter) List(java.util.List) Response(javax.ws.rs.core.Response) AbstractHueState(org.openhab.io.hueemulation.internal.dto.AbstractHueState) HueSceneEntry(org.openhab.io.hueemulation.internal.dto.HueSceneEntry) JaxrsApplicationSelect(org.osgi.service.jaxrs.whiteboard.propertytypes.JaxrsApplicationSelect) UriInfo(javax.ws.rs.core.UriInfo) PathParam(javax.ws.rs.PathParam) GET(javax.ws.rs.GET) RuleRegistry(org.openhab.core.automation.RuleRegistry) ItemCommandActionConfig(org.openhab.io.hueemulation.internal.automation.dto.ItemCommandActionConfig) HueChangeSceneEntry(org.openhab.io.hueemulation.internal.dto.changerequest.HueChangeSceneEntry) ArrayList(java.util.ArrayList) Component(org.osgi.service.component.annotations.Component) Operation(io.swagger.v3.oas.annotations.Operation) ApiResponse(io.swagger.v3.oas.annotations.responses.ApiResponse) ModuleBuilder(org.openhab.core.automation.util.ModuleBuilder) JaxrsWhiteboardConstants(org.osgi.service.jaxrs.whiteboard.JaxrsWhiteboardConstants) Activate(org.osgi.service.component.annotations.Activate) JaxrsResource(org.osgi.service.jaxrs.whiteboard.propertytypes.JaxrsResource) StateUtils(org.openhab.io.hueemulation.internal.StateUtils) POST(javax.ws.rs.POST) GroupItem(org.openhab.core.items.GroupItem) Command(org.openhab.core.types.Command) Logger(org.slf4j.Logger) State(org.openhab.core.types.State) ItemNotFoundException(org.openhab.core.items.ItemNotFoundException) Rule(org.openhab.core.automation.Rule) Item(org.openhab.core.items.Item) ItemRegistry(org.openhab.core.items.ItemRegistry) PUT(javax.ws.rs.PUT) HueStateChange(org.openhab.io.hueemulation.internal.dto.changerequest.HueStateChange) Reference(org.osgi.service.component.annotations.Reference) Collections(java.util.Collections) NonNullByDefault(org.eclipse.jdt.annotation.NonNullByDefault) Action(org.openhab.core.automation.Action) HueStateChange(org.openhab.io.hueemulation.internal.dto.changerequest.HueStateChange) ArrayList(java.util.ArrayList) HueSuccessGeneric(org.openhab.io.hueemulation.internal.dto.response.HueSuccessGeneric) HueChangeSceneEntry(org.openhab.io.hueemulation.internal.dto.changerequest.HueChangeSceneEntry) Command(org.openhab.core.types.Command) Objects(java.util.Objects) Rule(org.openhab.core.automation.Rule) RuleBuilder(org.openhab.core.automation.util.RuleBuilder) Map(java.util.Map) Path(javax.ws.rs.Path) Operation(io.swagger.v3.oas.annotations.Operation) PUT(javax.ws.rs.PUT)

Aggregations

RuleBuilder (org.openhab.core.automation.util.RuleBuilder)8 Operation (io.swagger.v3.oas.annotations.Operation)7 Path (javax.ws.rs.Path)7 Rule (org.openhab.core.automation.Rule)6 ArrayList (java.util.ArrayList)4 POST (javax.ws.rs.POST)4 PUT (javax.ws.rs.PUT)4 Action (org.openhab.core.automation.Action)4 HueSuccessGeneric (org.openhab.io.hueemulation.internal.dto.response.HueSuccessGeneric)4 Configuration (org.openhab.core.config.core.Configuration)2 GroupItem (org.openhab.core.items.GroupItem)2 Item (org.openhab.core.items.Item)2 HueSceneEntry (org.openhab.io.hueemulation.internal.dto.HueSceneEntry)2 Parameter (io.swagger.v3.oas.annotations.Parameter)1 ApiResponse (io.swagger.v3.oas.annotations.responses.ApiResponse)1 Arrays (java.util.Arrays)1 Collections (java.util.Collections)1 List (java.util.List)1 Map (java.util.Map)1 Objects (java.util.Objects)1