]> git.basschouten.com Git - openhab-addons.git/blob
e13b66f28f685e784bf10ca8eb0bd7f591c467a4
[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.alarmdecoder.internal.protocol;
14
15 import java.util.HashMap;
16 import java.util.Map;
17 import java.util.regex.Matcher;
18 import java.util.regex.Pattern;
19
20 import org.eclipse.jdt.annotation.NonNullByDefault;
21 import org.eclipse.jdt.annotation.Nullable;
22
23 /**
24  * The {@link IntCommandMap} class contains an integer to command map used by the keypad intcommand channel.
25  *
26  * @author Bob Adair - Initial contribution
27  */
28 @NonNullByDefault
29 public class IntCommandMap {
30     private static final Pattern VALID_COMMAND_PATTERN = Pattern.compile(ADCommand.KEYPAD_COMMAND_REGEX);
31
32     private final Map<Integer, String> commandMap;
33
34     public IntCommandMap(String mappingString) throws IllegalArgumentException {
35         commandMap = new HashMap<>();
36
37         String mstring = mappingString.replace("POUND", "#");
38         String[] elements = mstring.split(",");
39         for (String element : elements) {
40             String[] kvPair = element.split("=");
41             if (kvPair.length != 2) {
42                 throw new IllegalArgumentException("Invalid key-value pair format");
43             }
44
45             Matcher matcher = VALID_COMMAND_PATTERN.matcher(kvPair[1]);
46             if (!matcher.matches()) {
47                 throw new IllegalArgumentException("Invalid command characters in mapping");
48             }
49
50             try {
51                 commandMap.put(Integer.parseInt(kvPair[0]), kvPair[1]);
52             } catch (NumberFormatException e) {
53                 throw new IllegalArgumentException("Unable to parse integer in mapping", e);
54             }
55         }
56     }
57
58     @Nullable
59     public String getCommand(int key) {
60         return commandMap.get(key);
61     }
62
63     public int size() {
64         return commandMap.size();
65     }
66 }