From 3c78b0b6c4f17246fa4a6a1d0e9db095ce987cbc Mon Sep 17 00:00:00 2001 From: Hans Erik van Elburg Date: Mon, 9 Dec 2019 22:36:46 +0100 Subject: [PATCH] add file reader --- dsmr_parser/clients/filereader.py | 35 +++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 dsmr_parser/clients/filereader.py diff --git a/dsmr_parser/clients/filereader.py b/dsmr_parser/clients/filereader.py new file mode 100644 index 0000000..ee1fc90 --- /dev/null +++ b/dsmr_parser/clients/filereader.py @@ -0,0 +1,35 @@ +from dsmr_parser import telegram_specifications +from dsmr_parser.clients.telegram_buffer import TelegramBuffer +from dsmr_parser.exceptions import ParseError, InvalidChecksumError +from dsmr_parser.objects import CosemObject, MBusObject, Telegram +from dsmr_parser.parsers import TelegramParser +import os + +logger = logging.getLogger(__name__) + +class FileReader(object): + + def __init__(self, file, telegram_specification): + self._file = file + self.telegram_parser = TelegramParser(telegram_specification) + self.telegram_buffer = TelegramBuffer() + self.telegram_specification = telegram_specification + + def read_as_object(self): + """ + Read complete DSMR telegram's from a file and return a Telegram object. + :rtype: generator + """ + with open(self._file,"rb") as file_handle: + while True: + data = file_handle.readline() + str = data.decode() + self.telegram_buffer.append(str) + + for telegram in self.telegram_buffer.get_all(): + try: + yield Telegram(telegram, self.telegram_parser, self.telegram_specification) + except InvalidChecksumError as e: + logger.warning(str(e)) + except ParseError as e: + logger.error('Failed to parse telegram: %s', e)