Search in sources :

Example 1 with Command

use of org.eclipse.smarthome.core.types.Command in project smarthome by eclipse.

the class AutoUpdateBinding method receiveCommand.

/**
 * Handle the received command event.
 *
 * <p>
 * If the command could be converted to a {@link State} the auto-update configurations are inspected.
 * If there is at least one configuration that enable the auto-update, auto-update is applied.
 * If there is no configuration provided at all the autoupdate defaults to {@code true} and an update is posted for
 * the corresponding {@link State}.
 *
 * @param commandEvent the command event
 */
@Override
protected void receiveCommand(ItemCommandEvent commandEvent) {
    final Command command = commandEvent.getItemCommand();
    if (command instanceof State) {
        final State state = (State) command;
        final String itemName = commandEvent.getItemName();
        Boolean autoUpdate = autoUpdate(itemName);
        // we didn't find any autoupdate configuration, so apply the default now
        if (autoUpdate == null) {
            autoUpdate = Boolean.TRUE;
        }
        if (autoUpdate) {
            postUpdate(itemName, state);
        } else {
            logger.trace("Won't update item '{}' as it is not configured to update its state automatically.", itemName);
        }
    }
}
Also used : Command(org.eclipse.smarthome.core.types.Command) State(org.eclipse.smarthome.core.types.State)

Example 2 with Command

use of org.eclipse.smarthome.core.types.Command in project smarthome by eclipse.

the class ItemResource method postItemCommand.

@POST
@RolesAllowed({ Role.USER, Role.ADMIN })
@Path("/{itemname: [a-zA-Z_0-9]*}")
@Consumes(MediaType.TEXT_PLAIN)
@ApiOperation(value = "Sends a command to an item.")
@ApiResponses(value = { @ApiResponse(code = 200, message = "OK"), @ApiResponse(code = 404, message = "Item not found"), @ApiResponse(code = 400, message = "Item command null") })
public Response postItemCommand(@PathParam("itemname") @ApiParam(value = "item name", required = true) String itemname, @ApiParam(value = "valid item command (e.g. ON, OFF, UP, DOWN, REFRESH)", required = true) String value) {
    Item item = getItem(itemname);
    Command command = null;
    if (item != null) {
        if ("toggle".equalsIgnoreCase(value) && (item instanceof SwitchItem || item instanceof RollershutterItem)) {
            if (OnOffType.ON.equals(item.getStateAs(OnOffType.class))) {
                command = OnOffType.OFF;
            }
            if (OnOffType.OFF.equals(item.getStateAs(OnOffType.class))) {
                command = OnOffType.ON;
            }
            if (UpDownType.UP.equals(item.getStateAs(UpDownType.class))) {
                command = UpDownType.DOWN;
            }
            if (UpDownType.DOWN.equals(item.getStateAs(UpDownType.class))) {
                command = UpDownType.UP;
            }
        } else {
            command = TypeParser.parseCommand(item.getAcceptedCommandTypes(), value);
        }
        if (command != null) {
            logger.debug("Received HTTP POST request at '{}' with value '{}'.", uriInfo.getPath(), value);
            eventPublisher.post(ItemEventFactory.createCommandEvent(itemname, command));
            ResponseBuilder resbuilder = Response.ok();
            resbuilder.type(MediaType.TEXT_PLAIN);
            return resbuilder.build();
        } else {
            logger.warn("Received HTTP POST request at '{}' with an invalid status value '{}'.", uriInfo.getPath(), value);
            return Response.status(Status.BAD_REQUEST).build();
        }
    } else {
        logger.info("Received HTTP POST request at '{}' for the unknown item '{}'.", uriInfo.getPath(), itemname);
        throw new WebApplicationException(404);
    }
}
Also used : ActiveItem(org.eclipse.smarthome.core.items.ActiveItem) SwitchItem(org.eclipse.smarthome.core.library.items.SwitchItem) RollershutterItem(org.eclipse.smarthome.core.library.items.RollershutterItem) GroupItem(org.eclipse.smarthome.core.items.GroupItem) GenericItem(org.eclipse.smarthome.core.items.GenericItem) Item(org.eclipse.smarthome.core.items.Item) WebApplicationException(javax.ws.rs.WebApplicationException) Command(org.eclipse.smarthome.core.types.Command) OnOffType(org.eclipse.smarthome.core.library.types.OnOffType) RollershutterItem(org.eclipse.smarthome.core.library.items.RollershutterItem) UpDownType(org.eclipse.smarthome.core.library.types.UpDownType) ResponseBuilder(javax.ws.rs.core.Response.ResponseBuilder) SwitchItem(org.eclipse.smarthome.core.library.items.SwitchItem) Path(javax.ws.rs.Path) RolesAllowed(javax.annotation.security.RolesAllowed) POST(javax.ws.rs.POST) Consumes(javax.ws.rs.Consumes) ApiOperation(io.swagger.annotations.ApiOperation) ApiResponses(io.swagger.annotations.ApiResponses)

