]> git.basschouten.com Git - openhab-addons.git/blob
7e39d871ea30e96ce5a5fb65dc898b9545baa047
[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.lcn.internal;
14
15 import java.nio.ByteBuffer;
16 import java.util.Arrays;
17
18 import org.eclipse.jdt.annotation.NonNullByDefault;
19 import org.eclipse.jdt.annotation.Nullable;
20 import org.openhab.binding.lcn.internal.common.LcnChannelGroup;
21 import org.openhab.binding.lcn.internal.common.LcnDefs;
22 import org.openhab.binding.lcn.internal.common.LcnDefs.KeyTable;
23 import org.openhab.binding.lcn.internal.common.LcnDefs.SendKeyCommand;
24 import org.openhab.binding.lcn.internal.common.LcnException;
25 import org.openhab.binding.lcn.internal.common.PckGenerator;
26 import org.openhab.core.automation.annotation.ActionInput;
27 import org.openhab.core.automation.annotation.RuleAction;
28 import org.openhab.core.thing.binding.ThingActions;
29 import org.openhab.core.thing.binding.ThingActionsScope;
30 import org.openhab.core.thing.binding.ThingHandler;
31 import org.slf4j.Logger;
32 import org.slf4j.LoggerFactory;
33
34 /**
35  * Handles actions requested to be sent to an LCN module.
36  *
37  * @author Fabian Wolter - Initial contribution
38  */
39 @ThingActionsScope(name = "lcn")
40 @NonNullByDefault
41 public class LcnModuleActions implements ThingActions {
42     private final Logger logger = LoggerFactory.getLogger(LcnModuleActions.class);
43     private static final int MAX_BEEP_VOLUME = 100;
44     private static final int MAX_BEEP_COUNT = 50;
45     private static final int DYN_TEXT_CHUNK_COUNT = 5;
46     private static final int DYN_TEXT_HEADER_LENGTH = 6;
47     private static final int DYN_TEXT_CHUNK_LENGTH = 12;
48     private @Nullable LcnModuleHandler moduleHandler;
49
50     @Override
51     public void setThingHandler(@Nullable ThingHandler handler) {
52         this.moduleHandler = (LcnModuleHandler) handler;
53     }
54
55     @Override
56     public @Nullable ThingHandler getThingHandler() {
57         return moduleHandler;
58     }
59
60     @RuleAction(label = "send a hit key command", description = "Sends a \"hit key\" command to an LCN module.")
61     public void hitKey(
62             @ActionInput(name = "table", required = true, type = "java.lang.String", label = "Table", description = "The key table (A-D)") @Nullable String table,
63             @ActionInput(name = "key", required = true, type = "java.lang.Integer", label = "Key", description = "The key number (1-8)") int key,
64             @ActionInput(name = "action", required = true, type = "java.lang.String", label = "Action", description = "The action (HIT, MAKE, BREAK)") @Nullable String action) {
65         try {
66             if (table == null) {
67                 throw new LcnException("Table is not set");
68             }
69
70             if (action == null) {
71                 throw new LcnException("Action is not set");
72             }
73
74             KeyTable keyTable;
75             try {
76                 keyTable = LcnDefs.KeyTable.valueOf(table.toUpperCase());
77             } catch (IllegalArgumentException e) {
78                 throw new LcnException("Unknown key table: " + table);
79             }
80
81             SendKeyCommand sendKeyCommand;
82             try {
83                 sendKeyCommand = SendKeyCommand.valueOf(action.toUpperCase());
84             } catch (IllegalArgumentException e) {
85                 throw new LcnException("Unknown action: " + action);
86             }
87
88             if (!LcnChannelGroup.KEYLOCKTABLEA.isValidId(key - 1)) {
89                 throw new LcnException("Key number is out of range: " + key);
90             }
91
92             SendKeyCommand[] cmds = new SendKeyCommand[LcnDefs.KEY_TABLE_COUNT];
93             Arrays.fill(cmds, SendKeyCommand.DONTSEND);
94             boolean[] keys = new boolean[LcnChannelGroup.KEYLOCKTABLEA.getCount()];
95
96             int keyTableNumber = keyTable.name().charAt(0) - LcnDefs.KeyTable.A.name().charAt(0);
97             cmds[keyTableNumber] = sendKeyCommand;
98             keys[key - 1] = true;
99
100             getHandler().sendPck(PckGenerator.sendKeys(cmds, keys));
101         } catch (LcnException e) {
102             logger.warn("Could not execute hit key command: {}", e.getMessage());
103         }
104     }
105
106     @RuleAction(label = "flicker a dimmer output", description = "Let a dimmer output flicker for a given count of flashes.")
107     public void flickerOutput(
108             @ActionInput(name = "output", type = "java.lang.Integer", required = true, label = "Output", description = "The output number (1-4)") int output,
109             @ActionInput(name = "depth", type = "java.lang.Integer", label = "Depth", description = "0=25% 1=50% 2=100%") int depth,
110             @ActionInput(name = "ramp", type = "java.lang.Integer", label = "Ramp", description = "0=2sec 1=1sec 2=0.5sec") int ramp,
111             @ActionInput(name = "count", type = "java.lang.Integer", label = "Count", description = "Number of flashes (1-15)") int count) {
112         try {
113             getHandler().sendPck(PckGenerator.flickerOutput(output - 1, depth, ramp, count));
114         } catch (LcnException e) {
115             logger.warn("Could not send output flicker command: {}", e.getMessage());
116         }
117     }
118
119     @RuleAction(label = "send a custom text", description = "Send custom text to an LCN-GTxD display.")
120     public void sendDynamicText(
121             @ActionInput(name = "row", type = "java.lang.Integer", required = true, label = "Row", description = "Display the text on the LCN-GTxD in the given row number (1-4)") int row,
122             @ActionInput(name = "text", type = "java.lang.String", label = "Text", description = "The text to display (max. 60 chars/bytes)") @Nullable String textInput) {
123         try {
124             String text = textInput;
125
126             if (text == null) {
127                 text = new String();
128             }
129
130             // some LCN-GTxD don't display the text if it fits exactly in one chunk. Observed with GT10D 8.0.
131             if (text.getBytes(LcnDefs.LCN_ENCODING).length % DYN_TEXT_CHUNK_LENGTH == 0) {
132                 text += " ";
133             }
134
135             // convert String to bytes to split the data every 12 bytes, because a unicode character can take more than
136             // one byte
137             ByteBuffer bb = ByteBuffer.wrap(text.getBytes(LcnDefs.LCN_ENCODING));
138
139             if (bb.capacity() > DYN_TEXT_CHUNK_LENGTH * DYN_TEXT_CHUNK_COUNT) {
140                 logger.warn("Dynamic text truncated. Has {} bytes: '{}'", bb.capacity(), text);
141             }
142
143             bb.limit(Math.min(DYN_TEXT_CHUNK_LENGTH * DYN_TEXT_CHUNK_COUNT, bb.capacity()));
144
145             int part = 0;
146             while (bb.hasRemaining()) {
147                 byte[] chunk = new byte[DYN_TEXT_CHUNK_LENGTH];
148                 bb.get(chunk, 0, Math.min(bb.remaining(), DYN_TEXT_CHUNK_LENGTH));
149
150                 ByteBuffer command = ByteBuffer.allocate(DYN_TEXT_HEADER_LENGTH + DYN_TEXT_CHUNK_LENGTH);
151                 command.put(PckGenerator.dynTextHeader(row - 1, part++).getBytes(LcnDefs.LCN_ENCODING));
152                 command.put(chunk);
153
154                 getHandler().sendPck(command.array());
155             }
156         } catch (IllegalArgumentException | LcnException e) {
157             logger.warn("Could not send dynamic text: {}", e.getMessage());
158         }
159     }
160
161     /**
162      * Start an lcn relay timer with the given duration [ms]
163      *
164      * @param relayNumber 1-based number of the relay to use
165      * @param duration duration of the relay timer in milliseconds
166      */
167     @RuleAction(label = "start a relay timer", description = "Start an LCN relay timer.")
168     public void startRelayTimer(
169             @ActionInput(name = "relaynumber", required = true, type = "java.lang.Integer", label = "Relay Number", description = "The relay number (1-8)") int relayNumber,
170             @ActionInput(name = "duration", required = true, type = "java.lang.Double", label = "Duration [ms]", description = "The timer duration in milliseconds") double duration) {
171         try {
172             getHandler().sendPck(PckGenerator.startRelayTimer(relayNumber, duration));
173         } catch (LcnException e) {
174             logger.warn("Could not send start relay timer command: {}", e.getMessage());
175         }
176     }
177
178     /**
179      * Let the beeper connected to the LCN module beep.
180      *
181      * @param soundVolume sound volume in percent. Can be null. Then, the last volume is used.
182      * @param tonality N=normal, S=special, 1-7 tonalities 1-7. Can be null. Then, normal tonality is used.
183      * @param count number of beeps. Can be null. Then, number of beeps is one.
184      */
185     @RuleAction(label = "let the module's beeper beep", description = "Lets the beeper connected to the LCN module beep")
186     public void beep(
187             @ActionInput(name = "volume", required = false, type = "java.lang.Double", label = "Sound Volume", description = "The sound volume in percent.") @Nullable Double soundVolume,
188             @ActionInput(name = "tonality", required = false, type = "java.lang.String", label = "Tonality", description = "Tonality (N, S, 1-7)") @Nullable String tonality,
189             @ActionInput(name = "count", required = false, type = "java.lang.Integer", label = "Count", description = "Number of beeps") @Nullable Integer count) {
190         try {
191             if (soundVolume != null) {
192                 if (soundVolume < 0) {
193                     throw new LcnException("Volume cannot be negative: " + soundVolume);
194                 }
195                 getHandler().sendPck(PckGenerator.setBeepVolume(Math.min(soundVolume, MAX_BEEP_VOLUME)));
196             }
197
198             Integer localCount = count;
199             if (localCount == null) {
200                 localCount = 1;
201             }
202
203             String filteredTonality = LcnBindingConstants.ALLOWED_BEEP_TONALITIES.stream() //
204                     .filter(t -> t.equals(tonality)) //
205                     .findAny() //
206                     .orElse("N");
207
208             getHandler().sendPck(PckGenerator.beep(filteredTonality, Math.min(localCount, MAX_BEEP_COUNT)));
209         } catch (LcnException e) {
210             logger.warn("Could not send beep command: {}", e.getMessage());
211         }
212     }
213
214     /** Static alias to support the old DSL rules engine and make the action available there. */
215     public static void hitKey(ThingActions actions, @Nullable String table, int key, @Nullable String action) {
216         ((LcnModuleActions) actions).hitKey(table, key, action);
217     }
218
219     /** Static alias to support the old DSL rules engine and make the action available there. */
220     public static void flickerOutput(ThingActions actions, int output, int depth, int ramp, int count) {
221         ((LcnModuleActions) actions).flickerOutput(output, depth, ramp, count);
222     }
223
224     /** Static alias to support the old DSL rules engine and make the action available there. */
225     public static void sendDynamicText(ThingActions actions, int row, @Nullable String text) {
226         ((LcnModuleActions) actions).sendDynamicText(row, text);
227     }
228
229     /** Static alias to support the old DSL rules engine and make the action available there. */
230     public static void startRelayTimer(ThingActions actions, int relaynumber, double duration) {
231         ((LcnModuleActions) actions).startRelayTimer(relaynumber, duration);
232     }
233
234     /** Static alias to support the old DSL rules engine and make the action available there. */
235     public static void beep(ThingActions actions, Double soundVolume, String tonality, Integer count) {
236         ((LcnModuleActions) actions).beep(soundVolume, tonality, count);
237     }
238
239     private LcnModuleHandler getHandler() throws LcnException {
240         LcnModuleHandler localModuleHandler = moduleHandler;
241         if (localModuleHandler != null) {
242             return localModuleHandler;
243         } else {
244             throw new LcnException("Handler not set");
245         }
246     }
247 }