]> git.basschouten.com Git - openhab-addons.git/blob
75f3146ddbcf691ec6ed4fc1bb63056031ab8ab7
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2023 Contributors to the openHAB project
3  *
4  * See the NOTICE file(s) distributed with this work for additional
5  * information.
6  *
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
10  *
11  * SPDX-License-Identifier: EPL-2.0
12  */
13 package org.openhab.binding.omnilink.internal.handler;
14
15 import static org.openhab.binding.omnilink.internal.OmnilinkBindingConstants.*;
16
17 import java.math.BigInteger;
18 import java.util.EnumSet;
19 import java.util.List;
20 import java.util.Map;
21 import java.util.Optional;
22
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;
38
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;
47
48 /**
49  * The {@link AbstractAreaHandler} defines some methods that can be used across
50  * the many different areas defined in an OmniLink Controller.
51  *
52  * @author Craig Hamilton - Initial contribution
53  * @author Ethan Dye - openHAB3 rewrite
54  */
55 @NonNullByDefault
56 public abstract class AbstractAreaHandler extends AbstractOmnilinkStatusHandler<ExtendedAreaStatus> {
57     private final Logger logger = LoggerFactory.getLogger(AbstractAreaHandler.class);
58     private final int thingID = getThingNumber();
59
60     public AbstractAreaHandler(Thing thing) {
61         super(thing);
62     }
63
64     @Override
65     public void initialize() {
66         final OmnilinkBridgeHandler bridgeHandler = getOmnilinkBridgeHandler();
67
68         super.initialize();
69         if (bridgeHandler != null) {
70             updateAreaProperties(bridgeHandler);
71         } else {
72             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.OFFLINE.COMMUNICATION_ERROR,
73                     "Received null bridge while initializing Area!");
74         }
75     }
76
77     private void updateAreaProperties(OmnilinkBridgeHandler bridgeHandler) {
78         final List<AreaProperties> areas = getAreaProperties();
79         if (areas != null) {
80             for (AreaProperties areaProperties : areas) {
81                 String thingName = areaProperties.getName();
82                 if (areaProperties.getNumber() == 1 && "".equals(thingName)) {
83                     thingName = "Main Area";
84                 }
85                 Map<String, String> properties = editProperties();
86                 properties.put(THING_PROPERTIES_NAME, thingName);
87                 updateProperties(properties);
88             }
89         }
90     }
91
92     @Override
93     public void handleCommand(ChannelUID channelUID, Command command) {
94         logger.debug("handleCommand: {}, command: {}", channelUID, command);
95
96         if (command instanceof RefreshType) {
97             retrieveStatus().ifPresentOrElse(this::updateChannels, () -> updateStatus(ThingStatus.OFFLINE,
98                     ThingStatusDetail.OFFLINE.COMMUNICATION_ERROR, "Received null status update!"));
99             return;
100         }
101
102         switch (channelUID.getId()) {
103             case CHANNEL_AREA_ACTIVATE_KEYPAD_EMERGENCY:
104                 handleKeypadEmergency(channelUID, command);
105                 break;
106             default:
107                 handleSecurityMode(channelUID, command);
108                 break;
109         }
110     }
111
112     private void handleSecurityMode(ChannelUID channelUID, Command command) {
113         int mode = getMode(channelUID);
114
115         if (!(command instanceof StringType)) {
116             logger.debug("Invalid command: {}, must be StringType", command);
117             return;
118         }
119
120         logger.debug("Received mode: {}, on area: {}", mode, thingID);
121
122         char[] code = command.toFullString().toCharArray();
123         if (code.length != 4) {
124             logger.warn("Invalid code length, code must be 4 digits");
125         } else {
126             // mode, codeNum, areaNum
127             try {
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]));
133                     /*
134                      * 0 Invalid code
135                      * 1 Master
136                      * 2 Manager
137                      * 3 User
138                      */
139                     logger.debug("User code number: {}, level: {}", codeValidation.getCodeNumber(),
140                             codeValidation.getAuthorityLevel());
141
142                     /*
143                      * Valid user code number are 1-99, 251 is duress code, 0 means code does not exist
144                      */
145                     if ((codeValidation.getCodeNumber() > 0 && codeValidation.getCodeNumber() <= 99)
146                             && codeValidation.getAuthorityLevel() > 0) {
147                         sendOmnilinkCommand(mode, codeValidation.getCodeNumber(), thingID);
148                     } else {
149                         logger.warn("System reported an invalid code");
150                     }
151                 } else {
152                     logger.debug("Received null bridge while sending area command!");
153                 }
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());
158             }
159         }
160         // This is a send only channel, so don't store the user code
161         updateState(channelUID, UnDefType.UNDEF);
162     }
163
164     /**
165      * Get the specific mode for the OmniLink type
166      *
167      * @param channelUID Channel that maps to a mode
168      * @return OmniLink representation of mode.
169      */
170     protected abstract int getMode(ChannelUID channelUID);
171
172     /**
173      * Get the set of alarms supported by this area handler.
174      *
175      * @return Set of alarms for this handler.
176      */
177     protected abstract EnumSet<AreaAlarm> getAlarms();
178
179     private void handleKeypadEmergency(ChannelUID channelUID, Command command) {
180         if (command instanceof DecimalType decimalCommand) {
181             try {
182                 final OmnilinkBridgeHandler bridge = getOmnilinkBridgeHandler();
183                 if (bridge != null) {
184                     bridge.activateKeypadEmergency(thingID, decimalCommand.intValue());
185                 } else {
186                     logger.debug("Received null bridge while sending Keypad Emergency command!");
187                 }
188             } catch (OmniInvalidResponseException | OmniUnknownMessageTypeException | BridgeOfflineException e) {
189                 logger.debug("Received exception while sending command to OmniLink Controller: {}", e.getMessage());
190             }
191         } else {
192             logger.debug("Invalid command: {}, must be DecimalType", command);
193         }
194     }
195
196     @Override
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());
200
201         /*
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.
205          */
206         int mode = status.getExitTimer() > 0 ? status.getMode() | 1 << 3 : status.getMode();
207         updateState(new ChannelUID(thing.getUID(), CHANNEL_AREA_MODE), new DecimalType(mode));
208
209         /*
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
212          */
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);
217         }
218     }
219
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");
223     }
224
225     @Override
226     protected Optional<ExtendedAreaStatus> retrieveStatus() {
227         try {
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]);
232             } else {
233                 logger.debug("Received null bridge while updating Area status!");
234                 return Optional.empty();
235             }
236         } catch (OmniInvalidResponseException | OmniUnknownMessageTypeException | BridgeOfflineException e) {
237             logger.debug("Received exception while refreshing Area status: {}", e.getMessage());
238             return Optional.empty();
239         }
240     }
241 }