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.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.apache.commons.io.IOUtils;
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
31 public final class TelegramReaderUtil {
32 private static final String TELEGRAM_EXT = ".telegram";
34 private TelegramReaderUtil() {
39 * Reads the raw bytes of the telegram given the file relative to this package and returns the objects.
41 * @param telegramName name of the telegram file to read
42 * @return The raw bytes of a telegram
44 public static byte[] readRawTelegram(String telegramName) {
45 try (InputStream is = TelegramReaderUtil.class.getResourceAsStream(telegramName + TELEGRAM_EXT)) {
46 return IOUtils.toByteArray(is);
47 } catch (IOException e) {
48 throw new AssertionError("IOException reading telegram data: ", e);
53 * Reads a telegram given the file relative to this package and returns the objects.
55 * @param telegramName name of the telegram file to read
56 * @param expectedTelegramState expected state of the telegram read
57 * @return a P1Telegram object
59 public static P1Telegram readTelegram(String telegramName, TelegramState expectedTelegramState) {
60 AtomicReference<P1Telegram> p1Telegram = new AtomicReference<>();
61 byte[] telegram = readRawTelegram(telegramName);
62 P1TelegramParser parser = new P1TelegramParser(p1Telegram::set);
64 parser.setLenientMode(true);
65 parser.parse(telegram, telegram.length);
66 assertNotNull(p1Telegram.get(), "Telegram state should have been set. (Missing newline at end of message?)");
67 assertEquals(expectedTelegramState, p1Telegram.get().getTelegramState(),
68 "Expected TelegramState should be as expected");
69 return p1Telegram.get();