]> git.basschouten.com Git - openhab-addons.git/blob
5cb836d507f4a80bae456042fded1eef270e1a45
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2022 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.paradoxalarm.internal.communication.messages;
14
15 import java.nio.ByteBuffer;
16 import java.nio.ByteOrder;
17
18 import org.eclipse.jdt.annotation.NonNullByDefault;
19 import org.openhab.binding.paradoxalarm.internal.exceptions.ParadoxException;
20 import org.slf4j.Logger;
21 import org.slf4j.LoggerFactory;
22
23 /**
24  * The {@link MemoryRequestPayload} Abstract class which contains common logic used in RAM and EPROM payload generation
25  * classes.
26  *
27  * @author Konstantin Polihronov - Initial contribution
28  */
29 @NonNullByDefault
30 public abstract class MemoryRequestPayload implements IPayload {
31
32     private static final int BUFFER_LENGTH = 8;
33     private static final short MESSAGE_START = (short) ((0x50 << 8) | 0x08);
34
35     private final Logger logger = LoggerFactory.getLogger(MemoryRequestPayload.class);
36
37     private final int address;
38     private final byte bytesToRead;
39
40     public MemoryRequestPayload(int address, byte bytesToRead) throws ParadoxException {
41         if (bytesToRead < 1 || bytesToRead > 64) {
42             throw new ParadoxException("Invalid bytes to read. Valid values are 1 to 64.");
43         }
44
45         this.address = address;
46         this.bytesToRead = bytesToRead;
47
48         logTraceHexFormatted("MessageStart: {}", MESSAGE_START);
49     }
50
51     protected abstract byte calculateControlByte();
52
53     @Override
54     public byte[] getBytes() {
55         byte[] bufferArray = new byte[BUFFER_LENGTH];
56         ByteBuffer buffer = ByteBuffer.wrap(bufferArray);
57         buffer.order(ByteOrder.BIG_ENDIAN).putShort(MESSAGE_START);
58         buffer.put(calculateControlByte());
59         buffer.put((byte) 0x00);
60         buffer.order(ByteOrder.BIG_ENDIAN).putShort((short) address);
61         buffer.put(bytesToRead);
62         buffer.put((byte) 0x00);
63         return bufferArray;
64     }
65
66     protected int getAddress() {
67         return address;
68     }
69
70     protected void logTraceHexFormatted(String text, int address) {
71         logTraceOptional(text, "0x%02X,\t", address);
72     }
73
74     private void logTraceOptional(String text, String format, int address) {
75         if (logger.isTraceEnabled()) {
76             logger.trace("Address: {}", String.format(format, address));
77         }
78     }
79 }