Example 3 with Command

use of org.eclipse.smarthome.core.types.Command in project smarthome by eclipse.

the class CommunicationManager method handleEvent.

private <T extends Type> void handleEvent(String itemName, T type, String source, Function<@Nullable String, @Nullable List<Class<? extends T>>> acceptedTypesFunction, ProfileAction<T> action) {
    final Item item = getItem(itemName);
    if (item == null) {
        logger.debug("Received an event for item {} which does not exist", itemName);
        return;
    }
    itemChannelLinkRegistry.stream().filter(link -> {
        // all links for the item
        return link.getItemName().equals(itemName);
    }).filter(link -> {
        // make sure the command event is not sent back to its source
        return !link.getLinkedUID().toString().equals(source);
    }).forEach(link -> {
        ChannelUID channelUID = link.getLinkedUID();
        Thing thing = getThing(channelUID.getThingUID());
        if (thing != null) {
            Channel channel = thing.getChannel(channelUID.getId());
            if (channel != null) {
                @Nullable T convertedType = toAcceptedType(type, channel, acceptedTypesFunction);
                if (convertedType != null) {
                    if (thing.getHandler() != null) {
                        Profile profile = getProfile(link, item, thing);
                        action.handle(profile, thing, convertedType);
                    }
                } else {
                    logger.debug("Received event '{}' ({}) could not be converted to any type accepted by item '{}' ({})", type, type.getClass().getSimpleName(), itemName, item.getType());
                }
            } else {
                logger.debug("Received  event '{}' for non-existing channel '{}', not forwarding it to the handler", type, channelUID);
            }
        } else {
            logger.debug("Received  event '{}' for non-existing thing '{}', not forwarding it to the handler", type, channelUID.getThingUID());
        }
    });
}
Also used : Channel(org.eclipse.smarthome.core.thing.Channel) Arrays(java.util.Arrays) ItemFactory(org.eclipse.smarthome.core.items.ItemFactory) ProfileFactory(org.eclipse.smarthome.core.thing.profiles.ProfileFactory) LoggerFactory(org.slf4j.LoggerFactory) Command(org.eclipse.smarthome.core.types.Command) ItemChannelLinkConfigDescriptionProvider(org.eclipse.smarthome.core.thing.internal.link.ItemChannelLinkConfigDescriptionProvider) ChannelUID(org.eclipse.smarthome.core.thing.ChannelUID) Nullable(org.eclipse.jdt.annotation.Nullable) Map(java.util.Map) Thing(org.eclipse.smarthome.core.thing.Thing) UID(org.eclipse.smarthome.core.thing.UID) State(org.eclipse.smarthome.core.types.State) NonNullByDefault(org.eclipse.jdt.annotation.NonNullByDefault) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Set(java.util.Set) EventPublisher(org.eclipse.smarthome.core.events.EventPublisher) ItemStateConverter(org.eclipse.smarthome.core.items.ItemStateConverter) ReferencePolicy(org.osgi.service.component.annotations.ReferencePolicy) CopyOnWriteArraySet(java.util.concurrent.CopyOnWriteArraySet) ThingEventFactory(org.eclipse.smarthome.core.thing.events.ThingEventFactory) List(java.util.List) StateProfile(org.eclipse.smarthome.core.thing.profiles.StateProfile) Entry(java.util.Map.Entry) NonNull(org.eclipse.jdt.annotation.NonNull) SystemProfileFactory(org.eclipse.smarthome.core.thing.internal.profiles.SystemProfileFactory) ThingUID(org.eclipse.smarthome.core.thing.ThingUID) ItemCommandEvent(org.eclipse.smarthome.core.items.events.ItemCommandEvent) EventFilter(org.eclipse.smarthome.core.events.EventFilter) EventSubscriber(org.eclipse.smarthome.core.events.EventSubscriber) Function(java.util.function.Function) RegistryChangeListener(org.eclipse.smarthome.core.common.registry.RegistryChangeListener) HashSet(java.util.HashSet) ProfileCallbackImpl(org.eclipse.smarthome.core.thing.internal.profiles.ProfileCallbackImpl) Component(org.osgi.service.component.annotations.Component) SafeCaller(org.eclipse.smarthome.core.common.SafeCaller) Type(org.eclipse.smarthome.core.types.Type) ProfileCallback(org.eclipse.smarthome.core.thing.profiles.ProfileCallback) TriggerProfile(org.eclipse.smarthome.core.thing.profiles.TriggerProfile) Logger(org.slf4j.Logger) Profile(org.eclipse.smarthome.core.thing.profiles.Profile) Item(org.eclipse.smarthome.core.items.Item) ItemStateEvent(org.eclipse.smarthome.core.items.events.ItemStateEvent) ItemChannelLink(org.eclipse.smarthome.core.thing.link.ItemChannelLink) ItemRegistry(org.eclipse.smarthome.core.items.ItemRegistry) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) ThingRegistry(org.eclipse.smarthome.core.thing.ThingRegistry) ReferenceCardinality(org.osgi.service.component.annotations.ReferenceCardinality) ProfileAdvisor(org.eclipse.smarthome.core.thing.profiles.ProfileAdvisor) ChannelTriggeredEvent(org.eclipse.smarthome.core.thing.events.ChannelTriggeredEvent) ItemChannelLinkRegistry(org.eclipse.smarthome.core.thing.link.ItemChannelLinkRegistry) Event(org.eclipse.smarthome.core.events.Event) ProfileTypeUID(org.eclipse.smarthome.core.thing.profiles.ProfileTypeUID) Reference(org.osgi.service.component.annotations.Reference) Collections(java.util.Collections) Item(org.eclipse.smarthome.core.items.Item) ChannelUID(org.eclipse.smarthome.core.thing.ChannelUID) Channel(org.eclipse.smarthome.core.thing.Channel) Thing(org.eclipse.smarthome.core.thing.Thing) Nullable(org.eclipse.jdt.annotation.Nullable) StateProfile(org.eclipse.smarthome.core.thing.profiles.StateProfile) TriggerProfile(org.eclipse.smarthome.core.thing.profiles.TriggerProfile) Profile(org.eclipse.smarthome.core.thing.profiles.Profile)

