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.dsmr.internal;
15 import static org.junit.jupiter.api.Assertions.assertEquals;
16 import static org.junit.jupiter.api.Assertions.assertNotNull;
17 import static org.junit.jupiter.api.Assertions.fail;
19 import java.io.IOException;
20 import java.io.InputStream;
21 import java.util.concurrent.atomic.AtomicReference;
23 import org.eclipse.jdt.annotation.NonNullByDefault;
24 import org.openhab.binding.dsmr.internal.device.p1telegram.P1Telegram;
25 import org.openhab.binding.dsmr.internal.device.p1telegram.P1Telegram.TelegramState;
26 import org.openhab.binding.dsmr.internal.device.p1telegram.P1TelegramParser;
29 * Util class to read test input telegrams.
31 * @author Hilbrand Bouwkamp - Initial contribution
34 public final class TelegramReaderUtil {
35 private static final String TELEGRAM_EXT = ".telegram";
37 private TelegramReaderUtil() {
42 * Reads the raw bytes of the telegram given the file relative to this package and returns the objects.
44 * @param telegramName name of the telegram file to read
45 * @return The raw bytes of a telegram
47 public static byte[] readRawTelegram(String telegramName) {
48 try (InputStream is = TelegramReaderUtil.class.getResourceAsStream(telegramName + TELEGRAM_EXT)) {
50 fail("Could not find telegram file with name:" + telegramName + TELEGRAM_EXT);
52 return is.readAllBytes();
53 } catch (final IOException e) {
54 throw new AssertionError("IOException reading telegram data: ", e);
59 * Reads a telegram given the file relative to this package and returns the objects.
61 * @param telegramName name of the telegram file to read
62 * @param expectedTelegramState expected state of the telegram read
63 * @return a P1Telegram object
65 public static P1Telegram readTelegram(String telegramName, TelegramState expectedTelegramState) {
66 final AtomicReference<P1Telegram> p1Telegram = new AtomicReference<>();
67 final byte[] telegram = readRawTelegram(telegramName);
68 final P1TelegramParser parser = new P1TelegramParser(p1Telegram::set, true);
70 parser.setLenientMode(true);
71 parser.parse(telegram, telegram.length);
72 assertNotNull(p1Telegram.get(), "Telegram state should have been set. (Missing newline at end of message?)");
73 assertEquals(expectedTelegramState, p1Telegram.get().getTelegramState(),
74 "Expected TelegramState should be as expected");
75 return p1Telegram.get();