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