2 * Copyright (c) 2010-2023 Contributors to the openHAB project
4 * See the NOTICE file(s) distributed with this work for additional
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
11 * SPDX-License-Identifier: EPL-2.0
13 package org.openhab.binding.pjlinkdevice.internal.device.command.lampstatus;
15 import java.text.MessageFormat;
16 import java.util.ArrayList;
17 import java.util.List;
18 import java.util.regex.Matcher;
19 import java.util.regex.Pattern;
21 import org.eclipse.jdt.annotation.NonNullByDefault;
22 import org.openhab.binding.pjlinkdevice.internal.device.command.PrefixedResponse;
23 import org.openhab.binding.pjlinkdevice.internal.device.command.ResponseException;
26 * The response part of {@link LampStatesCommand}
28 * @author Nils Schnabel - Initial contribution
31 public class LampStatesResponse extends PrefixedResponse<List<LampStatesResponse.LampState>> {
32 static final Pattern RESPONSE_VALIDATION_PATTERN = Pattern.compile("^((\\d+) ([01]))( (\\d+) ([01]))*$");
33 static final Pattern RESPONSE_PARSING_PATTERN = Pattern.compile("(?<hours>\\d+) (?<active>[01])");
36 public class LampState {
37 private boolean active;
38 private int lampHours;
40 public LampState(boolean active, int lampHours) {
42 this.lampHours = lampHours;
45 public int getLampHours() {
49 public boolean isActive() {
54 public LampStatesResponse(String response) throws ResponseException {
55 super("LAMP=", response);
59 protected List<LampStatesResponse.LampState> parseResponseWithoutPrefix(String responseWithoutPrefix)
60 throws ResponseException {
61 // validate if response fully matches specification
62 if (!RESPONSE_VALIDATION_PATTERN.matcher(responseWithoutPrefix).matches()) {
63 throw new ResponseException(
64 MessageFormat.format("Lamp status response could not be parsed: ''{0}''", responseWithoutPrefix));
67 // go through individual matches for each lamp
68 List<LampStatesResponse.LampState> result = new ArrayList<>();
69 Matcher matcher = RESPONSE_PARSING_PATTERN.matcher(responseWithoutPrefix);
70 while (matcher.find()) {
71 int lampHours = Integer.parseInt(matcher.group("hours"));
72 boolean active = "1".equals(matcher.group("active"));
73 result.add(new LampState(active, lampHours));