2 * Copyright (c) 2010-2020 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.nibeheatpump.internal.message;
15 import org.openhab.binding.nibeheatpump.internal.NibeHeatPumpException;
16 import org.openhab.binding.nibeheatpump.internal.protocol.NibeHeatPumpProtocol;
19 * The {@link ModbusReadRequestMessage} implements Nibe read request message.
21 * @author Pauli Anttila - Initial contribution
23 public class ModbusReadRequestMessage extends NibeHeatPumpBaseMessage {
25 private int coilAddress;
27 private ModbusReadRequestMessage(MessageBuilder builder) {
28 super.msgType = MessageType.MODBUS_READ_REQUEST_MSG;
29 this.coilAddress = builder.coilAddress;
32 ModbusReadRequestMessage(byte[] data) throws NibeHeatPumpException {
36 public int getCoilAddress() {
41 public void encodeMessage(byte[] data) throws NibeHeatPumpException {
42 if (NibeHeatPumpProtocol.isModbus40ReadRequestPdu(data)) {
43 super.encodeMessage(data);
44 coilAddress = (data[4] & 0xFF) << 8 | (data[3] & 0xFF);
46 throw new NibeHeatPumpException("Not Read Request message");
51 public byte[] decodeMessage() {
52 return createModbus40ReadPdu(coilAddress);
55 private byte[] createModbus40ReadPdu(int coilAddress) {
56 byte[] data = new byte[6];
57 data[0] = NibeHeatPumpProtocol.FRAME_START_CHAR_TO_NIBE;
58 data[1] = NibeHeatPumpProtocol.CMD_MODBUS_READ_REQ;
59 data[2] = (byte) 0x02; // data len
60 data[3] = (byte) (coilAddress & 0xFF);
61 data[4] = (byte) ((coilAddress >> 8) & 0xFF);
62 data[5] = NibeHeatPumpProtocol.calculateChecksum(data, 0, 5);
68 public String toString() {
69 String str = super.toString();
70 str += ", Coil address = " + coilAddress;
75 public static class MessageBuilder {
76 private int coilAddress;
78 public MessageBuilder coilAddress(int coilAddress) {
79 this.coilAddress = coilAddress;
83 public ModbusReadRequestMessage build() {
84 return new ModbusReadRequestMessage(this);
89 public String toHexString() {
90 if (rawMessage == null) {
91 rawMessage = decodeMessage();
94 return super.toHexString();