]> git.basschouten.com Git - openhab-addons.git/blob
73588375e2e750cd6becc5d76311f6037cb64026
[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, AbstractLcnModuleSubHandler> subHandlers = new HashMap<>();
75     private final List<AbstractLcnModuleSubHandler> metadataSubHandlers = new ArrayList<>();
76     private final Map<ChannelUID, 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 invertState = channel.getConfiguration().get("invertState");
116                 Object invertUpDown = channel.getConfiguration().get("invertUpDown");
117
118                 // Initialize value converters
119                 if (unitObject instanceof String) {
120                     switch ((String) unitObject) {
121                         case "power":
122                         case "energy":
123                             converters.put(channel.getUID(), new S0Converter(parameterObject));
124                             break;
125                         default:
126                             Converter converter = VALUE_CONVERTERS.get(unitObject);
127                             if (converter != null) {
128                                 converters.put(channel.getUID(), converter);
129                             }
130                             break;
131                     }
132                 }
133
134                 // Initialize inversion converter
135                 if (Boolean.TRUE.equals(invertState) || Boolean.TRUE.equals(invertUpDown)) {
136                     converters.put(channel.getUID(), INVERSION_CONVERTER);
137                 }
138
139             }
140
141             // module is assumed as online, when the corresponding Bridge (PckGatewayHandler) is online.
142             updateStatus(ThingStatus.ONLINE);
143         } catch (LcnException e) {
144             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, e.getMessage());
145         }
146     }
147
148     /**
149      * Triggers requesting the firmware version of the LCN module. The message also contains the serial number.
150      *
151      * @throws LcnException when the handler is not initialized
152      */
153     @SuppressWarnings("null")
154     protected void requestFirmwareVersionAndSerialNumberIfNotSet() throws LcnException {
155         String serialNumber = getThing().getProperties().get(Thing.PROPERTY_SERIAL_NUMBER);
156         if (serialNumber == null || serialNumber.isEmpty()) {
157             LcnAddrMod localModuleAddress = moduleAddress;
158             if (localModuleAddress != null) {
159                 getPckGatewayHandler().getModInfo(localModuleAddress).requestFirmwareVersion();
160             }
161         }
162     }
163
164     @Override
165     public void handleCommand(ChannelUID channelUid, Command command) {
166         try {
167             String groupId = channelUid.getGroupId();
168
169             if (!channelUid.isInGroup()) {
170                 return;
171             }
172
173             if (groupId == null) {
174                 throw new LcnException("Group ID is null");
175             }
176
177             LcnChannelGroup channelGroup = LcnChannelGroup.valueOf(groupId.toUpperCase());
178             AbstractLcnModuleSubHandler subHandler = subHandlers.get(channelGroup);
179
180             if (subHandler == null) {
181                 throw new LcnException("Sub Handler not found for: " + channelGroup);
182             }
183
184             Optional<Integer> number = channelUidToChannelNumber(channelUid, channelGroup);
185
186             if (command instanceof RefreshType) {
187                 number.ifPresent(n -> subHandler.handleRefresh(channelGroup, n));
188                 subHandler.handleRefresh(channelUid.getIdWithoutGroup());
189             } else if (command instanceof OnOffType) {
190                 subHandler.handleCommandOnOff((OnOffType) command, channelGroup, number.get());
191             } else if (command instanceof DimmerOutputCommand) {
192                 subHandler.handleCommandDimmerOutput((DimmerOutputCommand) command, number.get());
193             } else if (command instanceof PercentType && number.isPresent()) {
194                 subHandler.handleCommandPercent((PercentType) command, channelGroup, number.get());
195             } else if (command instanceof HSBType) {
196                 subHandler.handleCommandHsb((HSBType) command, channelUid.getIdWithoutGroup());
197             } else if (command instanceof PercentType) {
198                 subHandler.handleCommandPercent((PercentType) command, channelGroup, channelUid.getIdWithoutGroup());
199             } else if (command instanceof StringType) {
200                 subHandler.handleCommandString((StringType) command, number.get());
201             } else if (command instanceof DecimalType) {
202                 DecimalType decimalType = (DecimalType) command;
203                 DecimalType nativeValue = getConverter(channelUid).onCommandFromItem(decimalType.doubleValue());
204                 subHandler.handleCommandDecimal(nativeValue, channelGroup, number.get());
205             } else if (command instanceof QuantityType) {
206                 QuantityType<?> quantityType = (QuantityType<?>) command;
207                 DecimalType nativeValue = getConverter(channelUid).onCommandFromItem(quantityType);
208                 subHandler.handleCommandDecimal(nativeValue, channelGroup, number.get());
209             } else if (command instanceof UpDownType) {
210                 Channel channel = thing.getChannel(channelUid);
211                 if (channel != null) {
212                     Object invertConfig = channel.getConfiguration().get("invertUpDown");
213                     boolean invertUpDown = invertConfig instanceof Boolean && (boolean) invertConfig;
214                     subHandler.handleCommandUpDown((UpDownType) command, channelGroup, number.get(), invertUpDown);
215                 }
216             } else if (command instanceof StopMoveType) {
217                 subHandler.handleCommandStopMove((StopMoveType) command, channelGroup, number.get());
218             } else {
219                 throw new LcnException("Unsupported command type");
220             }
221         } catch (IllegalArgumentException | NoSuchElementException | LcnException e) {
222             logger.warn("{}: Failed to handle command {}: {}", channelUid, command.getClass().getSimpleName(),
223                     e.getMessage());
224         }
225     }
226
227     @NonNullByDefault({}) // getOrDefault()
228     private Converter getConverter(ChannelUID channelUid) {
229         return converters.getOrDefault(channelUid, Converters.IDENTITY);
230     }
231
232     /**
233      * Invoked when a PCK messages arrives from the PCK gateway
234      *
235      * @param pck the message without line termination
236      */
237     @SuppressWarnings("null")
238     public void handleStatusMessage(String pck) {
239         for (AbstractLcnModuleSubHandler handler : subHandlers.values()) {
240             if (handler.tryParse(pck)) {
241                 break;
242             }
243         }
244
245         metadataSubHandlers.forEach(h -> h.tryParse(pck));
246     }
247
248     private Optional<Integer> channelUidToChannelNumber(ChannelUID channelUid, LcnChannelGroup channelGroup)
249             throws LcnException {
250         try {
251             int number = Integer.parseInt(channelUid.getIdWithoutGroup()) - 1;
252
253             if (!channelGroup.isValidId(number)) {
254                 throw new LcnException("Out of range: " + number);
255             }
256             return Optional.of(number);
257         } catch (NumberFormatException e) {
258             return Optional.empty();
259         }
260     }
261
262     private PckGatewayHandler getPckGatewayHandler() throws LcnException {
263         Bridge bridge = getBridge();
264         if (bridge == null) {
265             throw new LcnException("No LCN-PCK gateway configured for this module");
266         }
267
268         PckGatewayHandler handler = (PckGatewayHandler) bridge.getHandler();
269         if (handler == null) {
270             throw new LcnException("Could not get PckGatewayHandler");
271         }
272         return handler;
273     }
274
275     /**
276      * Queues a PCK string for sending.
277      *
278      * @param command without the address part
279      * @throws LcnException when the module address is unknown
280      */
281     public void sendPck(String command) throws LcnException {
282         getPckGatewayHandler().queue(getCommandAddress(), true, command);
283     }
284
285     /**
286      * Queues a PCK byte buffer for sending.
287      *
288      * @param command without the address part
289      * @throws LcnException when the module address is unknown
290      */
291     public void sendPck(byte[] command) throws LcnException {
292         getPckGatewayHandler().queue(getCommandAddress(), true, command);
293     }
294
295     /**
296      * Gets the address, which shall be used when sending commands into the LCN bus. This can also be a group address.
297      *
298      * @return the address to send to
299      * @throws LcnException when the address is unknown
300      */
301     protected LcnAddr getCommandAddress() throws LcnException, LcnException {
302         LcnAddr localAddress = moduleAddress;
303         if (localAddress == null) {
304             throw new LcnException("Module address not set");
305         }
306         return localAddress;
307     }
308
309     /**
310      * Invoked when an update for this LCN module should be fired to openHAB.
311      *
312      * @param channelGroup the Channel to update
313      * @param channelId the ID within the Channel to update
314      * @param state the new state
315      */
316     public void updateChannel(LcnChannelGroup channelGroup, String channelId, State state) {
317         ChannelUID channelUid = createChannelUid(channelGroup, channelId);
318         Converter converter = converters.get(channelUid);
319
320         State convertedState = state;
321         if (converter != null) {
322             convertedState = converter.onStateUpdateFromHandler(state);
323         }
324
325         updateState(channelUid, convertedState);
326     }
327
328     /**
329      * Updates the LCN module's serial number property.
330      *
331      * @param serialNumber the new serial number
332      */
333     public void updateSerialNumberProperty(String serialNumber) {
334         updateProperty(Thing.PROPERTY_SERIAL_NUMBER, serialNumber);
335     }
336
337     /**
338      * Invoked when an trigger for this LCN module should be fired to openHAB.
339      *
340      * @param channelGroup the Channel to update
341      * @param channelId the ID within the Channel to update
342      * @param event the event used to trigger
343      */
344     public void triggerChannel(LcnChannelGroup channelGroup, String channelId, String event) {
345         triggerChannel(createChannelUid(channelGroup, channelId), event);
346     }
347
348     private ChannelUID createChannelUid(LcnChannelGroup channelGroup, String channelId) {
349         return new ChannelUID(thing.getUID(), channelGroup.name().toLowerCase() + "#" + channelId);
350     }
351
352     /**
353      * Checks the LCN module address against the own.
354      *
355      * @param physicalSegmentId which is 0 if it is the local segment
356      * @param moduleId
357      * @return true, if the given address matches the own address
358      */
359     public boolean isMyAddress(String physicalSegmentId, String moduleId) {
360         try {
361             return new LcnAddrMod(getPckGatewayHandler().toLogicalSegmentId(Integer.parseInt(physicalSegmentId)),
362                     Integer.parseInt(moduleId)).equals(getStatusMessageAddress());
363         } catch (LcnException e) {
364             return false;
365         }
366     }
367
368     @Override
369     public Collection<Class<? extends ThingHandlerService>> getServices() {
370         return Collections.singleton(LcnModuleActions.class);
371     }
372
373     /**
374      * Invoked when an Ack from this module has been received.
375      */
376     public void onAckRceived() {
377         try {
378             Connection connection = getPckGatewayHandler().getConnection();
379             LcnAddrMod localModuleAddress = moduleAddress;
380             if (connection != null && localModuleAddress != null) {
381                 getPckGatewayHandler().getModInfo(localModuleAddress).onAck(LcnBindingConstants.CODE_ACK, connection,
382                         getPckGatewayHandler().getTimeoutMs(), System.nanoTime());
383             }
384         } catch (LcnException e) {
385             logger.warn("Connection or module address not set");
386         }
387     }
388
389     /**
390      * Gets the address the handler shall react to, when a status message from this address is processed.
391      *
392      * @return the address for status messages
393      */
394     public LcnAddrMod getStatusMessageAddress() {
395         LcnAddrMod localmoduleAddress = moduleAddress;
396         if (localmoduleAddress != null) {
397             return localmoduleAddress;
398         } else {
399             return new LcnAddrMod(0, 0);
400         }
401     }
402
403     @Override
404     public void dispose() {
405         metadataSubHandlers.clear();
406         subHandlers.clear();
407         converters.clear();
408     }
409 }