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