BASIS 2 Driver 0.1.0
API reference
Loading...
Searching...
No Matches
alicat_basis2_modbus.hpp
Go to the documentation of this file.
1
13#ifndef ALICAT_BASIS2_MODBUS_HPP
14#define ALICAT_BASIS2_MODBUS_HPP
15
16#include <array>
17#include <cstddef>
18#include <cstdint>
19#include <span>
20
24
27
35inline constexpr uint8_t kReadHolding = 3;
37inline constexpr uint8_t kWriteSingle = 6;
39inline constexpr uint8_t kWriteMultiple = 16;
40
46[[nodiscard]] constexpr uint16_t Crc16(std::span<const uint8_t> data) noexcept {
47 uint32_t crc = 0xFFFFU;
48 for (const uint8_t byte : data) {
49 crc ^= static_cast<uint32_t>(byte);
50 for (uint32_t bit = 0U; bit < 8U; ++bit) {
51 crc = ((crc & 1U) != 0U) ? ((crc >> 1U) ^ 0xA001U) : (crc >> 1U);
52 }
53 }
54 return static_cast<uint16_t>(crc);
55}
56
57// Known vectors (Modbus over Serial Line): the request 01 03 00 00 00 0A has CRC C5CD (bytes CD C5
58// ... wire order low first is C5 CD).
59static_assert(Crc16(std::array<uint8_t, 6>{0x01, 0x03, 0x00, 0x00, 0x00, 0x0A}) == 0xCDC5U);
60
61namespace detail {
62
64[[nodiscard]] constexpr const reg::RegisterSpec* RowContaining(uint32_t r) noexcept {
65 for (const reg::RegisterSpec& row : reg::kRegisters) {
66 if ((r >= row.address) && (r < (static_cast<uint32_t>(row.address) + row.count))) {
67 return &row;
68 }
69 }
70 return nullptr;
71}
72
75[[nodiscard]] constexpr uint16_t MinFirmwareOver(uint32_t first, uint32_t n) noexcept {
76 uint16_t newest = 0U;
77 for (uint32_t r = first; r < (first + n); ++r) {
78 const reg::RegisterSpec* row = RowContaining(r);
79 if ((row != nullptr) && (row->min_fw > newest)) {
80 newest = row->min_fw;
81 }
82 }
83 return newest;
84}
85
87[[nodiscard]] constexpr const reg::RegisterSpec* RowAt(uint32_t r) noexcept {
88 for (const reg::RegisterSpec& row : reg::kRegisters) {
89 if (r == row.address) {
90 return &row;
91 }
92 }
93 return nullptr;
94}
95
97[[nodiscard]] constexpr bool ReadLegal(uint32_t first, uint32_t n) noexcept {
98 if ((n < 1U) || (n > reg::kMaxRead)) {
99 return false;
100 }
101 for (uint32_t r = first; r < (first + n); ++r) {
102 const reg::RegisterSpec* row = RowContaining(r);
103 if ((row == nullptr) || ((static_cast<uint32_t>(row->access) & 1U) == 0U)) {
104 return false;
105 }
106 }
107 return true;
108}
109
111[[nodiscard]] constexpr bool WriteLegal(uint32_t first, uint32_t count, uint32_t value) noexcept {
112 const reg::RegisterSpec* row = RowAt(first);
113 if ((row == nullptr) || (row->count != count) ||
114 ((static_cast<uint32_t>(row->access) & 2U) == 0U)) {
115 return false;
116 }
117 if (row->magic != reg::kNoMagic) {
118 return value == row->magic;
119 }
120 return (value >= row->min_value) && (value <= row->max_value);
121}
122
124[[nodiscard]] inline Request Seal(alicat_basis2::detail::RequestData& d, std::size_t n,
125 uint8_t address, uint8_t function, uint16_t reply_bytes,
126 bool idempotent) noexcept {
127 const uint16_t crc = Crc16(std::span<const uint8_t>{d.bytes.data(), n});
128 d.bytes[n] = static_cast<uint8_t>(crc & 0xFFU);
129 d.bytes[n + 1U] = static_cast<uint8_t>(crc >> 8U);
130 d.length = static_cast<uint8_t>(n + 2U);
131 d.command = Command::Modbus;
132 d.id = ::alicat_basis2::detail::CharOf(address);
133 d.modbus = true;
134 d.function = function;
135 d.idempotent = idempotent;
136 d.reply_chars = reply_bytes;
137 return alicat_basis2::detail::RequestBuilder::Build(d);
138}
139
140} // namespace detail
141
149[[nodiscard]] inline Result<Request> BuildRead(uint8_t address, uint16_t first,
150 uint16_t count) noexcept {
151 if ((address < 1U) || (address > 247U) || !detail::ReadLegal(first, count)) {
153 }
154 alicat_basis2::detail::RequestData d{};
155 d.bytes[0] = address;
156 d.bytes[1] = kReadHolding;
157 d.bytes[2] = static_cast<uint8_t>(first >> 8U);
158 d.bytes[3] = static_cast<uint8_t>(first & 0xFFU);
159 d.bytes[4] = static_cast<uint8_t>(count >> 8U);
160 d.bytes[5] = static_cast<uint8_t>(count & 0xFFU);
162 detail::Seal(d, 6U, address, kReadHolding, static_cast<uint16_t>(5U + (2U * count)), true));
163}
164
172[[nodiscard]] inline Result<Request> BuildWriteSingle(uint8_t address, uint16_t target,
173 uint16_t value) noexcept {
174 if ((address < 1U) || (address > 247U) || !detail::WriteLegal(target, 1U, value)) {
176 }
177 alicat_basis2::detail::RequestData d{};
178 d.bytes[0] = address;
179 d.bytes[1] = kWriteSingle;
180 d.bytes[2] = static_cast<uint8_t>(target >> 8U);
181 d.bytes[3] = static_cast<uint8_t>(target & 0xFFU);
182 d.bytes[4] = static_cast<uint8_t>(value >> 8U);
183 d.bytes[5] = static_cast<uint8_t>(value & 0xFFU);
184 return Result<Request>::Success(detail::Seal(d, 6U, address, kWriteSingle, 8U, false));
185}
186
194[[nodiscard]] inline Result<Request> BuildWriteMultiple(uint8_t address, uint16_t target,
195 uint32_t value) noexcept {
196 if ((address < 1U) || (address > 247U) || !detail::WriteLegal(target, 2U, value)) {
198 }
199 alicat_basis2::detail::RequestData d{};
200 d.bytes[0] = address;
201 d.bytes[1] = kWriteMultiple;
202 d.bytes[2] = static_cast<uint8_t>(target >> 8U);
203 d.bytes[3] = static_cast<uint8_t>(target & 0xFFU);
204 d.bytes[4] = 0U;
205 d.bytes[5] = 2U;
206 d.bytes[6] = 4U;
207 d.bytes[7] = static_cast<uint8_t>(value >> 24U);
208 d.bytes[8] = static_cast<uint8_t>((value >> 16U) & 0xFFU);
209 d.bytes[9] = static_cast<uint8_t>((value >> 8U) & 0xFFU);
210 d.bytes[10] = static_cast<uint8_t>(value & 0xFFU);
211 return Result<Request>::Success(detail::Seal(d, 11U, address, kWriteMultiple, 8U, false));
212}
213
223[[nodiscard]] inline bool IsLegalModbusRequest(std::span<const uint8_t> bytes) noexcept {
224 const std::size_t n = bytes.size();
225 if ((n < 8U) || (n > 13U) || (bytes[0] < 1U) || (bytes[0] > 247U)) {
226 return false;
227 }
228 const uint16_t crc = Crc16(bytes.first(n - 2U));
229 if ((bytes[n - 2U] != (crc & 0xFFU)) || (bytes[n - 1U] != (crc >> 8U))) {
230 return false;
231 }
232 const auto first = static_cast<uint32_t>((static_cast<uint32_t>(bytes[2]) << 8U) | bytes[3]);
233 const auto word = static_cast<uint32_t>((static_cast<uint32_t>(bytes[4]) << 8U) | bytes[5]);
234 if ((bytes[1] == kReadHolding) && (n == 8U)) {
235 return detail::ReadLegal(first, word);
236 }
237 if ((bytes[1] == kWriteSingle) && (n == 8U)) {
238 return detail::WriteLegal(first, 1U, word);
239 }
240 if ((bytes[1] == kWriteMultiple) && (n == 13U) && (word == 2U) && (bytes[6] == 4U)) {
241 const uint32_t value = (static_cast<uint32_t>(bytes[7]) << 24U) |
242 (static_cast<uint32_t>(bytes[8]) << 16U) |
243 (static_cast<uint32_t>(bytes[9]) << 8U) | bytes[10];
244 return detail::WriteLegal(first, 2U, value);
245 }
246 return false;
247}
248
255[[nodiscard]] inline std::size_t ReplyLength(std::span<const char> bytes) noexcept {
256 if (bytes.size() < 2U) {
257 return 0U;
258 }
259 const auto fn = static_cast<uint32_t>(::alicat_basis2::detail::ByteOf(bytes[1]));
260 if ((fn & 0x80U) != 0U) {
261 return 5U;
262 }
263 if ((fn == kWriteSingle) || (fn == kWriteMultiple)) {
264 return 8U;
265 }
266 if (fn != kReadHolding) {
267 return kMaxLine + 1U;
268 }
269 return (bytes.size() < 3U)
270 ? 0U
271 : (5U + static_cast<std::size_t>(::alicat_basis2::detail::ByteOf(bytes[2])));
272}
273
275struct Response {
276 std::array<uint16_t, reg::kMaxRead> words{};
277 uint8_t count{0};
278 uint8_t exception{0};
279};
280
281namespace detail {
282
284[[nodiscard]] inline Error ParseReadBody(const std::array<uint8_t, kMaxLine + 1U>& raw,
285 std::size_t n, Response& out) noexcept {
286 const std::size_t bytes = raw[2];
287 if ((n != (5U + bytes)) || ((bytes % 2U) != 0U) || (bytes == 0U) ||
288 ((bytes / 2U) > reg::kMaxRead)) {
289 return Error::BadReply;
290 }
291 Response r{};
292 r.count = static_cast<uint8_t>(bytes / 2U);
293 for (std::size_t i = 0U; i < r.count; ++i) {
294 r.words[i] = static_cast<uint16_t>((static_cast<uint32_t>(raw[3U + (2U * i)]) << 8U) |
295 raw[4U + (2U * i)]);
296 }
297 out = r;
298 return Error::Ok;
299}
300
303[[nodiscard]] inline bool IsWriteEcho(const std::array<uint8_t, kMaxLine + 1U>& raw, std::size_t n,
304 std::span<const uint8_t> request_bytes) noexcept {
305 if ((n != 8U) || (request_bytes.size() < 6U)) {
306 return false;
307 }
308 for (std::size_t i = 0U; i < 6U; ++i) {
309 if (raw[i] != request_bytes[i]) {
310 return false;
311 }
312 }
313 return true;
314}
315
316} // namespace detail
317
329[[nodiscard]] inline Error ParseResponse(std::span<const char> frame, uint8_t request_address,
330 uint8_t request_function,
331 std::span<const uint8_t> request_bytes,
332 Response& out) noexcept {
333 const std::size_t n = frame.size();
334 if ((n < 5U) || (n > (kMaxLine + 1U))) {
335 return Error::BadReply;
336 }
337 std::array<uint8_t, kMaxLine + 1U> raw{};
338 for (std::size_t i = 0U; i < n; ++i) {
339 raw[i] = ::alicat_basis2::detail::ByteOf(frame[i]);
340 }
341 const uint16_t crc = Crc16(std::span<const uint8_t>{raw.data(), n - 2U});
342 if ((raw[n - 2U] != (crc & 0xFFU)) || (raw[n - 1U] != (crc >> 8U))) {
343 return Error::Crc;
344 }
345 if (raw[0] != request_address) {
347 }
348 if (raw[1] == (request_function | 0x80U)) {
349 out.exception = raw[2];
350 return (n == 5U) ? Error::Rejected : Error::BadReply;
351 }
352 if (raw[1] != request_function) {
353 return Error::BadReply;
354 }
355 if (request_function == kReadHolding) {
356 return detail::ParseReadBody(raw, n, out);
357 }
358 if (!detail::IsWriteEcho(raw, n, request_bytes)) {
359 return Error::BadReply;
360 }
361 out = Response{};
362 return Error::Ok;
363}
364
367} // namespace alicat_basis2::modbus
368
369#endif // ALICAT_BASIS2_MODBUS_HPP
ALICAT_BASIS2 Modbus register map, magic values, firmware gates and unit tables (M pp....
Request and Reply: the only things the driver puts on and takes off the wire, and the timing formulas...
Public types of the ALICAT_BASIS2 driver: errors, Result<T>, configuration, enumerations and the valu...
constexpr uint8_t kReadHolding
Function code: read holding registers.
Definition alicat_basis2_modbus.hpp:35
Result< Request > BuildRead(uint8_t address, uint16_t first, uint16_t count) noexcept
Build a function 3 request.
Definition alicat_basis2_modbus.hpp:149
constexpr uint8_t kWriteSingle
Function code: write single register.
Definition alicat_basis2_modbus.hpp:37
std::size_t ReplyLength(std::span< const char > bytes) noexcept
How long the reply frame is, as far as the bytes received so far tell.
Definition alicat_basis2_modbus.hpp:255
Result< Request > BuildWriteMultiple(uint8_t address, uint16_t target, uint32_t value) noexcept
Build a function 16 request for a two-register item (32-bit value, high register first).
Definition alicat_basis2_modbus.hpp:194
constexpr uint8_t kWriteMultiple
Function code: write multiple registers.
Definition alicat_basis2_modbus.hpp:39
Error ParseResponse(std::span< const char > frame, uint8_t request_address, uint8_t request_function, std::span< const uint8_t > request_bytes, Response &out) noexcept
Parse and validate a response frame.
Definition alicat_basis2_modbus.hpp:329
Result< Request > BuildWriteSingle(uint8_t address, uint16_t target, uint16_t value) noexcept
Build a function 6 request (one register).
Definition alicat_basis2_modbus.hpp:172
bool IsLegalModbusRequest(std::span< const uint8_t > bytes) noexcept
Whether bytes is exactly one request the driver may send: a valid CRC, an address 1 to 247,...
Definition alicat_basis2_modbus.hpp:223
constexpr uint16_t Crc16(std::span< const uint8_t > data) noexcept
Modbus CRC-16 (polynomial 0xA001 reflected, initial value 0xFFFF).
Definition alicat_basis2_modbus.hpp:46
constexpr std::array< RegisterSpec, kRegisterRows > kRegisters
The register table (M pp.18 to 27). Reads may span consecutive rows; writes must match one row.
Definition alicat_basis2_registers.hpp:116
constexpr uint16_t kMaxRead
Largest register count of one read the driver issues.
Definition alicat_basis2_registers.hpp:77
constexpr uint32_t kNoMagic
Marker for "no magic value".
Definition alicat_basis2_registers.hpp:109
@ Modbus
A Modbus RTU frame (function 3, 6 or 16).
Error
Why a call failed. Every call of the driver returns one of these in its Result.
Definition alicat_basis2_types.hpp:37
constexpr std::size_t kMaxLine
Largest line or frame the driver buffers: the gas list (GS *) reply can be this long.
Definition alicat_basis2_types.hpp:272
@ InvalidArgument
An argument or a Config field is out of range; nothing was sent.
@ DeviceIdMismatch
The reply carried another unit ID or Modbus address than the one addressed.
@ Crc
Modbus CRC-16 mismatch; the whole frame is discarded.
@ BadReply
The line does not match the command's reply grammar.
@ Ok
The call succeeded.
@ Rejected
The instrument answered with the error token ? or a Modbus exception reply.
The Modbus RTU codec.
Definition alicat_basis2_modbus.hpp:26
The value of a call, or why there is none.
Definition alicat_basis2_types.hpp:151
static constexpr Result Failure(Error e) noexcept
A failed result.
Definition alicat_basis2_types.hpp:177
static constexpr Result Success(T v) noexcept
A successful result.
Definition alicat_basis2_types.hpp:169
A parsed Modbus response.
Definition alicat_basis2_modbus.hpp:275
uint8_t count
Number of register values.
Definition alicat_basis2_modbus.hpp:277
std::array< uint16_t, reg::kMaxRead > words
Register values of a read reply.
Definition alicat_basis2_modbus.hpp:276
uint8_t exception
The exception code of a Rejected reply.
Definition alicat_basis2_modbus.hpp:278