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.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.core.library.types.DecimalType;
26 import org.openhab.core.library.types.OnOffType;
27 import org.openhab.core.library.types.StringType;
28 import org.openhab.core.thing.ChannelUID;
29 import org.openhab.core.thing.Thing;
30 import org.openhab.core.thing.ThingStatus;
31 import org.openhab.core.thing.ThingStatusDetail;
32 import org.openhab.core.types.Command;
33 import org.openhab.core.types.RefreshType;
34 import org.openhab.core.types.UnDefType;
35 import org.slf4j.Logger;
36 import org.slf4j.LoggerFactory;
38 import com.digitaldan.jomnilinkII.Message;
39 import com.digitaldan.jomnilinkII.MessageTypes.ObjectStatus;
40 import com.digitaldan.jomnilinkII.MessageTypes.SecurityCodeValidation;
41 import com.digitaldan.jomnilinkII.MessageTypes.properties.AreaProperties;
42 import com.digitaldan.jomnilinkII.MessageTypes.statuses.ExtendedAreaStatus;
43 import com.digitaldan.jomnilinkII.MessageTypes.systemevents.AllOnOffEvent;
44 import com.digitaldan.jomnilinkII.OmniInvalidResponseException;
45 import com.digitaldan.jomnilinkII.OmniUnknownMessageTypeException;
48 * The {@link AbstractAreaHandler} defines some methods that can be used across
49 * the many different areas defined in an OmniLink Controller.
51 * @author Craig Hamilton - Initial contribution
52 * @author Ethan Dye - openHAB3 rewrite
55 public abstract class AbstractAreaHandler extends AbstractOmnilinkStatusHandler<ExtendedAreaStatus> {
56 private final Logger logger = LoggerFactory.getLogger(AbstractAreaHandler.class);
57 private final int thingID = getThingNumber();
59 public AbstractAreaHandler(Thing thing) {
64 public void initialize() {
65 final OmnilinkBridgeHandler bridgeHandler = getOmnilinkBridgeHandler();
68 if (bridgeHandler != null) {
69 updateAreaProperties(bridgeHandler);
71 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.OFFLINE.COMMUNICATION_ERROR,
72 "Received null bridge while initializing Area!");
76 private void updateAreaProperties(OmnilinkBridgeHandler bridgeHandler) {
77 final List<AreaProperties> areas = getAreaProperties();
79 for (AreaProperties areaProperties : areas) {
80 String thingName = areaProperties.getName();
81 if (areaProperties.getNumber() == 1 && "".equals(thingName)) {
82 thingName = "Main Area";
84 Map<String, String> properties = editProperties();
85 properties.put(THING_PROPERTIES_NAME, thingName);
86 updateProperties(properties);
92 public void handleCommand(ChannelUID channelUID, Command command) {
93 logger.debug("handleCommand: {}, command: {}", channelUID, command);
95 if (command instanceof RefreshType) {
96 retrieveStatus().ifPresentOrElse(this::updateChannels, () -> updateStatus(ThingStatus.OFFLINE,
97 ThingStatusDetail.OFFLINE.COMMUNICATION_ERROR, "Received null staus update!"));
101 switch (channelUID.getId()) {
102 case CHANNEL_AREA_ACTIVATE_KEYPAD_EMERGENCY:
103 handleKeypadEmergency(channelUID, command);
106 handleSecurityMode(channelUID, command);
111 private void handleSecurityMode(ChannelUID channelUID, Command command) {
112 int mode = getMode(channelUID);
114 if (!(command instanceof StringType)) {
115 logger.debug("Invalid command: {}, must be StringType", command);
119 logger.debug("Received mode: {}, on area: {}", mode, thingID);
121 char[] code = command.toFullString().toCharArray();
122 if (code.length != 4) {
123 logger.warn("Invalid code length, code must be 4 digits");
125 // mode, codeNum, areaNum
127 final OmnilinkBridgeHandler bridge = getOmnilinkBridgeHandler();
128 if (bridge != null) {
129 SecurityCodeValidation codeValidation = bridge.reqSecurityCodeValidation(thingID,
130 Character.getNumericValue(code[0]), Character.getNumericValue(code[1]),
131 Character.getNumericValue(code[2]), Character.getNumericValue(code[3]));
138 logger.debug("User code number: {}, level: {}", codeValidation.getCodeNumber(),
139 codeValidation.getAuthorityLevel());
142 * Valid user code number are 1-99, 251 is duress code, 0 means code does not exist
144 if ((codeValidation.getCodeNumber() > 0 && codeValidation.getCodeNumber() <= 99)
145 && codeValidation.getAuthorityLevel() > 0) {
146 sendOmnilinkCommand(mode, codeValidation.getCodeNumber(), thingID);
148 logger.warn("System reported an invalid code");
151 logger.debug("Received null bridge while sending area command!");
153 } catch (OmniInvalidResponseException e) {
154 logger.debug("Could not arm area: {}, are all zones closed?", e.getMessage());
155 } catch (OmniUnknownMessageTypeException | BridgeOfflineException e) {
156 logger.debug("Could not send area command: {}", e.getMessage());
159 // This is a send only channel, so don't store the user code
160 updateState(channelUID, UnDefType.UNDEF);
164 * Get the specific mode for the OmniLink type
166 * @param channelUID Channel that maps to a mode
167 * @return OmniLink representation of mode.
169 protected abstract int getMode(ChannelUID channelUID);
172 * Get the set of alarms supported by this area handler.
174 * @return Set of alarms for this handler.
176 protected abstract EnumSet<AreaAlarm> getAlarms();
178 private void handleKeypadEmergency(ChannelUID channelUID, Command command) {
179 if (command instanceof DecimalType) {
181 final OmnilinkBridgeHandler bridge = getOmnilinkBridgeHandler();
182 if (bridge != null) {
183 bridge.activateKeypadEmergency(thingID, ((DecimalType) command).intValue());
185 logger.debug("Received null bridge while sending Keypad Emergency command!");
187 } catch (OmniInvalidResponseException | OmniUnknownMessageTypeException | BridgeOfflineException e) {
188 logger.debug("Received exception while sending command to OmniLink Controller: {}", e.getMessage());
191 logger.debug("Invalid command: {}, must be DecimalType", command);
196 public void updateChannels(ExtendedAreaStatus status) {
197 logger.debug("Handle area event: mode: {}, alarms: {}, entryTimer: {}, exitTimer: {}", status.getMode(),
198 status.getAlarms(), status.getEntryTimer(), status.getExitTimer());
201 * According to the specification, if the 3rd bit is set on a area mode, then that mode is in a delayed state.
202 * Unfortunately, this is not the case, but we can fix that by looking to see if the exit timer
203 * is set and do this manually.
205 int mode = status.getExitTimer() > 0 ? status.getMode() | 1 << 3 : status.getMode();
206 updateState(new ChannelUID(thing.getUID(), CHANNEL_AREA_MODE), new DecimalType(mode));
209 * Alarm status is actually 8 status, packed into each bit, so we loop through to see if a bit is set, note that
210 * this means you can have multiple alarms set at once
212 BigInteger alarmBits = BigInteger.valueOf(status.getAlarms());
213 for (AreaAlarm alarm : getAlarms()) {
214 OnOffType alarmState = OnOffType.from(alarm.isSet(alarmBits));
215 updateState(new ChannelUID(thing.getUID(), alarm.getChannelUID()), alarmState);
219 public void handleAllOnOffEvent(AllOnOffEvent event) {
220 ChannelUID activateChannel = new ChannelUID(getThing().getUID(), TRIGGER_CHANNEL_AREA_ALL_ON_OFF_EVENT);
221 triggerChannel(activateChannel, event.isOn() ? "ON" : "OFF");
225 protected Optional<ExtendedAreaStatus> retrieveStatus() {
227 final OmnilinkBridgeHandler bridge = getOmnilinkBridgeHandler();
228 if (bridge != null) {
229 ObjectStatus objStatus = bridge.requestObjectStatus(Message.OBJ_TYPE_AREA, thingID, thingID, true);
230 return Optional.of((ExtendedAreaStatus) objStatus.getStatuses()[0]);
232 logger.debug("Received null bridge while updating Area status!");
233 return Optional.empty();
235 } catch (OmniInvalidResponseException | OmniUnknownMessageTypeException | BridgeOfflineException e) {
236 logger.debug("Received exception while refreshing Area status: {}", e.getMessage());
237 return Optional.empty();