]> git.basschouten.com Git - openhab-addons.git/blob
970947763fd74fef4ab56c17fe494b4a0bcd82e0
[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.enocean.internal.handler;
14
15 import static org.openhab.binding.enocean.internal.EnOceanBindingConstants.*;
16
17 import java.util.Arrays;
18 import java.util.Collection;
19 import java.util.Collections;
20 import java.util.HashSet;
21 import java.util.Set;
22 import java.util.concurrent.ScheduledFuture;
23 import java.util.concurrent.TimeUnit;
24 import java.util.stream.Collectors;
25 import java.util.stream.Stream;
26
27 import org.openhab.binding.enocean.internal.config.EnOceanActuatorConfig;
28 import org.openhab.binding.enocean.internal.eep.EEP;
29 import org.openhab.binding.enocean.internal.eep.EEPFactory;
30 import org.openhab.binding.enocean.internal.eep.EEPType;
31 import org.openhab.binding.enocean.internal.messages.BasePacket;
32 import org.openhab.core.config.core.Configuration;
33 import org.openhab.core.thing.Channel;
34 import org.openhab.core.thing.ChannelUID;
35 import org.openhab.core.thing.Thing;
36 import org.openhab.core.thing.ThingStatus;
37 import org.openhab.core.thing.ThingTypeUID;
38 import org.openhab.core.thing.link.ItemChannelLinkRegistry;
39 import org.openhab.core.thing.type.ChannelTypeUID;
40 import org.openhab.core.types.Command;
41 import org.openhab.core.types.RefreshType;
42 import org.openhab.core.util.HexUtils;
43
44 /**
45  *
46  * @author Daniel Weber - Initial contribution
47  *         This class defines base functionality for sending eep messages. This class extends EnOceanBaseSensorHandler
48  *         class as most actuator things send status or response messages, too.
49  */
50 public class EnOceanBaseActuatorHandler extends EnOceanBaseSensorHandler {
51
52     // List of thing types which support sending of eep messages
53     public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES = new HashSet<>(Arrays.asList(THING_TYPE_CENTRALCOMMAND,
54             THING_TYPE_MEASUREMENTSWITCH, THING_TYPE_GENERICTHING, THING_TYPE_ROLLERSHUTTER, THING_TYPE_THERMOSTAT));
55
56     protected byte[] senderId; // base id of bridge + senderIdOffset, used for sending msg
57     protected byte[] destinationId; // in case of broadcast FFFFFFFF otherwise the enocean id of the device
58
59     protected EEPType sendingEEPType = null;
60
61     private ScheduledFuture<?> refreshJob; // used for polling current status of thing
62
63     public EnOceanBaseActuatorHandler(Thing thing, ItemChannelLinkRegistry itemChannelLinkRegistry) {
64         super(thing, itemChannelLinkRegistry);
65     }
66
67     /**
68      *
69      * @param senderIdOffset to be validated
70      * @return true if senderIdOffset is between ]0;128[ and is not used yet
71      */
72     private boolean validateSenderIdOffset(int senderIdOffset) {
73         if (senderIdOffset == -1) {
74             return true;
75         }
76
77         if (senderIdOffset > 0 && senderIdOffset < 128) {
78             EnOceanBridgeHandler bridgeHandler = getBridgeHandler();
79             if (bridgeHandler != null) {
80                 return !bridgeHandler.existsSender(senderIdOffset, this.thing);
81             }
82         }
83
84         return false;
85     }
86
87     @Override
88     void initializeConfig() {
89         config = getConfigAs(EnOceanActuatorConfig.class);
90     }
91
92     protected EnOceanActuatorConfig getConfiguration() {
93         return (EnOceanActuatorConfig) config;
94     }
95
96     @Override
97     Collection<EEPType> getEEPTypes() {
98         Collection<EEPType> r = super.getEEPTypes();
99         if (sendingEEPType == null) {
100             return r;
101         }
102
103         return Collections.unmodifiableCollection(Stream
104                 .concat(r.stream(), Collections.singletonList(sendingEEPType).stream()).collect(Collectors.toList()));
105     }
106
107     @Override
108     boolean validateConfig() {
109         EnOceanActuatorConfig config = getConfiguration();
110         if (config == null) {
111             configurationErrorDescription = "Configuration is not valid";
112             return false;
113         }
114
115         if (config.sendingEEPId == null || config.sendingEEPId.isEmpty()) {
116             configurationErrorDescription = "Sending EEP must be provided";
117             return false;
118         }
119
120         try {
121             sendingEEPType = EEPType.getType(getConfiguration().sendingEEPId);
122         } catch (IllegalArgumentException e) {
123             configurationErrorDescription = "Sending EEP is not supported";
124             return false;
125         }
126
127         if (super.validateConfig()) {
128             try {
129                 if (sendingEEPType.getSupportsRefresh()) {
130                     if (getConfiguration().pollingInterval > 0) {
131                         refreshJob = scheduler.scheduleWithFixedDelay(() -> {
132                             try {
133                                 refreshStates();
134                             } catch (Exception e) {
135                             }
136                         }, 30, getConfiguration().pollingInterval, TimeUnit.SECONDS);
137                     }
138                 }
139
140                 if (getConfiguration().broadcastMessages) {
141                     destinationId = new byte[] { (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff };
142                 } else {
143                     destinationId = HexUtils.hexToBytes(config.enoceanId);
144                 }
145             } catch (Exception e) {
146                 configurationErrorDescription = "Configuration is not valid";
147                 return false;
148             }
149
150             if (validateSenderIdOffset(getConfiguration().senderIdOffset)) {
151                 return initializeIdForSending();
152             } else {
153                 configurationErrorDescription = "Sender Id is not valid for bridge";
154             }
155         }
156
157         return false;
158     }
159
160     private boolean initializeIdForSending() {
161         // Generic things are treated as actuator things, however to support also generic sensors one can define a
162         // senderIdOffset of -1
163         // TODO: seperate generic actuators from generic sensors?
164         String thingTypeId = this.getThing().getThingTypeUID().getId();
165         String genericThingTypeId = THING_TYPE_GENERICTHING.getId();
166
167         if (getConfiguration().senderIdOffset == -1 && thingTypeId.equals(genericThingTypeId)) {
168             return true;
169         }
170
171         EnOceanBridgeHandler bridgeHandler = getBridgeHandler();
172         if (bridgeHandler == null) {
173             return false;
174         }
175
176         // if senderIdOffset is not set (=> defaults to -1) or set to -1, the next free senderIdOffset is determined
177         if (getConfiguration().senderIdOffset == -1) {
178             Configuration updateConfig = editConfiguration();
179             getConfiguration().senderIdOffset = bridgeHandler.getNextSenderId(thing);
180             if (getConfiguration().senderIdOffset == -1) {
181                 configurationErrorDescription = "Could not get a free sender Id from Bridge";
182                 return false;
183             }
184             updateConfig.put(PARAMETER_SENDERIDOFFSET, getConfiguration().senderIdOffset);
185             updateConfiguration(updateConfig);
186         }
187
188         byte[] baseId = bridgeHandler.getBaseId();
189         baseId[3] = (byte) ((baseId[3] & 0xFF) + getConfiguration().senderIdOffset);
190         this.senderId = baseId;
191
192         this.updateProperty(PROPERTY_ENOCEAN_ID, HexUtils.bytesToHex(this.senderId));
193         bridgeHandler.addSender(getConfiguration().senderIdOffset, thing);
194
195         return true;
196     }
197
198     private void refreshStates() {
199         logger.debug("polling channels");
200         if (thing.getStatus().equals(ThingStatus.ONLINE)) {
201             for (Channel channel : this.getThing().getChannels()) {
202                 handleCommand(channel.getUID(), RefreshType.REFRESH);
203             }
204         }
205     }
206
207     @Override
208     public void handleCommand(ChannelUID channelUID, Command command) {
209         // We must have a valid sendingEEPType and sender id to send commands
210         if (sendingEEPType == null || senderId == null) {
211             return;
212         }
213
214         // check if the channel is linked otherwise do nothing
215         String channelId = channelUID.getId();
216         Channel channel = getThing().getChannel(channelUID);
217         if (channel == null || !isLinked(channelUID)) {
218             return;
219         }
220
221         ChannelTypeUID channelTypeUID = channel.getChannelTypeUID();
222         String channelTypeId = (channelTypeUID != null) ? channelTypeUID.getId() : "";
223
224         // check if we do support refreshs
225         if (command == RefreshType.REFRESH) {
226             if (!sendingEEPType.getSupportsRefresh()) {
227                 return;
228             }
229
230             // receiving status cannot be refreshed
231             switch (channelTypeId) {
232                 case CHANNEL_RSSI:
233                 case CHANNEL_REPEATCOUNT:
234                 case CHANNEL_LASTRECEIVED:
235                     return;
236             }
237         }
238
239         try {
240             Configuration channelConfig = channel.getConfiguration();
241
242             EEP eep = EEPFactory.createEEP(sendingEEPType);
243             if (eep.convertFromCommand(channelId, channelTypeId, command, id -> getCurrentState(id), channelConfig)
244                     .hasData()) {
245                 BasePacket msg = eep.setSenderId(senderId).setDestinationId(destinationId)
246                         .setSuppressRepeating(getConfiguration().suppressRepeating).getERP1Message();
247
248                 getBridgeHandler().sendMessage(msg, null);
249             }
250
251         } catch (IllegalArgumentException e) {
252             logger.warn("Exception while sending telegram!", e);
253         }
254     }
255
256     @Override
257     public void handleRemoval() {
258         if (getConfiguration().senderIdOffset > 0) {
259             EnOceanBridgeHandler bridgeHandler = getBridgeHandler();
260             if (bridgeHandler != null) {
261                 bridgeHandler.removeSender(getConfiguration().senderIdOffset);
262             }
263         }
264
265         super.handleRemoval();
266     }
267
268     @Override
269     public void dispose() {
270         if (refreshJob != null && !refreshJob.isCancelled()) {
271             refreshJob.cancel(true);
272             refreshJob = null;
273         }
274     }
275 }