Example 4 with Command

use of org.eclipse.smarthome.core.types.Command in project smarthome by eclipse.

the class CommunicationManager method receiveCommand.

private void receiveCommand(ItemCommandEvent commandEvent) {
    final String itemName = commandEvent.getItemName();
    final Command command = commandEvent.getItemCommand();
    handleEvent(itemName, command, commandEvent.getSource(), s -> acceptedCommandTypeMap.get(s), (profile, thing, convertedCommand) -> {
        if (profile instanceof StateProfile) {
            // 
            safeCaller.create(((StateProfile) profile), StateProfile.class).withAsync().withIdentifier(// 
            thing).withTimeout(// 
            THINGHANDLER_EVENT_TIMEOUT).build().onCommandFromItem(convertedCommand);
        }
    });
}
Also used : Command(org.eclipse.smarthome.core.types.Command) StateProfile(org.eclipse.smarthome.core.thing.profiles.StateProfile)

Example 5 with Command

use of org.eclipse.smarthome.core.types.Command in project smarthome by eclipse.

the class SystemFollowProfile method onStateUpdateFromItem.

@Override
public void onStateUpdateFromItem(State state) {
    if (!(state instanceof Command)) {
        logger.debug("The given state {} could not be transformed to a command", state);
        return;
    }
    Command command = (Command) state;
    callback.handleCommand(command);
}
Also used : Command(org.eclipse.smarthome.core.types.Command)

Aggregations

Command (org.eclipse.smarthome.core.types.Command)23 Item (org.eclipse.smarthome.core.items.Item)9 ItemNotFoundException (org.eclipse.smarthome.core.items.ItemNotFoundException)7 ChannelUID (org.eclipse.smarthome.core.thing.ChannelUID)6 Thing (org.eclipse.smarthome.core.thing.Thing)6 JavaOSGiTest (org.eclipse.smarthome.test.java.JavaOSGiTest)6 Test (org.junit.Test)6 GroupItem (org.eclipse.smarthome.core.items.GroupItem)5 BaseThingHandler (org.eclipse.smarthome.core.thing.binding.BaseThingHandler)5 ThingHandler (org.eclipse.smarthome.core.thing.binding.ThingHandler)4 Semaphore (java.util.concurrent.Semaphore)3 ItemCommandEvent (org.eclipse.smarthome.core.items.events.ItemCommandEvent)3 SwitchItem (org.eclipse.smarthome.core.library.items.SwitchItem)3 OnOffType (org.eclipse.smarthome.core.library.types.OnOffType)3 State (org.eclipse.smarthome.core.types.State)3 HashMap (java.util.HashMap)2 Map (java.util.Map)2 NonNull (org.eclipse.jdt.annotation.NonNull)2 EventPublisher (org.eclipse.smarthome.core.events.EventPublisher)2 ItemRegistry (org.eclipse.smarthome.core.items.ItemRegistry)2