From d3ac9c1696b4b8b9319019de9041ddcd1a1b2d26 Mon Sep 17 00:00:00 2001 From: Spencer Oliver Date: Sat, 10 May 2025 16:54:09 +0100 Subject: [PATCH] coils: ability to configure number of supported coils No change to current default behaviour of allocating 2000 coils. However memory usage can be reduced by defining NMBS_MAX_COILS. --- nanomodbus.c | 4 ++-- nanomodbus.h | 12 +++++++++++- 2 files changed, 13 insertions(+), 3 deletions(-) diff --git a/nanomodbus.c b/nanomodbus.c index d1f928f..5786301 100644 --- a/nanomodbus.c +++ b/nanomodbus.c @@ -546,7 +546,7 @@ static nmbs_error recv_read_discrete_res(nmbs_t* nmbs, nmbs_bitfield values) { uint8_t coils_bytes = get_1(nmbs); NMBS_DEBUG_PRINT("b %d\t", coils_bytes); - if (coils_bytes > 250) { + if (coils_bytes > NMBS_MAX_COIL_BYTES) { return NMBS_ERROR_INVALID_RESPONSE; } @@ -1958,7 +1958,7 @@ nmbs_error nmbs_client_create(nmbs_t* nmbs, const nmbs_platform_conf* platform_c static nmbs_error read_discrete(nmbs_t* nmbs, uint8_t fc, uint16_t address, uint16_t quantity, nmbs_bitfield values) { - if (quantity < 1 || quantity > 2000) + if (quantity < 1 || quantity > NMBS_MAX_COILS) return NMBS_ERROR_INVALID_ARGUMENT; if ((uint32_t) address + (uint32_t) quantity > ((uint32_t) 0xFFFF) + 1) diff --git a/nanomodbus.h b/nanomodbus.h index b0c872d..50aa276 100644 --- a/nanomodbus.h +++ b/nanomodbus.h @@ -78,11 +78,21 @@ typedef enum nmbs_error { */ #define nmbs_error_is_exception(e) ((e) > 0 && (e) < 5) +#ifndef NMBS_MAX_COILS + #define NMBS_MAX_COILS 2000 +#endif + +/* check coil count divisible by 8 */ +#if ((NMBS_MAX_COILS & 7) > 0) + #error "NMBS_MAX_COILS must be disible by 8" +#endif + +#define NMBS_MAX_COIL_BYTES (NMBS_MAX_COILS / 8) /** * Bitfield consisting of 2000 coils/discrete inputs */ -typedef uint8_t nmbs_bitfield[250]; +typedef uint8_t nmbs_bitfield[NMBS_MAX_COIL_BYTES]; /** * Bitfield consisting of 256 values