]> git.basschouten.com Git - openhab-addons.git/blob
fe1e41985ecb582006a4520210f1bf782761e18c
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2020 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.lcn.internal;
14
15 import java.util.ArrayList;
16 import java.util.Collection;
17 import java.util.Collections;
18 import java.util.HashMap;
19 import java.util.List;
20 import java.util.Map;
21 import java.util.NoSuchElementException;
22 import java.util.Optional;
23
24 import org.eclipse.jdt.annotation.NonNullByDefault;
25 import org.eclipse.jdt.annotation.Nullable;
26 import org.openhab.binding.lcn.internal.common.DimmerOutputCommand;
27 import org.openhab.binding.lcn.internal.common.LcnAddr;
28 import org.openhab.binding.lcn.internal.common.LcnAddrMod;
29 import org.openhab.binding.lcn.internal.common.LcnChannelGroup;
30 import org.openhab.binding.lcn.internal.common.LcnException;
31 import org.openhab.binding.lcn.internal.connection.Connection;
32 import org.openhab.binding.lcn.internal.connection.ModInfo;
33 import org.openhab.binding.lcn.internal.converter.Converter;
34 import org.openhab.binding.lcn.internal.converter.Converters;
35 import org.openhab.binding.lcn.internal.converter.InversionConverter;
36 import org.openhab.binding.lcn.internal.converter.S0Converter;
37 import org.openhab.binding.lcn.internal.subhandler.AbstractLcnModuleSubHandler;
38 import org.openhab.binding.lcn.internal.subhandler.LcnModuleMetaAckSubHandler;
39 import org.openhab.binding.lcn.internal.subhandler.LcnModuleMetaFirmwareSubHandler;
40 import org.openhab.core.library.types.DecimalType;
41 import org.openhab.core.library.types.HSBType;
42 import org.openhab.core.library.types.OnOffType;
43 import org.openhab.core.library.types.PercentType;
44 import org.openhab.core.library.types.QuantityType;
45 import org.openhab.core.library.types.StopMoveType;
46 import org.openhab.core.library.types.StringType;
47 import org.openhab.core.library.types.UpDownType;
48 import org.openhab.core.thing.Bridge;
49 import org.openhab.core.thing.Channel;
50 import org.openhab.core.thing.ChannelUID;
51 import org.openhab.core.thing.Thing;
52 import org.openhab.core.thing.ThingStatus;
53 import org.openhab.core.thing.ThingStatusDetail;
54 import org.openhab.core.thing.binding.BaseThingHandler;
55 import org.openhab.core.thing.binding.ThingHandlerService;
56 import org.openhab.core.types.Command;
57 import org.openhab.core.types.RefreshType;
58 import org.openhab.core.types.State;
59 import org.slf4j.Logger;
60 import org.slf4j.LoggerFactory;
61
62 /**
63  * The {@link LcnModuleHandler} is responsible for handling commands, which are
64  * sent to or received from one of the channels.
65  *
66  * @author Fabian Wolter - Initial contribution
67  */
68 @NonNullByDefault
69 public class LcnModuleHandler extends BaseThingHandler {
70     private final Logger logger = LoggerFactory.getLogger(LcnModuleHandler.class);
71     private static final Map<String, Converter> VALUE_CONVERTERS = new HashMap<>();
72     private static final InversionConverter INVERSION_CONVERTER = new InversionConverter();
73     private @Nullable LcnAddrMod moduleAddress;
74     private final Map<LcnChannelGroup, @Nullable AbstractLcnModuleSubHandler> subHandlers = new HashMap<>();
75     private final List<AbstractLcnModuleSubHandler> metadataSubHandlers = new ArrayList<>();
76     private final Map<ChannelUID, @Nullable Converter> converters = new HashMap<>();
77
78     static {
79         VALUE_CONVERTERS.put("temperature", Converters.TEMPERATURE);
80         VALUE_CONVERTERS.put("light", Converters.LIGHT);
81         VALUE_CONVERTERS.put("co2", Converters.CO2);
82         VALUE_CONVERTERS.put("current", Converters.CURRENT);
83         VALUE_CONVERTERS.put("voltage", Converters.VOLTAGE);
84         VALUE_CONVERTERS.put("angle", Converters.ANGLE);
85         VALUE_CONVERTERS.put("windspeed", Converters.WINDSPEED);
86     }
87
88     public LcnModuleHandler(Thing thing) {
89         super(thing);
90     }
91
92     @Override
93     public void initialize() {
94         LcnModuleConfiguration localConfig = getConfigAs(LcnModuleConfiguration.class);
95         LcnAddrMod localModuleAddress = moduleAddress = new LcnAddrMod(localConfig.segmentId, localConfig.moduleId);
96
97         try {
98             // Determine serial number of manually added modules
99             requestFirmwareVersionAndSerialNumberIfNotSet();
100
101             // create sub handlers
102             ModInfo info = getPckGatewayHandler().getModInfo(localModuleAddress);
103             for (LcnChannelGroup type : LcnChannelGroup.values()) {
104                 subHandlers.put(type, type.createSubHandler(this, info));
105             }
106
107             // meta sub handlers, which are not assigned to a channel group
108             metadataSubHandlers.add(new LcnModuleMetaAckSubHandler(this, info));
109             metadataSubHandlers.add(new LcnModuleMetaFirmwareSubHandler(this, info));
110
111             // initialize converters
112             for (Channel channel : thing.getChannels()) {
113                 Object unitObject = channel.getConfiguration().get("unit");
114                 Object parameterObject = channel.getConfiguration().get("parameter");
115                 Object invertConfig = channel.getConfiguration().get("invertState");
116
117                 // Initialize value converters
118                 if (unitObject instanceof String) {
119                     switch ((String) unitObject) {
120                         case "power":
121                         case "energy":
122                             converters.put(channel.getUID(), new S0Converter(parameterObject));
123                             break;
124                         default:
125                             if (VALUE_CONVERTERS.containsKey(unitObject)) {
126                                 converters.put(channel.getUID(), VALUE_CONVERTERS.get(unitObject));
127                             }
128                             break;
129                     }
130                 }
131
132                 // Initialize inversion converter
133                 if (invertConfig instanceof Boolean && invertConfig.equals(true)) {
134                     converters.put(channel.getUID(), INVERSION_CONVERTER);
135                 }
136
137             }
138
139             // module is assumed as online, when the corresponding Bridge (PckGatewayHandler) is online.
140             updateStatus(ThingStatus.ONLINE);
141         } catch (LcnException e) {
142             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, e.getMessage());
143         }
144     }
145
146     /**
147      * Triggers requesting the firmware version of the LCN module. The message also contains the serial number.
148      *
149      * @throws LcnException when the handler is not initialized
150      */
151     @SuppressWarnings("null")
152     protected void requestFirmwareVersionAndSerialNumberIfNotSet() throws LcnException {
153         String serialNumber = getThing().getProperties().get(Thing.PROPERTY_SERIAL_NUMBER);
154         if (serialNumber == null || serialNumber.isEmpty()) {
155             LcnAddrMod localModuleAddress = moduleAddress;
156             if (localModuleAddress != null) {
157                 getPckGatewayHandler().getModInfo(localModuleAddress).requestFirmwareVersion();
158             }
159         }
160     }
161
162     @Override
163     public void handleCommand(ChannelUID channelUid, Command command) {
164         try {
165             String groupId = channelUid.getGroupId();
166
167             if (!channelUid.isInGroup()) {
168                 return;
169             }
170
171             if (groupId == null) {
172                 throw new LcnException("Group ID is null");
173             }
174
175             LcnChannelGroup channelGroup = LcnChannelGroup.valueOf(groupId.toUpperCase());
176             AbstractLcnModuleSubHandler subHandler = subHandlers.get(channelGroup);
177
178             if (subHandler == null) {
179                 throw new LcnException("Sub Handler not found for: " + channelGroup);
180             }
181
182             Optional<Integer> number = channelUidToChannelNumber(channelUid, channelGroup);
183
184             if (command instanceof RefreshType) {
185                 number.ifPresent(n -> subHandler.handleRefresh(channelGroup, n));
186                 subHandler.handleRefresh(channelUid.getIdWithoutGroup());
187             } else if (command instanceof OnOffType) {
188                 subHandler.handleCommandOnOff((OnOffType) command, channelGroup, number.get());
189             } else if (command instanceof DimmerOutputCommand) {
190                 subHandler.handleCommandDimmerOutput((DimmerOutputCommand) command, number.get());
191             } else if (command instanceof PercentType && number.isPresent()) {
192                 subHandler.handleCommandPercent((PercentType) command, channelGroup, number.get());
193             } else if (command instanceof HSBType) {
194                 subHandler.handleCommandHsb((HSBType) command, channelUid.getIdWithoutGroup());
195             } else if (command instanceof PercentType) {
196                 subHandler.handleCommandPercent((PercentType) command, channelGroup, channelUid.getIdWithoutGroup());
197             } else if (command instanceof StringType) {
198                 subHandler.handleCommandString((StringType) command, number.get());
199             } else if (command instanceof DecimalType) {
200                 DecimalType decimalType = (DecimalType) command;
201                 DecimalType nativeValue = getConverter(channelUid).onCommandFromItem(decimalType.doubleValue());
202                 subHandler.handleCommandDecimal(nativeValue, channelGroup, number.get());
203             } else if (command instanceof QuantityType) {
204                 QuantityType<?> quantityType = (QuantityType<?>) command;
205                 DecimalType nativeValue = getConverter(channelUid).onCommandFromItem(quantityType);
206                 subHandler.handleCommandDecimal(nativeValue, channelGroup, number.get());
207             } else if (command instanceof UpDownType) {
208                 Channel channel = thing.getChannel(channelUid);
209                 if (channel != null) {
210                     Object invertConfig = channel.getConfiguration().get("invertUpDown");
211                     boolean invertUpDown = invertConfig instanceof Boolean && (boolean) invertConfig;
212                     subHandler.handleCommandUpDown((UpDownType) command, channelGroup, number.get(), invertUpDown);
213                 }
214             } else if (command instanceof StopMoveType) {
215                 subHandler.handleCommandStopMove((StopMoveType) command, channelGroup, number.get());
216             } else {
217                 throw new LcnException("Unsupported command type");
218             }
219         } catch (IllegalArgumentException | NoSuchElementException | LcnException e) {
220             logger.warn("{}: Failed to handle command {}: {}", channelUid, command.getClass().getSimpleName(),
221                     e.getMessage());
222         }
223     }
224
225     @NonNullByDefault({}) // getOrDefault()
226     private Converter getConverter(ChannelUID channelUid) {
227         return converters.getOrDefault(channelUid, Converters.IDENTITY);
228     }
229
230     /**
231      * Invoked when a PCK messages arrives from the PCK gateway
232      *
233      * @param pck the message without line termination
234      */
235     @SuppressWarnings("null")
236     public void handleStatusMessage(String pck) {
237         for (AbstractLcnModuleSubHandler handler : subHandlers.values()) {
238             if (handler.tryParse(pck)) {
239                 break;
240             }
241         }
242
243         metadataSubHandlers.forEach(h -> h.tryParse(pck));
244     }
245
246     private Optional<Integer> channelUidToChannelNumber(ChannelUID channelUid, LcnChannelGroup channelGroup)
247             throws LcnException {
248         try {
249             int number = Integer.parseInt(channelUid.getIdWithoutGroup()) - 1;
250
251             if (!channelGroup.isValidId(number)) {
252                 throw new LcnException("Out of range: " + number);
253             }
254             return Optional.of(number);
255         } catch (NumberFormatException e) {
256             return Optional.empty();
257         }
258     }
259
260     private PckGatewayHandler getPckGatewayHandler() throws LcnException {
261         Bridge bridge = getBridge();
262         if (bridge == null) {
263             throw new LcnException("No LCN-PCK gateway configured for this module");
264         }
265
266         PckGatewayHandler handler = (PckGatewayHandler) bridge.getHandler();
267         if (handler == null) {
268             throw new LcnException("Could not get PckGatewayHandler");
269         }
270         return handler;
271     }
272
273     /**
274      * Queues a PCK string for sending.
275      *
276      * @param command without the address part
277      * @throws LcnException when the module address is unknown
278      */
279     public void sendPck(String command) throws LcnException {
280         getPckGatewayHandler().queue(getCommandAddress(), true, command);
281     }
282
283     /**
284      * Queues a PCK byte buffer for sending.
285      *
286      * @param command without the address part
287      * @throws LcnException when the module address is unknown
288      */
289     public void sendPck(byte[] command) throws LcnException {
290         getPckGatewayHandler().queue(getCommandAddress(), true, command);
291     }
292
293     /**
294      * Gets the address, which shall be used when sending commands into the LCN bus. This can also be a group address.
295      *
296      * @return the address to send to
297      * @throws LcnException when the address is unknown
298      */
299     protected LcnAddr getCommandAddress() throws LcnException, LcnException {
300         LcnAddr localAddress = moduleAddress;
301         if (localAddress == null) {
302             throw new LcnException("Module address not set");
303         }
304         return localAddress;
305     }
306
307     /**
308      * Invoked when an update for this LCN module should be fired to openHAB.
309      *
310      * @param channelGroup the Channel to update
311      * @param channelId the ID within the Channel to update
312      * @param state the new state
313      */
314     public void updateChannel(LcnChannelGroup channelGroup, String channelId, State state) {
315         ChannelUID channelUid = createChannelUid(channelGroup, channelId);
316         Converter converter = converters.get(channelUid);
317
318         State convertedState = state;
319         if (converter != null) {
320             convertedState = converter.onStateUpdateFromHandler(state);
321         }
322
323         updateState(channelUid, convertedState);
324     }
325
326     /**
327      * Updates the LCN module's serial number property.
328      *
329      * @param serialNumber the new serial number
330      */
331     public void updateSerialNumberProperty(String serialNumber) {
332         updateProperty(Thing.PROPERTY_SERIAL_NUMBER, serialNumber);
333     }
334
335     /**
336      * Invoked when an trigger for this LCN module should be fired to openHAB.
337      *
338      * @param channelGroup the Channel to update
339      * @param channelId the ID within the Channel to update
340      * @param event the event used to trigger
341      */
342     public void triggerChannel(LcnChannelGroup channelGroup, String channelId, String event) {
343         triggerChannel(createChannelUid(channelGroup, channelId), event);
344     }
345
346     private ChannelUID createChannelUid(LcnChannelGroup channelGroup, String channelId) {
347         return new ChannelUID(thing.getUID(), channelGroup.name().toLowerCase() + "#" + channelId);
348     }
349
350     /**
351      * Checks the LCN module address against the own.
352      *
353      * @param physicalSegmentId which is 0 if it is the local segment
354      * @param moduleId
355      * @return true, if the given address matches the own address
356      */
357     public boolean isMyAddress(String physicalSegmentId, String moduleId) {
358         try {
359             return new LcnAddrMod(getPckGatewayHandler().toLogicalSegmentId(Integer.parseInt(physicalSegmentId)),
360                     Integer.parseInt(moduleId)).equals(getStatusMessageAddress());
361         } catch (LcnException e) {
362             return false;
363         }
364     }
365
366     @Override
367     public Collection<Class<? extends ThingHandlerService>> getServices() {
368         return Collections.singleton(LcnModuleActions.class);
369     }
370
371     /**
372      * Invoked when an Ack from this module has been received.
373      */
374     public void onAckRceived() {
375         try {
376             Connection connection = getPckGatewayHandler().getConnection();
377             LcnAddrMod localModuleAddress = moduleAddress;
378             if (connection != null && localModuleAddress != null) {
379                 getPckGatewayHandler().getModInfo(localModuleAddress).onAck(LcnBindingConstants.CODE_ACK, connection,
380                         getPckGatewayHandler().getTimeoutMs(), System.nanoTime());
381             }
382         } catch (LcnException e) {
383             logger.warn("Connection or module address not set");
384         }
385     }
386
387     /**
388      * Gets the address the handler shall react to, when a status message from this address is processed.
389      *
390      * @return the address for status messages
391      */
392     public LcnAddrMod getStatusMessageAddress() {
393         LcnAddrMod localmoduleAddress = moduleAddress;
394         if (localmoduleAddress != null) {
395             return localmoduleAddress;
396         } else {
397             return new LcnAddrMod(0, 0);
398         }
399     }
400
401     @Override
402     public void dispose() {
403         metadataSubHandlers.clear();
404         subHandlers.clear();
405         converters.clear();
406     }
407 }