Search in sources :

Example 1 with Rule

use of org.openhab.core.automation.Rule 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 2 with Rule

use of org.openhab.core.automation.Rule 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 3 with Rule

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

the class Schedules method activate.

/**
 * Registers to the {@link RuleRegistry} and enumerates currently existing rules.
 */
@Activate
public void activate() {
    ruleRegistry.removeRegistryChangeListener(this);
    ruleRegistry.addRegistryChangeListener(this);
    for (Rule item : ruleRegistry.getAll()) {
        added(item);
    }
}
Also used : Rule(org.openhab.core.automation.Rule) Activate(org.osgi.service.component.annotations.Activate)

Example 4 with Rule

use of org.openhab.core.automation.Rule 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 Rule

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

the class Schedules method added.

/**
 * Called by the registry when a rule got added (and when a rule got modified).
 * <p>
 * Converts the rule into a {@link HueScheduleEntry} object and add that to the hue datastore.
 */
@Override
public void added(Rule rule) {
    if (!rule.getTags().contains(SCHEDULE_TAG)) {
        return;
    }
    HueScheduleEntry entry = new HueScheduleEntry();
    entry.name = rule.getName();
    entry.description = rule.getDescription();
    entry.autodelete = rule.getActions().stream().anyMatch(p -> p.getId().equals("autodelete"));
    entry.status = ruleManager.isEnabled(rule.getUID()) ? "enabled" : "disabled";
    String timeStringFromTrigger = RuleUtils.timeStringFromTrigger(rule.getTriggers());
    if (timeStringFromTrigger == null) {
        logger.warn("Schedule from rule '{}' invalid!", rule.getName());
        return;
    }
    entry.localtime = timeStringFromTrigger;
    for (Action a : rule.getActions()) {
        if (!a.getTypeUID().equals("rules.HttpAction")) {
            continue;
        }
        HueCommand command = RuleUtils.httpActionToHueCommand(cs.ds, a, rule.getName());
        if (command == null) {
            continue;
        }
        entry.command = command;
    }
    cs.ds.schedules.put(rule.getUID(), entry);
}
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) RuleManager(org.openhab.core.automation.RuleManager) RuleBuilder(org.openhab.core.automation.util.RuleBuilder) RegistryChangeListener(org.openhab.core.common.registry.RegistryChangeListener) LoggerFactory(org.slf4j.LoggerFactory) HueDataStore(org.openhab.io.hueemulation.internal.dto.HueDataStore) ConfigStore(org.openhab.io.hueemulation.internal.ConfigStore) Trigger(org.openhab.core.automation.Trigger) MediaType(javax.ws.rs.core.MediaType) Consumes(javax.ws.rs.Consumes) Configuration(org.openhab.core.config.core.Configuration) 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) HueScheduleEntry(org.openhab.io.hueemulation.internal.dto.HueScheduleEntry) 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) JaxrsApplicationSelect(org.osgi.service.jaxrs.whiteboard.propertytypes.JaxrsApplicationSelect) UriInfo(javax.ws.rs.core.UriInfo) HueCommand(org.openhab.io.hueemulation.internal.dto.changerequest.HueCommand) PathParam(javax.ws.rs.PathParam) GET(javax.ws.rs.GET) RuleRegistry(org.openhab.core.automation.RuleRegistry) 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) Visibility(org.openhab.core.automation.Visibility) POST(javax.ws.rs.POST) Logger(org.slf4j.Logger) HueChangeScheduleEntry(org.openhab.io.hueemulation.internal.dto.changerequest.HueChangeScheduleEntry) Rule(org.openhab.core.automation.Rule) PUT(javax.ws.rs.PUT) RuleUtils(org.openhab.io.hueemulation.internal.RuleUtils) Reference(org.osgi.service.component.annotations.Reference) Collections(java.util.Collections) HueCommand(org.openhab.io.hueemulation.internal.dto.changerequest.HueCommand) Action(org.openhab.core.automation.Action) HueScheduleEntry(org.openhab.io.hueemulation.internal.dto.HueScheduleEntry)

Aggregations

Rule (org.openhab.core.automation.Rule)76 Test (org.junit.jupiter.api.Test)47 JavaOSGiTest (org.openhab.core.test.java.JavaOSGiTest)36 Configuration (org.openhab.core.config.core.Configuration)27 Trigger (org.openhab.core.automation.Trigger)23 Action (org.openhab.core.automation.Action)21 Event (org.openhab.core.events.Event)19 ItemCommandEvent (org.openhab.core.items.events.ItemCommandEvent)19 EventSubscriber (org.openhab.core.events.EventSubscriber)16 RuleStatusInfoEvent (org.openhab.core.automation.events.RuleStatusInfoEvent)15 RuleRegistry (org.openhab.core.automation.RuleRegistry)14 HashMap (java.util.HashMap)13 Random (java.util.Random)13 EventPublisher (org.openhab.core.events.EventPublisher)13 ArrayList (java.util.ArrayList)12 Response (javax.ws.rs.core.Response)12 Operation (io.swagger.v3.oas.annotations.Operation)10 Path (javax.ws.rs.Path)10 RuleManager (org.openhab.core.automation.RuleManager)10 RuleAddedEvent (org.openhab.core.automation.events.RuleAddedEvent)10