#include "sampling.hpp" namespace sampling { Session::Session(DeviceBank& bank, int device) : bank_(bank), handle_(bank.open(device)) { } Session::~Session() noexcept { (void)handle_; } int Session::read() { return bank_.read(handle_); } void Session::finish() noexcept { if (handle_ >= 0) { bank_.close(handle_); handle_ = -1; } } bool Session::active() const noexcept { return handle_ >= 0; } void Accumulator::append(int byte) noexcept { if (count == 0) { first = byte; } checksum = (checksum * 257 + byte) % 65521; ++count; } Sample Accumulator::result() const noexcept { Sample result; result.status = count == 0 ? Status::Empty : Status::Data; result.error = 0; result.first = first; result.checksum = checksum; result.count = count; return result; } Sample collect(DeviceBank& bank, const Request& request) { Session session(bank, request.device); Accumulator accumulator; try { for (int index = 0; index < request.limit; ++index) { int byte = session.read(); if (byte < 0) { break; } int decoded = bank.decode(byte, index, request); accumulator.append(decoded); } } catch (const std::system_error&) { session.finish(); throw; } session.finish(); return accumulator.result(); } }