2 * Copyright (c) 2010-2021 Contributors to the openHAB project
4 * See the NOTICE file(s) distributed with this work for additional
7 * This program and the accompanying materials are made available under the
8 * terms of the Eclipse Public License 2.0 which is available at
9 * http://www.eclipse.org/legal/epl-2.0
11 * SPDX-License-Identifier: EPL-2.0
13 package org.openhab.automation.pidcontroller.internal.handler;
15 import static org.openhab.automation.pidcontroller.internal.PIDControllerConstants.AUTOMATION_NAME;
17 import java.math.BigDecimal;
20 import org.eclipse.jdt.annotation.NonNullByDefault;
21 import org.eclipse.jdt.annotation.Nullable;
22 import org.openhab.core.automation.Action;
23 import org.openhab.core.automation.handler.ActionHandler;
24 import org.openhab.core.automation.handler.BaseModuleHandler;
25 import org.openhab.core.config.core.Configuration;
26 import org.openhab.core.events.EventPublisher;
27 import org.openhab.core.items.ItemRegistry;
28 import org.openhab.core.items.events.ItemCommandEvent;
29 import org.openhab.core.items.events.ItemEventFactory;
30 import org.openhab.core.library.types.DecimalType;
31 import org.slf4j.Logger;
32 import org.slf4j.LoggerFactory;
36 * @author Hilbrand Bouwkamp - Initial Contribution
37 * @author Fabian Wolter - Add PID debugging items
40 public class PIDControllerActionHandler extends BaseModuleHandler<Action> implements ActionHandler {
41 public static final String MODULE_TYPE_ID = AUTOMATION_NAME + ".action";
43 private final Logger logger = LoggerFactory.getLogger(PIDControllerActionHandler.class);
45 private ItemRegistry itemRegistry;
46 private EventPublisher eventPublisher;
48 public PIDControllerActionHandler(Action module, ItemRegistry itemRegistry, EventPublisher eventPublisher) {
50 this.itemRegistry = itemRegistry;
51 this.eventPublisher = eventPublisher;
55 public @Nullable Map<String, Object> execute(Map<String, Object> context) {
56 final Configuration configuration = module.getConfiguration();
58 context.forEach((k, v) -> {
59 // Remove triggername from key to get raw trigger param
60 String itemKey = k.substring(k.lastIndexOf('.') + 1);
61 String itemName = (String) configuration.get(itemKey);
63 if (itemName == null || itemName.isBlank()) {
64 // try original key name (<triggername>.<trigger_param>)
65 itemName = (String) configuration.get(k);
66 if (itemName == null || itemName.isBlank()) {
70 if (v instanceof BigDecimal) {
71 final BigDecimal command = (BigDecimal) v;
72 final DecimalType outputValue = new DecimalType(command);
73 final ItemCommandEvent itemCommandEvent = ItemEventFactory.createCommandEvent(itemName, outputValue);
75 eventPublisher.post(itemCommandEvent);
78 "Command was not posted because either the configuration was not correct or a service was missing: ItemName: {}, Command: {}, eventPublisher: {}, ItemRegistry: {}",
79 itemName, v, eventPublisher, itemRegistry);