Search in sources :

Example 1 with Action

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

the class Rules method createActions.

protected static List<Action> createActions(String uid, List<HueCommand> hueActions, List<Action> oldActions, String apikey) {
    // Preserve all actions that are not "rules.HttpAction"
    List<Action> actions = new ArrayList<>(oldActions);
    actions.removeIf(a -> a.getTypeUID().equals("rules.HttpAction"));
    for (HueCommand command : hueActions) {
        command.address = "/api/" + apikey + command.address;
        actions.add(RuleUtils.createHttpAction(command, command.address.replace("/", "-")));
    }
    return actions;
}
Also used : HueCommand(org.openhab.io.hueemulation.internal.dto.changerequest.HueCommand) Action(org.openhab.core.automation.Action) ArrayList(java.util.ArrayList)

Example 2 with Action

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

the class Scenes method added.

@Override
public void added(Rule scene) {
    if (!scene.getTags().contains("scene")) {
        return;
    }
    HueSceneEntry entry = new HueSceneEntry(scene.getName());
    String desc = scene.getDescription();
    if (desc != null) {
        entry.description = desc;
    }
    List<String> items = new ArrayList<>();
    for (Action a : scene.getActions()) {
        if (!a.getTypeUID().equals("core.ItemCommandAction")) {
            continue;
        }
        ItemCommandActionConfig config = a.getConfiguration().as(ItemCommandActionConfig.class);
        Item item;
        try {
            item = itemRegistry.getItem(config.itemName);
        } catch (ItemNotFoundException e) {
            logger.warn("Rule {} is referring to a non existing item {}", scene.getName(), config.itemName);
            continue;
        }
        if (scene.getActions().size() == 1 && item instanceof GroupItem) {
            entry.type = HueSceneEntry.TypeEnum.GroupScene;
            entry.group = cs.mapItemUIDtoHueID(item);
        } else {
            items.add(cs.mapItemUIDtoHueID(item));
        }
    }
    if (!items.isEmpty()) {
        entry.lights = items;
    }
    cs.ds.scenes.put(scene.getUID(), entry);
}
Also used : GroupItem(org.openhab.core.items.GroupItem) Item(org.openhab.core.items.Item) Action(org.openhab.core.automation.Action) HueSceneEntry(org.openhab.io.hueemulation.internal.dto.HueSceneEntry) ArrayList(java.util.ArrayList) GroupItem(org.openhab.core.items.GroupItem) ItemCommandActionConfig(org.openhab.io.hueemulation.internal.automation.dto.ItemCommandActionConfig) ItemNotFoundException(org.openhab.core.items.ItemNotFoundException)

Example 3 with Action

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

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

the class Schedules method createRule.

/**
 * Creates a new rule that executes a http rule action, triggered by the scheduled time
 *
 * @param uid A rule unique id.
 * @param builder A rule builder that will be used for creating the rule. It must have been created with the given
 *            uid.
 * @param oldActions Old actions. Useful if `data` is only partially set and old actions should be preserved
 * @param data The configuration for the http action and trigger time is in here
 * @return A new rule with the given uid
 * @throws IllegalStateException If a required parameter is not set or if a light / group that is referred to is not
 *             existing
 */
protected static Rule createRule(String uid, RuleBuilder builder, List<Action> oldActions, List<Trigger> oldTriggers, HueChangeScheduleEntry data, HueDataStore ds) throws IllegalStateException {
    HueCommand command = data.command;
    Boolean autodelete = data.autodelete;
    String temp;
    temp = data.name;
    if (temp != null) {
        builder.withName(temp);
    } else if (oldActions.isEmpty()) {
        // This is a new rule without a name yet
        throw new IllegalStateException("Name not set!");
    }
    temp = data.description;
    if (temp != null) {
        builder.withDescription(temp);
    }
    temp = data.localtime;
    if (temp != null) {
        builder.withTriggers(RuleUtils.createTriggerForTimeString(temp));
    } else if (oldTriggers.isEmpty()) {
        // This is a new rule without triggers yet
        throw new IllegalStateException("localtime not set!");
    }
    List<Action> actions = new ArrayList<>(oldActions);
    if (command != null) {
        RuleUtils.validateHueHttpAddress(ds, command.address);
        // Remove old command action if any and add new one
        actions.removeIf(a -> a.getId().equals("command"));
        actions.add(RuleUtils.createHttpAction(command, "command"));
    } else if (oldActions.isEmpty()) {
        // This is a new rule without an action yet
        throw new IllegalStateException("No command set!");
    }
    if (autodelete != null) {
        // Remove action to remove rule after execution
        actions = actions.stream().filter(e -> !e.getId().equals("autodelete")).collect(Collectors.toCollection(() -> new ArrayList<>()));
        if (autodelete) {
            // Add action to remove this rule again after execution
            final Configuration actionConfig = new Configuration();
            actionConfig.put("removeuid", uid);
            actions.add(ModuleBuilder.createAction().withId("autodelete").withTypeUID("rules.RemoveRuleAction").withConfiguration(actionConfig).build());
        }
    }
    builder.withActions(actions);
    return builder.withVisibility(Visibility.VISIBLE).withTags(SCHEDULE_TAG).build();
}
Also used : HueCommand(org.openhab.io.hueemulation.internal.dto.changerequest.HueCommand) Action(org.openhab.core.automation.Action) Configuration(org.openhab.core.config.core.Configuration) ArrayList(java.util.ArrayList)

Example 5 with Action

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

Action (org.openhab.core.automation.Action)40 Trigger (org.openhab.core.automation.Trigger)27 Configuration (org.openhab.core.config.core.Configuration)22 Rule (org.openhab.core.automation.Rule)20 HashMap (java.util.HashMap)19 JavaOSGiTest (org.openhab.core.test.java.JavaOSGiTest)16 Test (org.junit.jupiter.api.Test)15 Condition (org.openhab.core.automation.Condition)15 ArrayList (java.util.ArrayList)14 Random (java.util.Random)13 Nullable (org.eclipse.jdt.annotation.Nullable)12 Event (org.openhab.core.events.Event)12 EventSubscriber (org.openhab.core.events.EventSubscriber)12 ItemCommandEvent (org.openhab.core.items.events.ItemCommandEvent)12 RuleRegistry (org.openhab.core.automation.RuleRegistry)9 RuleStatusInfoEvent (org.openhab.core.automation.events.RuleStatusInfoEvent)9 EventPublisher (org.openhab.core.events.EventPublisher)9 NonNullByDefault (org.eclipse.jdt.annotation.NonNullByDefault)8 Item (org.openhab.core.items.Item)8 Logger (org.slf4j.Logger)8