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.lgtvserial.internal.protocol.serial.commands;
15 import java.io.IOException;
17 import org.openhab.binding.lgtvserial.internal.protocol.serial.LGSerialCommand;
18 import org.openhab.binding.lgtvserial.internal.protocol.serial.LGSerialCommunicator;
19 import org.openhab.binding.lgtvserial.internal.protocol.serial.LGSerialResponse;
20 import org.openhab.binding.lgtvserial.internal.protocol.serial.responses.StringResponse;
21 import org.openhab.core.thing.ChannelUID;
24 * This class represents the base for most, if not all, LG commands.
27 * - the command1 character which represents the command group
28 * - the command2 character which represents the command in the group
29 * - the setid which represents the device to target defined by the protocol, 0 means it will target all devices
30 * - updatable which represents if this command can actually change the device state, or can only retrieve it's state
33 * @author Richard Lavoie - Initial contribution
36 public abstract class BaseLGSerialCommand implements LGSerialCommand {
38 private char command1;
39 private char command2;
41 private boolean updatable;
43 public BaseLGSerialCommand(char command1, char command2, int setId, boolean updatable) {
44 this.command1 = command1;
45 this.command2 = command2;
47 this.updatable = true;
51 public void execute(ChannelUID channel, LGSerialCommunicator comm, Object data) throws IOException {
52 if (!updatable && data != null) {
53 throw new IllegalArgumentException("This command cannot set any data on the TV, " //
54 + "the only allowed value is null, got : " + data);
56 comm.write(this, getCommand(data), channel);
60 public LGSerialResponse parseResponse(String response) {
61 int set = Integer.parseInt(response.substring(2, 4), 16);
62 boolean success = 'O' == response.charAt(5) && 'K' == response.charAt(6);
64 String data = response.substring(7);
67 return new StringResponse(set, success, data);
70 return createResponse(set, success, data);
73 protected abstract LGSerialResponse createResponse(int set, boolean success, String data);
75 protected String getCommand(Object data) {
76 return command1 + "" + command2 + " " + String.format("%02x", setId) + " "
77 + (data == null ? "FF" : computeSerialDataFrom(data));
80 protected abstract String computeSerialDataFrom(Object data);