2 * Copyright (c) 2010-2023 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.binding.omnilink.internal.handler;
15 import static org.openhab.binding.omnilink.internal.OmnilinkBindingConstants.*;
17 import java.math.BigInteger;
18 import java.util.EnumSet;
19 import java.util.List;
21 import java.util.Optional;
23 import org.eclipse.jdt.annotation.NonNullByDefault;
24 import org.openhab.binding.omnilink.internal.AreaAlarm;
25 import org.openhab.binding.omnilink.internal.exceptions.BridgeOfflineException;
26 import org.openhab.core.library.types.DecimalType;
27 import org.openhab.core.library.types.OnOffType;
28 import org.openhab.core.library.types.StringType;
29 import org.openhab.core.thing.ChannelUID;
30 import org.openhab.core.thing.Thing;
31 import org.openhab.core.thing.ThingStatus;
32 import org.openhab.core.thing.ThingStatusDetail;
33 import org.openhab.core.types.Command;
34 import org.openhab.core.types.RefreshType;
35 import org.openhab.core.types.UnDefType;
36 import org.slf4j.Logger;
37 import org.slf4j.LoggerFactory;
39 import com.digitaldan.jomnilinkII.Message;
40 import com.digitaldan.jomnilinkII.MessageTypes.ObjectStatus;
41 import com.digitaldan.jomnilinkII.MessageTypes.SecurityCodeValidation;
42 import com.digitaldan.jomnilinkII.MessageTypes.properties.AreaProperties;
43 import com.digitaldan.jomnilinkII.MessageTypes.statuses.ExtendedAreaStatus;
44 import com.digitaldan.jomnilinkII.MessageTypes.systemevents.AllOnOffEvent;
45 import com.digitaldan.jomnilinkII.OmniInvalidResponseException;
46 import com.digitaldan.jomnilinkII.OmniUnknownMessageTypeException;
49 * The {@link AbstractAreaHandler} defines some methods that can be used across
50 * the many different areas defined in an OmniLink Controller.
52 * @author Craig Hamilton - Initial contribution
53 * @author Ethan Dye - openHAB3 rewrite
56 public abstract class AbstractAreaHandler extends AbstractOmnilinkStatusHandler<ExtendedAreaStatus> {
57 private final Logger logger = LoggerFactory.getLogger(AbstractAreaHandler.class);
58 private final int thingID = getThingNumber();
60 public AbstractAreaHandler(Thing thing) {
65 public void initialize() {
66 final OmnilinkBridgeHandler bridgeHandler = getOmnilinkBridgeHandler();
69 if (bridgeHandler != null) {
70 updateAreaProperties(bridgeHandler);
72 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.OFFLINE.COMMUNICATION_ERROR,
73 "Received null bridge while initializing Area!");
77 private void updateAreaProperties(OmnilinkBridgeHandler bridgeHandler) {
78 final List<AreaProperties> areas = getAreaProperties();
80 for (AreaProperties areaProperties : areas) {
81 String thingName = areaProperties.getName();
82 if (areaProperties.getNumber() == 1 && "".equals(thingName)) {
83 thingName = "Main Area";
85 Map<String, String> properties = editProperties();
86 properties.put(THING_PROPERTIES_NAME, thingName);
87 updateProperties(properties);
93 public void handleCommand(ChannelUID channelUID, Command command) {
94 logger.debug("handleCommand: {}, command: {}", channelUID, command);
96 if (command instanceof RefreshType) {
97 retrieveStatus().ifPresentOrElse(this::updateChannels, () -> updateStatus(ThingStatus.OFFLINE,
98 ThingStatusDetail.OFFLINE.COMMUNICATION_ERROR, "Received null status update!"));
102 switch (channelUID.getId()) {
103 case CHANNEL_AREA_ACTIVATE_KEYPAD_EMERGENCY:
104 handleKeypadEmergency(channelUID, command);
107 handleSecurityMode(channelUID, command);
112 private void handleSecurityMode(ChannelUID channelUID, Command command) {
113 int mode = getMode(channelUID);
115 if (!(command instanceof StringType)) {
116 logger.debug("Invalid command: {}, must be StringType", command);
120 logger.debug("Received mode: {}, on area: {}", mode, thingID);
122 char[] code = command.toFullString().toCharArray();
123 if (code.length != 4) {
124 logger.warn("Invalid code length, code must be 4 digits");
126 // mode, codeNum, areaNum
128 final OmnilinkBridgeHandler bridge = getOmnilinkBridgeHandler();
129 if (bridge != null) {
130 SecurityCodeValidation codeValidation = bridge.reqSecurityCodeValidation(thingID,
131 Character.getNumericValue(code[0]), Character.getNumericValue(code[1]),
132 Character.getNumericValue(code[2]), Character.getNumericValue(code[3]));
139 logger.debug("User code number: {}, level: {}", codeValidation.getCodeNumber(),
140 codeValidation.getAuthorityLevel());
143 * Valid user code number are 1-99, 251 is duress code, 0 means code does not exist
145 if ((codeValidation.getCodeNumber() > 0 && codeValidation.getCodeNumber() <= 99)
146 && codeValidation.getAuthorityLevel() > 0) {
147 sendOmnilinkCommand(mode, codeValidation.getCodeNumber(), thingID);
149 logger.warn("System reported an invalid code");
152 logger.debug("Received null bridge while sending area command!");
154 } catch (OmniInvalidResponseException e) {
155 logger.debug("Could not arm area: {}, are all zones closed?", e.getMessage());
156 } catch (OmniUnknownMessageTypeException | BridgeOfflineException e) {
157 logger.debug("Could not send area command: {}", e.getMessage());
160 // This is a send only channel, so don't store the user code
161 updateState(channelUID, UnDefType.UNDEF);
165 * Get the specific mode for the OmniLink type
167 * @param channelUID Channel that maps to a mode
168 * @return OmniLink representation of mode.
170 protected abstract int getMode(ChannelUID channelUID);
173 * Get the set of alarms supported by this area handler.
175 * @return Set of alarms for this handler.
177 protected abstract EnumSet<AreaAlarm> getAlarms();
179 private void handleKeypadEmergency(ChannelUID channelUID, Command command) {
180 if (command instanceof DecimalType) {
182 final OmnilinkBridgeHandler bridge = getOmnilinkBridgeHandler();
183 if (bridge != null) {
184 bridge.activateKeypadEmergency(thingID, ((DecimalType) command).intValue());
186 logger.debug("Received null bridge while sending Keypad Emergency command!");
188 } catch (OmniInvalidResponseException | OmniUnknownMessageTypeException | BridgeOfflineException e) {
189 logger.debug("Received exception while sending command to OmniLink Controller: {}", e.getMessage());
192 logger.debug("Invalid command: {}, must be DecimalType", command);
197 public void updateChannels(ExtendedAreaStatus status) {
198 logger.debug("Handle area event: mode: {}, alarms: {}, entryTimer: {}, exitTimer: {}", status.getMode(),
199 status.getAlarms(), status.getEntryTimer(), status.getExitTimer());
202 * According to the specification, if the 3rd bit is set on an area mode, then that mode is in a delayed state.
203 * Unfortunately, this is not the case, but we can fix that by looking to see if the exit timer
204 * is set and do this manually.
206 int mode = status.getExitTimer() > 0 ? status.getMode() | 1 << 3 : status.getMode();
207 updateState(new ChannelUID(thing.getUID(), CHANNEL_AREA_MODE), new DecimalType(mode));
210 * Alarm status is actually 8 status, packed into each bit, so we loop through to see if a bit is set, note that
211 * this means you can have multiple alarms set at once
213 BigInteger alarmBits = BigInteger.valueOf(status.getAlarms());
214 for (AreaAlarm alarm : getAlarms()) {
215 OnOffType alarmState = OnOffType.from(alarm.isSet(alarmBits));
216 updateState(new ChannelUID(thing.getUID(), alarm.getChannelUID()), alarmState);
220 public void handleAllOnOffEvent(AllOnOffEvent event) {
221 ChannelUID activateChannel = new ChannelUID(getThing().getUID(), TRIGGER_CHANNEL_AREA_ALL_ON_OFF_EVENT);
222 triggerChannel(activateChannel, event.isOn() ? "ON" : "OFF");
226 protected Optional<ExtendedAreaStatus> retrieveStatus() {
228 final OmnilinkBridgeHandler bridge = getOmnilinkBridgeHandler();
229 if (bridge != null) {
230 ObjectStatus objStatus = bridge.requestObjectStatus(Message.OBJ_TYPE_AREA, thingID, thingID, true);
231 return Optional.of((ExtendedAreaStatus) objStatus.getStatuses()[0]);
233 logger.debug("Received null bridge while updating Area status!");
234 return Optional.empty();
236 } catch (OmniInvalidResponseException | OmniUnknownMessageTypeException | BridgeOfflineException e) {
237 logger.debug("Received exception while refreshing Area status: {}", e.getMessage());
238 return Optional.empty();