Commit 45b813f64493832ec01f29727c33f8a33d0c0b81

Authored by Stéphane Raimbault
1 parent 932769d8

New functions to manipulate data and use them in unit-tests

- MODBUS_GET_INT32_FROM_INT16
- MODBUS_GET_INT16_FROM_INT8
- MODBUS_SET_INT16_TO_INT8
- check the trame length before indexing in unit-test-server
src/modbus.h
... ... @@ -178,6 +178,13 @@ int modbus_reply(modbus_t *ctx, const uint8_t *req,
178 178  
179 179 #define MODBUS_GET_HIGH_BYTE(data) ((data >> 8) & 0xFF)
180 180 #define MODBUS_GET_LOW_BYTE(data) (data & 0xFF)
  181 +#define MODBUS_GET_INT32_FROM_INT16(tab_int16, index) ((tab_int16[index] << 16) + tab_int16[index + 1])
  182 +#define MODBUS_GET_INT16_FROM_INT8(tab_int8, index) ((tab_int8[index] << 8) + tab_int8[index + 1])
  183 +#define MODBUS_SET_INT16_TO_INT8(tab_int8, index, value) \
  184 + do { \
  185 + tab_int8[index] = value >> 8; \
  186 + tab_int8[index + 1] = value & 0xFF; \
  187 + } while (0)
181 188  
182 189 void modbus_set_bits_from_byte(uint8_t *dest, int address, const uint8_t value);
183 190 void modbus_set_bits_from_bytes(uint8_t *dest, int address, unsigned int nb_bits,
... ...
tests/unit-test-server.c
... ... @@ -24,9 +24,6 @@
24 24  
25 25 #include "unit-test.h"
26 26  
27   -/* Copied from modbus-private.h */
28   -#define HEADER_LENGTH_TCP 7
29   -
30 27 enum {
31 28 TCP,
32 29 RTU
... ... @@ -110,22 +107,23 @@ int main(int argc, char*argv[])
110 107  
111 108 for (;;) {
112 109 rc = modbus_receive(ctx, -1, query);
113   - if (rc > 0) {
114   - if (((query[header_length + 3] << 8) +
115   - query[header_length + 4])
  110 + if (rc == -1) {
  111 + /* Connection closed by the client or error */
  112 + break;
  113 + }
  114 +
  115 + /* Read holding registers */
  116 + if (query[header_length] == 0x03) {
  117 + if (MODBUS_GET_INT16_FROM_INT8(query, header_length + 3)
116 118 == UT_REGISTERS_NB_POINTS_SPECIAL) {
117   - /* Change the number of values (offset
118   - TCP = 6) */
119   - query[header_length + 3] = 0;
120   - query[header_length + 4] = UT_REGISTERS_NB_POINTS;
  119 + printf("Set an incorrect number of values\n");
  120 + MODBUS_SET_INT16_TO_INT8(query, header_length + 3,
  121 + UT_REGISTERS_NB_POINTS);
121 122 }
  123 + }
122 124  
123   - rc = modbus_reply(ctx, query, rc, mb_mapping);
124   - if (rc == -1) {
125   - return -1;
126   - }
127   - } else {
128   - /* Connection closed by the client or error */
  125 + rc = modbus_reply(ctx, query, rc, mb_mapping);
  126 + if (rc == -1) {
129 127 break;
130 128 }
131 129 }
... ...