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.echonetlite.internal;
15 import static org.openhab.binding.echonetlite.internal.LangUtil.b;
17 import java.net.InetSocketAddress;
18 import java.net.SocketAddress;
19 import java.nio.ByteBuffer;
20 import java.nio.ByteOrder;
22 import org.eclipse.jdt.annotation.NonNullByDefault;
23 import org.eclipse.jdt.annotation.Nullable;
26 * @author Michael Barker - Initial contribution
29 public class EchonetMessageBuilder {
30 private static final byte EHD_1 = 0x10;
31 private static final byte EHD_2 = (byte) (0x81 & 0xFF);
33 private final ByteBuffer buffer;
34 private final ByteBuffer edtBuffer = ByteBuffer.allocate(4096);
35 private int opcPosition = 0;
37 private InetSocketAddress destAddress;
39 public EchonetMessageBuilder() {
40 buffer = ByteBuffer.allocateDirect(4096).order(ByteOrder.BIG_ENDIAN);
43 public void start(short tid, InstanceKey source, InstanceKey dest, Esv service) {
44 // 1081000005ff010ef0006201d60100
45 // 1081000105ff010ef0006201d600
46 // 0000 10 81 00 00 05 ff 01 0e f0 00 62 01 d6 01 00
47 // 0000 10 81 00 01 05 ff 01 0e f0 00 62 01 d6 00
49 destAddress = dest.address;
55 buffer.put(b(source.klass.groupCode()));
56 buffer.put(b(source.klass.classCode()));
57 buffer.put(b(source.instance));
58 buffer.put(b(dest.klass.groupCode()));
59 buffer.put(b(dest.klass.classCode()));
60 buffer.put(b(dest.instance));
61 buffer.put(service.code());
63 opcPosition = buffer.position();
67 private void incrementOpc() {
68 buffer.put(opcPosition, (byte) (buffer.get(opcPosition) + 1));
71 public void append(final byte edt, final byte length, final byte value) {
72 buffer.put(edt).put(length).put(value);
76 public void appendEpcRequest(final int epc) {
77 buffer.put(b(epc)).put((byte) 0);
81 public ByteBuffer buffer() {
86 public SocketAddress address() {
90 public ByteBuffer edtBuffer() {
95 public void appendEpcUpdate(final int epc, ByteBuffer edtBuffer) {
96 if (edtBuffer.remaining() < 0 || 255 < edtBuffer.remaining()) {
97 throw new IllegalArgumentException("Invalid update value, length: " + edtBuffer.remaining());
100 buffer.put(b(epc)).put(b(edtBuffer.remaining())).put(edtBuffer);