libmodbus4r 0.3.0 → 2.0.0

Sign up to get free protection for your applications and to get access to all the features.
@@ -1,21 +0,0 @@
1
- begin
2
- require 'rubygems'
3
- rescue
4
- end
5
-
6
- require 'modbus4r'
7
-
8
- sl = ModBus::TCPSlave.new('127.0.0.1', #ip-address
9
- 1502, #port
10
- 1) #slave id
11
-
12
- sl.coil_status = [false, false, false, false, false]
13
- sl.input_status = [false, false, false, false, false]
14
- sl.holding_registers = [0, 0, 0, 0, 0, 0, 0, 0]
15
- sl.input_registers = [0, 0, 0, 0, 0, 0, 0, 0]
16
-
17
- sl.start
18
-
19
- sl.join
20
-
21
- sl.stop
data/ext/errors.c DELETED
@@ -1,81 +0,0 @@
1
- /* libmodbus4r - binding use libmodbus for Ruby.
2
- Copyright (C) 2009 Timin Aleksey
3
-
4
- This program is free software: you can redistribute it and/or modify
5
- it under the terms of the GNU General Public License as published by
6
- the Free Software Foundation, either version 3 of the License, or
7
- (at your option) any later version.
8
-
9
- This program is distributed in the hope that it will be useful,
10
- but WITHOUT ANY WARRANTY; without even the implied warranty of
11
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12
- GNU General Public License for more details. */
13
-
14
- #include "modbus4r.h"
15
-
16
- VALUE mErrors, eModBusError, eIllegalFunction,
17
- eIllegalDataAddress, eIllegalDataValue,
18
- eSlaveDeviceFailure, eAcknowledge,
19
- eSlaveDeviceBusy, eNegativeAcknowledge,
20
- eMemoryParityError, eGatewayProblemPath, eGatewayProblemTarget;
21
-
22
- void mb_raise_error(int exception)
23
- {
24
- switch (exception) {
25
- case ILLEGAL_FUNCTION:
26
- rb_raise(eIllegalFunction, "Illegal function code (%i)", ILLEGAL_FUNCTION);
27
- break;
28
- case ILLEGAL_DATA_ADDRESS:
29
- rb_raise(eIllegalDataAddress, "Illegal data address (%i)", ILLEGAL_DATA_ADDRESS);
30
- break;
31
- case ILLEGAL_DATA_VALUE:
32
- rb_raise(eIllegalDataValue, "Illegal data value (%i)", ILLEGAL_DATA_VALUE);
33
- break;
34
- case SLAVE_DEVICE_FAILURE:
35
- rb_raise(eSlaveDeviceFailure, "Slave device or server failure (%i)", SLAVE_DEVICE_FAILURE);
36
- break;
37
- case ACKNOWLEDGE:
38
- rb_raise(eAcknowledge, "Acknowledge (%i)", ACKNOWLEDGE);
39
- break;
40
- case SLAVE_DEVICE_BUSY:
41
- rb_raise(eSlaveDeviceBusy, "Slave device or server busy (%i)", SLAVE_DEVICE_BUSY);
42
- break;
43
- case NEGATIVE_ACKNOWLEDGE:
44
- rb_raise(eNegativeAcknowledge, "Negative acknowledge (%i)", NEGATIVE_ACKNOWLEDGE);
45
- break;
46
- case MEMORY_PARITY_ERROR:
47
- rb_raise(eMemoryParityError, "Memory parity error (%i)", MEMORY_PARITY_ERROR);
48
- break;
49
- case GATEWAY_PROBLEM_PATH:
50
- rb_raise(eGatewayProblemPath, "Gateway problem path (%i)", GATEWAY_PROBLEM_PATH);
51
- break;
52
- case GATEWAY_PROBLEM_TARGET:
53
- rb_raise(eGatewayProblemTarget, "Gateway problem target (%i)", GATEWAY_PROBLEM_TARGET);
54
- break;
55
- case INVALID_DATA:
56
- rb_raise(eModBusError, "Invalid data (%i)", INVALID_DATA);
57
- break;
58
- case INVALID_CRC:
59
- rb_raise(eModBusError, "Invalid CRC (%i)", INVALID_CRC);
60
- break;
61
- case INVALID_EXCEPTION_CODE:
62
- rb_raise(eModBusError, "Invalid exception code (%i)", INVALID_EXCEPTION_CODE);
63
- break;
64
- case SELECT_TIMEOUT:
65
- rb_raise(eModBusError, "Select timeout (%i)", SELECT_TIMEOUT);
66
- break;
67
- case SELECT_FAILURE:
68
- rb_raise(eModBusError, "Select failure (%i)", SELECT_FAILURE);
69
- break;
70
- case SOCKET_FAILURE:
71
- rb_raise(eModBusError, "Socket failure (%i)", SOCKET_FAILURE);
72
- break;
73
- case CONNECTION_CLOSED:
74
- rb_raise(eModBusError, "Connection closed (%i)", CONNECTION_CLOSED);
75
- break;
76
- default:
77
- rb_raise(eModBusError, "Unknow exception with code %i", exception);
78
- }
79
- }
80
-
81
-
data/ext/errors.h DELETED
@@ -1,24 +0,0 @@
1
- /* libmodbus4r - binding use libmodbus for Ruby.
2
- Copyright (C) 2009 Timin Aleksey
3
-
4
- This program is free software: you can redistribute it and/or modify
5
- it under the terms of the GNU General Public License as published by
6
- the Free Software Foundation, either version 3 of the License, or
7
- (at your option) any later version.
8
-
9
- This program is distributed in the hope that it will be useful,
10
- but WITHOUT ANY WARRANTY; without even the implied warranty of
11
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12
- GNU General Public License for more details. */
13
-
14
- #ifndef ERRORS_H
15
- #define ERRORS_H
16
-
17
- extern VALUE mErrors, eModBusError, eIllegalFunction,
18
- eIllegalDataAddress, eIllegalDataValue,
19
- eSlaveDeviceFailure, eAcknowledge,
20
- eSlaveDeviceBusy, eNegativeAcknowledge,
21
- eMemoryParityError, eGatewayProblemPath, eGatewayProblemTarget;
22
-
23
- extern void mb_raise_error(int exception);
24
- #endif
data/ext/master.c DELETED
@@ -1,215 +0,0 @@
1
- /* libmodbus4r - binding use libmodbus for Ruby.
2
- Copyright (C) 2009 Timin Aleksey
3
-
4
- This program is free software: you can redistribute it and/or modify
5
- it under the terms of the GNU General Public License as published by
6
- the Free Software Foundation, either version 3 of the License, or
7
- (at your option) any later version.
8
-
9
- This program is distributed in the hope that it will be useful,
10
- but WITHOUT ANY WARRANTY; without even the implied warranty of
11
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12
- GNU General Public License for more details. */
13
-
14
- #include <unistd.h>
15
- #include "modbus4r.h"
16
- #include "errors.h"
17
-
18
- void mb_mstr_free(modbus_param_t *mb_param )
19
- {
20
- modbus_close(mb_param);
21
- free(mb_param);
22
- }
23
-
24
-
25
- VALUE mb_mstr_is_closed(VALUE self)
26
- {
27
- modbus_param_t *mb_param;
28
- Data_Get_Struct(self, modbus_param_t, mb_param);
29
-
30
- if (read(mb_param->fd, NULL, 0) || mb_param->fd == 0) {
31
- return Qtrue;
32
- }
33
- return Qfalse;
34
- }
35
-
36
- VALUE mb_mstr_connect(VALUE self)
37
- {
38
- modbus_param_t *mb_param;
39
- Data_Get_Struct(self, modbus_param_t, mb_param);
40
-
41
- if (modbus_connect(mb_param)) {
42
- rb_raise(eModBusError, "Connection refused");
43
- }
44
- return self;
45
- }
46
-
47
- VALUE mb_mstr_close(VALUE self)
48
- {
49
- modbus_param_t *mb_param;
50
- Data_Get_Struct(self, modbus_param_t, mb_param);
51
-
52
- modbus_close(mb_param);
53
-
54
- return self;
55
- }
56
-
57
- VALUE mb_mstr_read_coil(VALUE self, VALUE start_addr, VALUE nb,
58
- int (*func)(modbus_param_t*, int, int, uint8_t*))
59
- {
60
- modbus_param_t *mb_param;
61
- Data_Get_Struct(self, modbus_param_t, mb_param);
62
-
63
- start_addr = rb_funcall(start_addr, rb_intern("to_i"), 0);
64
- nb = rb_funcall(nb, rb_intern("to_i"), 0);
65
-
66
- uint8_t dest[FIX2INT(nb)];
67
- int status = (*func)(mb_param, FIX2INT(start_addr), FIX2INT(nb), dest);
68
-
69
- if (status < 0) {
70
- mb_raise_error(status);
71
- }
72
-
73
- int i;
74
- VALUE ret = rb_ary_new();
75
- for (i = 0; i < FIX2INT(nb); i++) {
76
- dest[i] == 1 ? rb_ary_push(ret, Qtrue) : rb_ary_push(ret, Qfalse);
77
- }
78
-
79
- return ret;
80
- }
81
-
82
- VALUE mb_mstr_read_coil_status(VALUE self, VALUE start_addr, VALUE nb)
83
- {
84
- return mb_mstr_read_coil(self, start_addr, nb, read_coil_status);
85
- }
86
-
87
- VALUE mb_mstr_read_input_status(VALUE self, VALUE start_addr, VALUE nb)
88
- {
89
- return mb_mstr_read_coil(self, start_addr, nb, read_input_status);
90
- }
91
-
92
- VALUE mb_mstr_read_registers(VALUE self, VALUE start_addr, VALUE nb,
93
- int (*func)(modbus_param_t*, int, int, uint16_t*))
94
- {
95
- modbus_param_t *mb_param;
96
- Data_Get_Struct(self, modbus_param_t, mb_param);
97
-
98
- start_addr = rb_funcall(start_addr, rb_intern("to_i"), 0);
99
- nb = rb_funcall(nb, rb_intern("to_i"), 0);
100
-
101
- uint16_t dest[FIX2INT(nb)];
102
- int status = (*func)(mb_param, FIX2INT(start_addr), FIX2INT(nb), dest);
103
-
104
- if (status < 0) {
105
- mb_raise_error(status);
106
- }
107
-
108
- int i;
109
- VALUE ret = rb_ary_new();
110
- for (i = 0; i < FIX2INT(nb); i++) {
111
- rb_ary_push(ret, INT2FIX(dest[i]));
112
- }
113
-
114
-
115
- return ret;
116
- }
117
-
118
- VALUE mb_mstr_read_holding_registers(VALUE self, VALUE start_addr, VALUE nb)
119
- {
120
- return mb_mstr_read_registers(self, start_addr, nb,
121
- read_holding_registers);
122
- }
123
-
124
- VALUE mb_mstr_read_input_registers(VALUE self, VALUE start_addr, VALUE nb)
125
- {
126
- return mb_mstr_read_registers(self, start_addr, nb,
127
- read_input_registers);
128
- }
129
-
130
- VALUE mb_mstr_force_single_coil(VALUE self, VALUE coil_addr, VALUE state)
131
- {
132
- modbus_param_t *mb_param;
133
- Data_Get_Struct(self, modbus_param_t, mb_param);
134
-
135
- coil_addr = rb_funcall(coil_addr, rb_intern("to_i"), 0);
136
-
137
- int status = force_single_coil(mb_param, FIX2INT(coil_addr), (state == Qfalse ? 0 : 1));
138
-
139
- if (status < 0) {
140
- mb_raise_error(status);
141
- }
142
-
143
- return self;
144
- }
145
-
146
-
147
- VALUE mb_mstr_preset_single_register(VALUE self, VALUE reg_addr, VALUE value)
148
- {
149
- modbus_param_t *mb_param;
150
- Data_Get_Struct(self, modbus_param_t, mb_param);
151
-
152
- reg_addr = rb_funcall(reg_addr, rb_intern("to_i"), 0);
153
- value = rb_funcall(value, rb_intern("to_i"), 0);
154
-
155
- int status = preset_single_register(mb_param, FIX2INT(reg_addr), FIX2INT(value));
156
-
157
- if (status < 0) {
158
- mb_raise_error(status);
159
- }
160
-
161
- return self;
162
- }
163
-
164
- VALUE mb_mstr_force_multiple_coils(VALUE self, VALUE start_addr, VALUE data)
165
- {
166
- modbus_param_t *mb_param;
167
- Data_Get_Struct(self, modbus_param_t, mb_param);
168
-
169
- start_addr = rb_funcall(start_addr, rb_intern("to_i"), 0);
170
- data = rb_funcall(data, rb_intern("to_a"), 0);
171
-
172
- uint8_t buf[RARRAY_LEN(data)];
173
- VALUE *ary = RARRAY_PTR(data);
174
- int i;
175
-
176
- for (i = 0; i < RARRAY_LEN(data); i++) {
177
- buf[i] = (*ary == Qfalse ? 0 : 1);
178
- ary++;
179
- }
180
-
181
- int status = force_multiple_coils(mb_param, FIX2INT(start_addr), RARRAY_LEN(data), buf);
182
-
183
- if (status < 0) {
184
- mb_raise_error(status);
185
- }
186
-
187
- return self;
188
- }
189
-
190
- VALUE mb_mstr_preset_multiple_registers(VALUE self, VALUE start_addr, VALUE data)
191
- {
192
- modbus_param_t *mb_param;
193
- Data_Get_Struct(self, modbus_param_t, mb_param);
194
-
195
- start_addr = rb_funcall(start_addr, rb_intern("to_i"), 0);
196
- data = rb_funcall(data, rb_intern("to_a"), 0);
197
-
198
- uint16_t buf[RARRAY_LEN(data)];
199
- VALUE *ary = RARRAY_PTR(data);
200
- int i;
201
-
202
- for (i = 0; i < RARRAY_LEN(data); i++) {
203
- *ary = rb_funcall(*ary, rb_intern("to_i"), 0);
204
- buf[i] = FIX2INT(*ary);
205
- ary++;
206
- }
207
-
208
- int status = preset_multiple_registers(mb_param, FIX2INT(start_addr), RARRAY_LEN(data), buf);
209
-
210
- if (status < 0) {
211
- mb_raise_error(status);
212
- }
213
-
214
- return self;
215
- }
data/ext/master.h DELETED
@@ -1,37 +0,0 @@
1
- /* libmodbus4r - binding use libmodbus for Ruby.
2
- Copyright (C) 2009 Timin Aleksey
3
-
4
- This program is free software: you can redistribute it and/or modify
5
- it under the terms of the GNU General Public License as published by
6
- the Free Software Foundation, either version 3 of the License, or
7
- (at your option) any later version.
8
-
9
- This program is distributed in the hope that it will be useful,
10
- but WITHOUT ANY WARRANTY; without even the implied warranty of
11
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12
- GNU General Public License for more details. */
13
-
14
- #ifndef MASTER_H
15
- #define MASTER_H
16
-
17
- extern VALUE mb_mstr_is_closed(VALUE self);
18
- extern VALUE mb_mstr_connect(VALUE self);
19
- extern VALUE mb_mstr_close(VALUE self);
20
- extern VALUE mb_mstr_read_coil_status(VALUE self,
21
- VALUE start_addr, VALUE nb);
22
- extern VALUE mb_mstr_read_input_status(VALUE self,
23
- VALUE start_addr, VALUE nb);
24
- extern VALUE mb_mstr_read_holding_registers(VALUE self,
25
- VALUE start_addr, VALUE nb);
26
- extern VALUE mb_mstr_read_input_registers(VALUE self,
27
- VALUE start_addr, VALUE nb);
28
- extern VALUE mb_mstr_force_single_coil(VALUE self,
29
- VALUE coil_addr, VALUE state);
30
- extern VALUE mb_mstr_preset_single_register(VALUE self,
31
- VALUE reg_addr, VALUE value);
32
- extern VALUE mb_mstr_force_multiple_coils(VALUE self,
33
- VALUE start_addr, VALUE data);
34
- extern VALUE mb_mstr_preset_multiple_registers(VALUE self,
35
- VALUE start_addr, VALUE data);
36
- extern void mb_mstr_free(modbus_param_t *mb_param );
37
- #endif
data/ext/modbus.c DELETED
@@ -1,1959 +0,0 @@
1
- /*
2
- * Copyright © 2001-2008 Stéphane Raimbault <stephane.raimbault@gmail.com>
3
- *
4
- * This program is free software: you can redistribute it and/or modify
5
- * it under the terms of the GNU Lesser Public License as published by
6
- * the Free Software Foundation; either version 3 of the License, or
7
- * (at your option) any later version.
8
- *
9
- * This program is distributed in the hope that it will be useful,
10
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
11
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12
- * GNU Lesser Public License for more details.
13
- *
14
- * You should have received a copy of the GNU Lesser Public License
15
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
16
- */
17
-
18
- /*
19
- The library is designed to send and receive data from a device that
20
- communicate via the Modbus protocol.
21
-
22
- The function names used are inspired by the Modicon Modbus Protocol
23
- Reference Guide which can be obtained from Schneider at
24
- www.schneiderautomation.com.
25
-
26
- Documentation:
27
- http://www.easysw.com/~mike/serial/serial.html
28
- http://copyleft.free.fr/wordpress/index.php/libmodbus/
29
- */
30
-
31
- #include <stdio.h>
32
- #include <string.h>
33
- #include <stdlib.h>
34
- #include <stdint.h>
35
- #include <termios.h>
36
- #include <sys/time.h>
37
- #include <unistd.h>
38
- #include <errno.h>
39
- #include <limits.h>
40
- #include <fcntl.h>
41
-
42
- /* TCP */
43
- #include <sys/types.h>
44
- #include <sys/socket.h>
45
- #include <sys/ioctl.h>
46
- #include <netinet/in.h>
47
- #include <netinet/ip.h>
48
- #include <netinet/tcp.h>
49
- #include <arpa/inet.h>
50
-
51
- //#include "config.h"
52
- #include "modbus.h"
53
-
54
- #define UNKNOWN_ERROR_MSG "Not defined in modbus specification"
55
-
56
- /* This structure reduces the number of params in functions and so
57
- * optimizes the speed of execution (~ 37%). */
58
- typedef struct {
59
- int slave;
60
- int function;
61
- int t_id;
62
- } sft_t;
63
-
64
- static const uint8_t NB_TAB_ERROR_MSG = 12;
65
- static const char *TAB_ERROR_MSG[] = {
66
- /* 0x00 */ UNKNOWN_ERROR_MSG,
67
- /* 0x01 */ "Illegal function code",
68
- /* 0x02 */ "Illegal data address",
69
- /* 0x03 */ "Illegal data value",
70
- /* 0x04 */ "Slave device or server failure",
71
- /* 0x05 */ "Acknowledge",
72
- /* 0x06 */ "Slave device or server busy",
73
- /* 0x07 */ "Negative acknowledge",
74
- /* 0x08 */ "Memory parity error",
75
- /* 0x09 */ UNKNOWN_ERROR_MSG,
76
- /* 0x0A */ "Gateway path unavailable",
77
- /* 0x0B */ "Target device failed to respond"
78
- };
79
-
80
- /* Table of CRC values for high-order byte */
81
- static uint8_t table_crc_hi[] = {
82
- 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0,
83
- 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41,
84
- 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0,
85
- 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40,
86
- 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1,
87
- 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41,
88
- 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1,
89
- 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41,
90
- 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0,
91
- 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40,
92
- 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1,
93
- 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40,
94
- 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0,
95
- 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40,
96
- 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0,
97
- 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40,
98
- 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0,
99
- 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41,
100
- 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0,
101
- 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41,
102
- 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0,
103
- 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40,
104
- 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1,
105
- 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41,
106
- 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0,
107
- 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40
108
- };
109
-
110
- /* Table of CRC values for low-order byte */
111
- static uint8_t table_crc_lo[] = {
112
- 0x00, 0xC0, 0xC1, 0x01, 0xC3, 0x03, 0x02, 0xC2, 0xC6, 0x06,
113
- 0x07, 0xC7, 0x05, 0xC5, 0xC4, 0x04, 0xCC, 0x0C, 0x0D, 0xCD,
114
- 0x0F, 0xCF, 0xCE, 0x0E, 0x0A, 0xCA, 0xCB, 0x0B, 0xC9, 0x09,
115
- 0x08, 0xC8, 0xD8, 0x18, 0x19, 0xD9, 0x1B, 0xDB, 0xDA, 0x1A,
116
- 0x1E, 0xDE, 0xDF, 0x1F, 0xDD, 0x1D, 0x1C, 0xDC, 0x14, 0xD4,
117
- 0xD5, 0x15, 0xD7, 0x17, 0x16, 0xD6, 0xD2, 0x12, 0x13, 0xD3,
118
- 0x11, 0xD1, 0xD0, 0x10, 0xF0, 0x30, 0x31, 0xF1, 0x33, 0xF3,
119
- 0xF2, 0x32, 0x36, 0xF6, 0xF7, 0x37, 0xF5, 0x35, 0x34, 0xF4,
120
- 0x3C, 0xFC, 0xFD, 0x3D, 0xFF, 0x3F, 0x3E, 0xFE, 0xFA, 0x3A,
121
- 0x3B, 0xFB, 0x39, 0xF9, 0xF8, 0x38, 0x28, 0xE8, 0xE9, 0x29,
122
- 0xEB, 0x2B, 0x2A, 0xEA, 0xEE, 0x2E, 0x2F, 0xEF, 0x2D, 0xED,
123
- 0xEC, 0x2C, 0xE4, 0x24, 0x25, 0xE5, 0x27, 0xE7, 0xE6, 0x26,
124
- 0x22, 0xE2, 0xE3, 0x23, 0xE1, 0x21, 0x20, 0xE0, 0xA0, 0x60,
125
- 0x61, 0xA1, 0x63, 0xA3, 0xA2, 0x62, 0x66, 0xA6, 0xA7, 0x67,
126
- 0xA5, 0x65, 0x64, 0xA4, 0x6C, 0xAC, 0xAD, 0x6D, 0xAF, 0x6F,
127
- 0x6E, 0xAE, 0xAA, 0x6A, 0x6B, 0xAB, 0x69, 0xA9, 0xA8, 0x68,
128
- 0x78, 0xB8, 0xB9, 0x79, 0xBB, 0x7B, 0x7A, 0xBA, 0xBE, 0x7E,
129
- 0x7F, 0xBF, 0x7D, 0xBD, 0xBC, 0x7C, 0xB4, 0x74, 0x75, 0xB5,
130
- 0x77, 0xB7, 0xB6, 0x76, 0x72, 0xB2, 0xB3, 0x73, 0xB1, 0x71,
131
- 0x70, 0xB0, 0x50, 0x90, 0x91, 0x51, 0x93, 0x53, 0x52, 0x92,
132
- 0x96, 0x56, 0x57, 0x97, 0x55, 0x95, 0x94, 0x54, 0x9C, 0x5C,
133
- 0x5D, 0x9D, 0x5F, 0x9F, 0x9E, 0x5E, 0x5A, 0x9A, 0x9B, 0x5B,
134
- 0x99, 0x59, 0x58, 0x98, 0x88, 0x48, 0x49, 0x89, 0x4B, 0x8B,
135
- 0x8A, 0x4A, 0x4E, 0x8E, 0x8F, 0x4F, 0x8D, 0x4D, 0x4C, 0x8C,
136
- 0x44, 0x84, 0x85, 0x45, 0x87, 0x47, 0x46, 0x86, 0x82, 0x42,
137
- 0x43, 0x83, 0x41, 0x81, 0x80, 0x40
138
- };
139
-
140
- static const int TAB_HEADER_LENGTH[2] = {
141
- HEADER_LENGTH_RTU,
142
- HEADER_LENGTH_TCP
143
- };
144
-
145
- static const int TAB_CHECKSUM_LENGTH[2] = {
146
- CHECKSUM_LENGTH_RTU,
147
- CHECKSUM_LENGTH_TCP
148
- };
149
-
150
- static const int TAB_MAX_ADU_LENGTH[2] = {
151
- MAX_ADU_LENGTH_RTU,
152
- MAX_ADU_LENGTH_TCP,
153
- };
154
-
155
- /* Treats errors and flush or close connection if necessary */
156
- static void error_treat(modbus_param_t *mb_param, int code, const char *string)
157
- {
158
- printf("\nERROR %s (%0X)\n", string, -code);
159
-
160
- if (mb_param->error_handling == FLUSH_OR_CONNECT_ON_ERROR) {
161
- switch (code) {
162
- case INVALID_DATA:
163
- case INVALID_CRC:
164
- case INVALID_EXCEPTION_CODE:
165
- modbus_flush(mb_param);
166
- break;
167
- case SELECT_FAILURE:
168
- case SOCKET_FAILURE:
169
- case CONNECTION_CLOSED:
170
- modbus_close(mb_param);
171
- modbus_connect(mb_param);
172
- break;
173
- default:
174
- /* NOP */
175
- break;
176
- }
177
- }
178
- }
179
-
180
- void modbus_flush(modbus_param_t *mb_param)
181
- {
182
- if (mb_param->type_com == RTU) {
183
- tcflush(mb_param->fd, TCIOFLUSH);
184
- } else {
185
- int ret;
186
- do {
187
- /* Extract the garbage from the socket */
188
- char devnull[MAX_ADU_LENGTH_TCP];
189
- #if (!HAVE_DECL___CYGWIN__)
190
- ret = recv(mb_param->fd, devnull, MAX_ADU_LENGTH_TCP, MSG_DONTWAIT);
191
- #else
192
- /* On Cygwin, it's a bit more complicated to not wait */
193
- fd_set rfds;
194
- struct timeval tv;
195
-
196
- tv.tv_sec = 0;
197
- tv.tv_usec = 0;
198
- FD_ZERO(&rfds);
199
- FD_SET(mb_param->fd, &rfds);
200
- ret = select(mb_param->fd+1, &rfds, NULL, NULL, &tv);
201
- if (ret > 0) {
202
- ret = recv(mb_param->fd, devnull, MAX_ADU_LENGTH_TCP, 0);
203
- } else if (ret == -1) {
204
- /* error_treat() doesn't call modbus_flush() in
205
- this case (avoid infinite loop) */
206
- error_treat(mb_param, SELECT_FAILURE, "Select failure");
207
- }
208
- #endif
209
- if (mb_param->debug && ret > 0) {
210
- printf("%d bytes flushed\n", ret);
211
- }
212
- } while (ret > 0);
213
- }
214
- }
215
-
216
- /* Computes the length of the expected response */
217
- static unsigned int compute_response_length(modbus_param_t *mb_param,
218
- uint8_t *query)
219
- {
220
- int length;
221
- int offset;
222
-
223
- offset = TAB_HEADER_LENGTH[mb_param->type_com];
224
-
225
- switch (query[offset]) {
226
- case FC_READ_COIL_STATUS:
227
- case FC_READ_INPUT_STATUS: {
228
- /* Header + nb values (code from force_multiple_coils) */
229
- int nb = (query[offset + 3] << 8) | query[offset + 4];
230
- length = 2 + (nb / 8) + ((nb % 8) ? 1 : 0);
231
- }
232
- break;
233
- case FC_READ_HOLDING_REGISTERS:
234
- case FC_READ_INPUT_REGISTERS:
235
- /* Header + 2 * nb values */
236
- length = 2 + 2 * (query[offset + 3] << 8 |
237
- query[offset + 4]);
238
- break;
239
- case FC_READ_EXCEPTION_STATUS:
240
- length = 3;
241
- break;
242
- default:
243
- length = 5;
244
- }
245
-
246
- return length + offset + TAB_CHECKSUM_LENGTH[mb_param->type_com];
247
- }
248
-
249
- /* Builds a RTU query header */
250
- static int build_query_basis_rtu(int slave, int function,
251
- int start_addr, int nb,
252
- uint8_t *query)
253
- {
254
- query[0] = slave;
255
- query[1] = function;
256
- query[2] = start_addr >> 8;
257
- query[3] = start_addr & 0x00ff;
258
- query[4] = nb >> 8;
259
- query[5] = nb & 0x00ff;
260
-
261
- return PRESET_QUERY_LENGTH_RTU;
262
- }
263
-
264
- /* Builds a TCP query header */
265
- static int build_query_basis_tcp(int slave, int function,
266
- int start_addr, int nb,
267
- uint8_t *query)
268
- {
269
-
270
- /* Extract from MODBUS Messaging on TCP/IP Implementation
271
- Guide V1.0b (page 23/46):
272
- The transaction identifier is used to associate the future
273
- response with the request. So, at a time, on a TCP
274
- connection, this identifier must be unique.
275
- */
276
- static uint16_t t_id = 0;
277
-
278
- /* Transaction ID */
279
- if (t_id < UINT16_MAX)
280
- t_id++;
281
- else
282
- t_id = 0;
283
- query[0] = t_id >> 8;
284
- query[1] = t_id & 0x00ff;
285
-
286
- /* Protocol Modbus */
287
- query[2] = 0;
288
- query[3] = 0;
289
-
290
- /* Length will be defined later by set_query_length_tcp at offsets 4
291
- * and 5 */
292
-
293
- query[6] = slave;
294
- query[7] = function;
295
- query[8] = start_addr >> 8;
296
- query[9] = start_addr & 0x00ff;
297
- query[10] = nb >> 8;
298
- query[11] = nb & 0x00ff;
299
-
300
- return PRESET_QUERY_LENGTH_TCP;
301
- }
302
-
303
- static int build_query_basis(modbus_param_t *mb_param,
304
- int function, int start_addr,
305
- int nb, uint8_t *query)
306
- {
307
- if (mb_param->type_com == RTU)
308
- return build_query_basis_rtu(mb_param->slave, function,
309
- start_addr, nb, query);
310
- else
311
- return build_query_basis_tcp(mb_param->slave, function,
312
- start_addr, nb, query);
313
- }
314
-
315
- /* Builds a RTU response header */
316
- static int build_response_basis_rtu(sft_t *sft, uint8_t *response)
317
- {
318
- response[0] = sft->slave;
319
- response[1] = sft->function;
320
-
321
- return PRESET_RESPONSE_LENGTH_RTU;
322
- }
323
-
324
- /* Builds a TCP response header */
325
- static int build_response_basis_tcp(sft_t *sft, uint8_t *response)
326
- {
327
- /* Extract from MODBUS Messaging on TCP/IP Implementation
328
- Guide V1.0b (page 23/46):
329
- The transaction identifier is used to associate the future
330
- response with the request. */
331
- response[0] = sft->t_id >> 8;
332
- response[1] = sft->t_id & 0x00ff;
333
-
334
- /* Protocol Modbus */
335
- response[2] = 0;
336
- response[3] = 0;
337
-
338
- /* Length to fix later with set_message_length_tcp (4 and 5) */
339
-
340
- response[6] = sft->slave;
341
- response[7] = sft->function;
342
-
343
- return PRESET_RESPONSE_LENGTH_TCP;
344
- }
345
-
346
- static int build_response_basis(modbus_param_t *mb_param, sft_t *sft,
347
- uint8_t *response)
348
- {
349
- if (mb_param->type_com == RTU)
350
- return build_response_basis_rtu(sft, response);
351
- else
352
- return build_response_basis_tcp(sft, response);
353
- }
354
-
355
- /* Sets the length of TCP message in the message (query and response) */
356
- void set_message_length_tcp(uint8_t *msg, int msg_length)
357
- {
358
- /* Substract the header length to the message length */
359
- int mbap_length = msg_length - 6;
360
-
361
- msg[4] = mbap_length >> 8;
362
- msg[5] = mbap_length & 0x00FF;
363
- }
364
-
365
- /* Fast CRC */
366
- static uint16_t crc16(uint8_t *buffer, uint16_t buffer_length)
367
- {
368
- uint8_t crc_hi = 0xFF; /* high CRC byte initialized */
369
- uint8_t crc_lo = 0xFF; /* low CRC byte initialized */
370
- unsigned int i; /* will index into CRC lookup */
371
-
372
- /* pass through message buffer */
373
- while (buffer_length--) {
374
- i = crc_hi ^ *buffer++; /* calculate the CRC */
375
- crc_hi = crc_lo ^ table_crc_hi[i];
376
- crc_lo = table_crc_lo[i];
377
- }
378
-
379
- return (crc_hi << 8 | crc_lo);
380
- }
381
-
382
- /* If CRC is correct returns 0 else returns INVALID_CRC */
383
- static int check_crc16(modbus_param_t *mb_param,
384
- uint8_t *msg,
385
- const int msg_length)
386
- {
387
- int ret;
388
- uint16_t crc_calc;
389
- uint16_t crc_received;
390
-
391
- crc_calc = crc16(msg, msg_length - 2);
392
- crc_received = (msg[msg_length - 2] << 8) | msg[msg_length - 1];
393
-
394
- /* Check CRC of msg */
395
- if (crc_calc == crc_received) {
396
- ret = 0;
397
- } else {
398
- char s_error[64];
399
- sprintf(s_error,
400
- "invalid crc received %0X - crc_calc %0X",
401
- crc_received, crc_calc);
402
- ret = INVALID_CRC;
403
- error_treat(mb_param, ret, s_error);
404
- }
405
-
406
- return ret;
407
- }
408
-
409
- /* Sends a query/response over a serial or a TCP communication */
410
- static int modbus_send(modbus_param_t *mb_param, uint8_t *query,
411
- int query_length)
412
- {
413
- int ret;
414
- uint16_t s_crc;
415
- int i;
416
-
417
- if (mb_param->type_com == RTU) {
418
- s_crc = crc16(query, query_length);
419
- query[query_length++] = s_crc >> 8;
420
- query[query_length++] = s_crc & 0x00FF;
421
- } else {
422
- set_message_length_tcp(query, query_length);
423
- }
424
-
425
- if (mb_param->debug) {
426
- for (i = 0; i < query_length; i++)
427
- printf("[%.2X]", query[i]);
428
- printf("\n");
429
- }
430
-
431
- if (mb_param->type_com == RTU)
432
- ret = write(mb_param->fd, query, query_length);
433
- else
434
- ret = send(mb_param->fd, query, query_length, 0);
435
-
436
- /* Return the number of bytes written (0 to n)
437
- or SOCKET_FAILURE on error */
438
- if ((ret == -1) || (ret != query_length)) {
439
- ret = SOCKET_FAILURE;
440
- error_treat(mb_param, ret, "Write socket failure");
441
- }
442
-
443
- return ret;
444
- }
445
-
446
- /* Computes the length of the header following the function code */
447
- static uint8_t compute_query_length_header(int function)
448
- {
449
- int length;
450
-
451
- if (function <= FC_FORCE_SINGLE_COIL ||
452
- function == FC_PRESET_SINGLE_REGISTER)
453
- /* Read and single write */
454
- length = 4;
455
- else if (function == FC_FORCE_MULTIPLE_COILS ||
456
- function == FC_PRESET_MULTIPLE_REGISTERS)
457
- /* Multiple write */
458
- length = 5;
459
- else
460
- length = 0;
461
-
462
- return length;
463
- }
464
-
465
- /* Computes the length of the data to write in the query */
466
- static int compute_query_length_data(modbus_param_t *mb_param, uint8_t *msg)
467
- {
468
- int function = msg[TAB_HEADER_LENGTH[mb_param->type_com]];
469
- int length;
470
-
471
- if (function == FC_FORCE_MULTIPLE_COILS ||
472
- function == FC_PRESET_MULTIPLE_REGISTERS)
473
- length = msg[TAB_HEADER_LENGTH[mb_param->type_com] + 5];
474
- else
475
- length = 0;
476
-
477
- length += TAB_CHECKSUM_LENGTH[mb_param->type_com];
478
-
479
- return length;
480
- }
481
-
482
- #define WAIT_DATA() \
483
- { \
484
- while ((select_ret = select(mb_param->fd+1, &rfds, NULL, NULL, &tv)) == -1) { \
485
- if (errno == EINTR) { \
486
- printf("A non blocked signal was caught\n"); \
487
- /* Necessary after an error */ \
488
- FD_ZERO(&rfds); \
489
- FD_SET(mb_param->fd, &rfds); \
490
- } else { \
491
- error_treat(mb_param, SELECT_FAILURE, "Select failure"); \
492
- return SELECT_FAILURE; \
493
- } \
494
- } \
495
- \
496
- if (select_ret == 0) { \
497
- /* Call to error_treat is done later to manage exceptions */ \
498
- return SELECT_TIMEOUT; \
499
- } \
500
- }
501
-
502
- /* Waits a reply from a modbus slave or a query from a modbus master.
503
- This function blocks for timeout seconds if there is no reply.
504
-
505
- In
506
- - msg_length_computed must be set to MSG_LENGTH_UNDEFINED if undefined
507
-
508
- Out
509
- - msg is an array of uint8_t to receive the message
510
- - p_msg_length, the variable is assigned to the number of
511
- characters received. This value won't be greater than
512
- msg_length_computed.
513
-
514
- Returns 0 in success or a negative value if an error occured.
515
- */
516
- static int receive_msg(modbus_param_t *mb_param,
517
- int msg_length_computed,
518
- uint8_t *msg, int *p_msg_length)
519
- {
520
- int select_ret;
521
- int read_ret;
522
- fd_set rfds;
523
- struct timeval tv;
524
- int length_to_read;
525
- uint8_t *p_msg;
526
- enum { FUNCTION, BYTE, COMPLETE };
527
- int state;
528
-
529
- if (mb_param->debug) {
530
- if (msg_length_computed == MSG_LENGTH_UNDEFINED)
531
- printf("Waiting for a message...\n");
532
- else
533
- printf("Waiting for a message (%d bytes)...\n",
534
- msg_length_computed);
535
- }
536
-
537
- /* Add a file descriptor to the set */
538
- FD_ZERO(&rfds);
539
- FD_SET(mb_param->fd, &rfds);
540
-
541
- if (msg_length_computed == MSG_LENGTH_UNDEFINED) {
542
- /* Wait for a message */
543
- tv.tv_sec = 60;
544
- tv.tv_usec = 0;
545
-
546
- /* The message length is undefined (query receiving) so
547
- * we need to analyse the message step by step.
548
- * At the first step, we want to reach the function
549
- * code because all packets have that information. */
550
- state = FUNCTION;
551
- msg_length_computed = TAB_HEADER_LENGTH[mb_param->type_com] + 1;
552
- } else {
553
- tv.tv_sec = 0;
554
- tv.tv_usec = TIME_OUT_BEGIN_OF_TRAME;
555
- state = COMPLETE;
556
- }
557
-
558
- length_to_read = msg_length_computed;
559
-
560
- select_ret = 0;
561
- WAIT_DATA();
562
-
563
- /* Initialize the readin the message */
564
- (*p_msg_length) = 0;
565
- p_msg = msg;
566
-
567
- while (select_ret) {
568
- if (mb_param->type_com == RTU)
569
- read_ret = read(mb_param->fd, p_msg, length_to_read);
570
- else
571
- read_ret = recv(mb_param->fd, p_msg, length_to_read, 0);
572
-
573
- if (read_ret == 0) {
574
- return CONNECTION_CLOSED;
575
- } else if (read_ret < 0) {
576
- /* The only negative possible value is -1 */
577
- error_treat(mb_param, SOCKET_FAILURE,
578
- "Read socket failure");
579
- return SOCKET_FAILURE;
580
- }
581
-
582
- /* Sums bytes received */
583
- (*p_msg_length) += read_ret;
584
-
585
- /* Display the hex code of each character received */
586
- if (mb_param->debug) {
587
- int i;
588
- for (i=0; i < read_ret; i++)
589
- printf("<%.2X>", p_msg[i]);
590
- }
591
-
592
- if ((*p_msg_length) < msg_length_computed) {
593
- /* Message incomplete */
594
- length_to_read = msg_length_computed - (*p_msg_length);
595
- } else {
596
- switch (state) {
597
- case FUNCTION:
598
- /* Function code position */
599
- length_to_read = compute_query_length_header(
600
- msg[TAB_HEADER_LENGTH[mb_param->type_com]]);
601
- msg_length_computed += length_to_read;
602
- /* It's useless to check
603
- p_msg_length_computed value in this
604
- case (only defined values are used). */
605
- state = BYTE;
606
- break;
607
- case BYTE:
608
- length_to_read = compute_query_length_data(mb_param, msg);
609
- msg_length_computed += length_to_read;
610
- if (msg_length_computed > TAB_MAX_ADU_LENGTH[mb_param->type_com]) {
611
- error_treat(mb_param, INVALID_DATA, "Too many data");
612
- return INVALID_DATA;
613
- }
614
- state = COMPLETE;
615
- break;
616
- case COMPLETE:
617
- length_to_read = 0;
618
- break;
619
- }
620
- }
621
-
622
- /* Moves the pointer to receive other data */
623
- p_msg = &(p_msg[read_ret]);
624
-
625
- if (length_to_read > 0) {
626
- /* If no character at the buffer wait
627
- TIME_OUT_END_OF_TRAME before to generate an error. */
628
- tv.tv_sec = 0;
629
- tv.tv_usec = TIME_OUT_END_OF_TRAME;
630
-
631
- WAIT_DATA();
632
- } else {
633
- /* All chars are received */
634
- select_ret = FALSE;
635
- }
636
- }
637
-
638
- if (mb_param->debug)
639
- printf("\n");
640
-
641
- if (mb_param->type_com == RTU) {
642
- return check_crc16(mb_param, msg, (*p_msg_length));
643
- } else {
644
- /* OK */
645
- return 0;
646
- }
647
- }
648
-
649
- /* Listens for any query from a modbus master in TCP, requires the socket file
650
- descriptor etablished with the master device in argument or -1 to use the
651
- internal one of modbus_param_t.
652
-
653
- Returns:
654
- - 0 on success, or a negative error number if the request fails
655
- - query, message received
656
- - query_length, length in bytes of the message */
657
- int modbus_slave_receive(modbus_param_t *mb_param, int sockfd,
658
- uint8_t *query, int *query_length)
659
- {
660
- int ret;
661
-
662
- if (sockfd != -1) {
663
- mb_param->fd = sockfd;
664
- }
665
-
666
- /* The length of the query to receive isn't known. */
667
- ret = receive_msg(mb_param, MSG_LENGTH_UNDEFINED, query, query_length);
668
-
669
- return ret;
670
- }
671
-
672
- /* Receives the response and checks values (and checksum in RTU).
673
-
674
- Returns:
675
- - the number of values (bits or word) if success or the response
676
- length if no value is returned
677
- - less than 0 for exception errors
678
-
679
- Note: all functions used to send or receive data with modbus return
680
- these values. */
681
- static int modbus_receive(modbus_param_t *mb_param,
682
- uint8_t *query,
683
- uint8_t *response)
684
- {
685
- int ret;
686
- int response_length;
687
- int response_length_computed;
688
- int offset = TAB_HEADER_LENGTH[mb_param->type_com];
689
-
690
- response_length_computed = compute_response_length(mb_param, query);
691
- ret = receive_msg(mb_param, response_length_computed,
692
- response, &response_length);
693
- if (ret == 0) {
694
- /* GOOD RESPONSE */
695
- int query_nb_value;
696
- int response_nb_value;
697
-
698
- /* The number of values is returned if it's corresponding
699
- * to the query */
700
- switch (response[offset]) {
701
- case FC_READ_COIL_STATUS:
702
- case FC_READ_INPUT_STATUS:
703
- /* Read functions, 8 values in a byte (nb
704
- * of values in the query and byte count in
705
- * the response. */
706
- query_nb_value = (query[offset + 3] << 8) + query[offset + 4];
707
- query_nb_value = (query_nb_value / 8) + ((query_nb_value % 8) ? 1 : 0);
708
- response_nb_value = response[offset + 1];
709
- break;
710
- case FC_READ_HOLDING_REGISTERS:
711
- case FC_READ_INPUT_REGISTERS:
712
- /* Read functions 1 value = 2 bytes */
713
- query_nb_value = (query[offset + 3] << 8) + query[offset + 4];
714
- response_nb_value = (response[offset + 1] / 2);
715
- break;
716
- case FC_FORCE_MULTIPLE_COILS:
717
- case FC_PRESET_MULTIPLE_REGISTERS:
718
- /* N Write functions */
719
- query_nb_value = (query[offset + 3] << 8) + query[offset + 4];
720
- response_nb_value = (response[offset + 3] << 8) | response[offset + 4];
721
- break;
722
- case FC_REPORT_SLAVE_ID:
723
- /* Report slave ID (bytes received) */
724
- query_nb_value = response_nb_value = response_length;
725
- break;
726
- default:
727
- /* 1 Write functions & others */
728
- query_nb_value = response_nb_value = 1;
729
- }
730
-
731
- if (query_nb_value == response_nb_value) {
732
- ret = response_nb_value;
733
- } else {
734
- char *s_error = malloc(64 * sizeof(char));
735
- sprintf(s_error, "Quantity not corresponding to the query (%d != %d)",
736
- response_nb_value, query_nb_value);
737
- ret = INVALID_DATA;
738
- error_treat(mb_param, ret, s_error);
739
- free(s_error);
740
- }
741
- } else if (ret == SELECT_TIMEOUT) {
742
-
743
- if (response_length == (offset + 2 + TAB_CHECKSUM_LENGTH[mb_param->type_com])) {
744
- /* EXCEPTION CODE RECEIVED */
745
-
746
- /* Optimization allowed because exception response is
747
- the smallest trame in modbus protocol (3) so always
748
- raise a timeout error */
749
-
750
- /* CRC must be checked here (not done in receive_msg) */
751
- if (mb_param->type_com == RTU) {
752
- ret = check_crc16(mb_param, response, response_length);
753
- if (ret != 0)
754
- return ret;
755
- }
756
-
757
- /* Check for exception response.
758
- 0x80 + function is stored in the exception
759
- response. */
760
- if (0x80 + query[offset] == response[offset]) {
761
-
762
- int exception_code = response[offset + 1];
763
- // FIXME check test
764
- if (exception_code < NB_TAB_ERROR_MSG) {
765
- error_treat(mb_param, -exception_code,
766
- TAB_ERROR_MSG[response[offset + 1]]);
767
- /* RETURN THE EXCEPTION CODE */
768
- /* Modbus error code is negative */
769
- return -exception_code;
770
- } else {
771
- /* The chances are low to hit this
772
- case but it can avoid a vicious
773
- segfault */
774
- char *s_error = malloc(64 * sizeof(char));
775
- sprintf(s_error,
776
- "Invalid exception code %d",
777
- response[offset + 1]);
778
- error_treat(mb_param, INVALID_EXCEPTION_CODE,
779
- s_error);
780
- free(s_error);
781
- return INVALID_EXCEPTION_CODE;
782
- }
783
- }
784
- /* If doesn't return previously, return as
785
- TIME OUT here */
786
- }
787
-
788
- error_treat(mb_param, ret, "Select timeout");
789
- return ret;
790
- }
791
-
792
- return ret;
793
- }
794
-
795
- static int response_io_status(int address, int nb,
796
- uint8_t *tab_io_status,
797
- uint8_t *response, int offset)
798
- {
799
- int shift = 0;
800
- int byte = 0;
801
- int i;
802
-
803
- for (i = address; i < address+nb; i++) {
804
- byte |= tab_io_status[i] << shift;
805
- if (shift == 7) {
806
- /* Byte is full */
807
- response[offset++] = byte;
808
- byte = shift = 0;
809
- } else {
810
- shift++;
811
- }
812
- }
813
-
814
- if (shift != 0)
815
- response[offset++] = byte;
816
-
817
- return offset;
818
- }
819
-
820
- /* Build the exception response */
821
- static int response_exception(modbus_param_t *mb_param, sft_t *sft,
822
- int exception_code, uint8_t *response)
823
- {
824
- int response_length;
825
-
826
- sft->function = sft->function + 0x80;
827
- response_length = build_response_basis(mb_param, sft, response);
828
-
829
- /* Positive exception code */
830
- response[response_length++] = -exception_code;
831
-
832
- return response_length;
833
- }
834
-
835
- /* Manages the received query.
836
- Analyses the query and constructs a response.
837
-
838
- If an error occurs, this function construct the response
839
- accordingly.
840
- */
841
- void modbus_slave_manage(modbus_param_t *mb_param, const uint8_t *query,
842
- int query_length, modbus_mapping_t *mb_mapping)
843
- {
844
- int offset = TAB_HEADER_LENGTH[mb_param->type_com];
845
- int slave = query[offset - 1];
846
- int function = query[offset];
847
- uint16_t address = (query[offset + 1] << 8) + query[offset + 2];
848
- uint8_t response[MAX_MESSAGE_LENGTH];
849
- int resp_length = 0;
850
- sft_t sft;
851
-
852
- if (slave != mb_param->slave && slave != MODBUS_BROADCAST_ADDRESS) {
853
- // Ignores the query (not for me)
854
- if (mb_param->debug) {
855
- printf("Request for slave %d ignored (not %d)\n",
856
- slave, mb_param->slave);
857
- }
858
- return;
859
- }
860
-
861
- sft.slave = slave;
862
- sft.function = function;
863
- if (mb_param->type_com == TCP) {
864
- sft.t_id = (query[0] << 8) + query[1];
865
- } else {
866
- sft.t_id = 0;
867
- query_length -= CHECKSUM_LENGTH_RTU;
868
- }
869
-
870
- switch (function) {
871
- case FC_READ_COIL_STATUS: {
872
- int nb = (query[offset + 3] << 8) + query[offset + 4];
873
-
874
- if ((address + nb) > mb_mapping->nb_coil_status) {
875
- printf("Illegal data address %0X in read_coil_status\n",
876
- address + nb);
877
- resp_length = response_exception(mb_param, &sft,
878
- ILLEGAL_DATA_ADDRESS, response);
879
- } else {
880
- resp_length = build_response_basis(mb_param, &sft, response);
881
- response[resp_length++] = (nb / 8) + ((nb % 8) ? 1 : 0);
882
- resp_length = response_io_status(address, nb,
883
- mb_mapping->tab_coil_status,
884
- response, resp_length);
885
- }
886
- }
887
- break;
888
- case FC_READ_INPUT_STATUS: {
889
- /* Similar to coil status (but too much arguments to use a
890
- * function) */
891
- int nb = (query[offset + 3] << 8) + query[offset + 4];
892
-
893
- if ((address + nb) > mb_mapping->nb_input_status) {
894
- printf("Illegal data address %0X in read_input_status\n",
895
- address + nb);
896
- resp_length = response_exception(mb_param, &sft,
897
- ILLEGAL_DATA_ADDRESS, response);
898
- } else {
899
- resp_length = build_response_basis(mb_param, &sft, response);
900
- response[resp_length++] = (nb / 8) + ((nb % 8) ? 1 : 0);
901
- resp_length = response_io_status(address, nb,
902
- mb_mapping->tab_input_status,
903
- response, resp_length);
904
- }
905
- }
906
- break;
907
- case FC_READ_HOLDING_REGISTERS: {
908
- int nb = (query[offset + 3] << 8) + query[offset + 4];
909
-
910
- if ((address + nb) > mb_mapping->nb_holding_registers) {
911
- printf("Illegal data address %0X in read_holding_registers\n",
912
- address + nb);
913
- resp_length = response_exception(mb_param, &sft,
914
- ILLEGAL_DATA_ADDRESS, response);
915
- } else {
916
- int i;
917
-
918
- resp_length = build_response_basis(mb_param, &sft, response);
919
- response[resp_length++] = nb << 1;
920
- for (i = address; i < address + nb; i++) {
921
- response[resp_length++] = mb_mapping->tab_holding_registers[i] >> 8;
922
- response[resp_length++] = mb_mapping->tab_holding_registers[i] & 0xFF;
923
- }
924
- }
925
- }
926
- break;
927
- case FC_READ_INPUT_REGISTERS: {
928
- /* Similar to holding registers (but too much arguments to use a
929
- * function) */
930
- int nb = (query[offset + 3] << 8) + query[offset + 4];
931
-
932
- if ((address + nb) > mb_mapping->nb_input_registers) {
933
- printf("Illegal data address %0X in read_input_registers\n",
934
- address + nb);
935
- resp_length = response_exception(mb_param, &sft,
936
- ILLEGAL_DATA_ADDRESS, response);
937
- } else {
938
- int i;
939
-
940
- resp_length = build_response_basis(mb_param, &sft, response);
941
- response[resp_length++] = nb << 1;
942
- for (i = address; i < address + nb; i++) {
943
- response[resp_length++] = mb_mapping->tab_input_registers[i] >> 8;
944
- response[resp_length++] = mb_mapping->tab_input_registers[i] & 0xFF;
945
- }
946
- }
947
- }
948
- break;
949
- case FC_FORCE_SINGLE_COIL:
950
- if (address >= mb_mapping->nb_coil_status) {
951
- printf("Illegal data address %0X in force_singe_coil\n", address);
952
- resp_length = response_exception(mb_param, &sft,
953
- ILLEGAL_DATA_ADDRESS, response);
954
- } else {
955
- int data = (query[offset + 3] << 8) + query[offset + 4];
956
-
957
- if (data == 0xFF00 || data == 0x0) {
958
- mb_mapping->tab_coil_status[address] = (data) ? ON : OFF;
959
-
960
- /* In RTU mode, the CRC is computed and added
961
- to the query by modbus_send, the computed
962
- CRC will be same and optimisation is
963
- possible here (FIXME). */
964
- memcpy(response, query, query_length);
965
- resp_length = query_length;
966
- } else {
967
- printf("Illegal data value %0X in force_single_coil request at address %0X\n",
968
- data, address);
969
- resp_length = response_exception(mb_param, &sft,
970
- ILLEGAL_DATA_VALUE, response);
971
- }
972
- }
973
- break;
974
- case FC_PRESET_SINGLE_REGISTER:
975
- if (address >= mb_mapping->nb_holding_registers) {
976
- printf("Illegal data address %0X in preset_holding_register\n", address);
977
- resp_length = response_exception(mb_param, &sft,
978
- ILLEGAL_DATA_ADDRESS, response);
979
- } else {
980
- int data = (query[offset + 3] << 8) + query[offset + 4];
981
-
982
- mb_mapping->tab_holding_registers[address] = data;
983
- memcpy(response, query, query_length);
984
- resp_length = query_length;
985
- }
986
- break;
987
- case FC_FORCE_MULTIPLE_COILS: {
988
- int nb = (query[offset + 3] << 8) + query[offset + 4];
989
-
990
- if ((address + nb) > mb_mapping->nb_coil_status) {
991
- printf("Illegal data address %0X in force_multiple_coils\n",
992
- address + nb);
993
- resp_length = response_exception(mb_param, &sft,
994
- ILLEGAL_DATA_ADDRESS, response);
995
- } else {
996
- /* 6 = byte count */
997
- set_bits_from_bytes(mb_mapping->tab_coil_status, address, nb, &query[offset + 6]);
998
-
999
- resp_length = build_response_basis(mb_param, &sft, response);
1000
- /* 4 to copy the coil address (2) and the quantity of coils */
1001
- memcpy(response + resp_length, query + resp_length, 4);
1002
- resp_length += 4;
1003
- }
1004
- }
1005
- break;
1006
- case FC_PRESET_MULTIPLE_REGISTERS: {
1007
- int nb = (query[offset + 3] << 8) + query[offset + 4];
1008
-
1009
- if ((address + nb) > mb_mapping->nb_holding_registers) {
1010
- printf("Illegal data address %0X in preset_multiple_registers\n",
1011
- address + nb);
1012
- resp_length = response_exception(mb_param, &sft,
1013
- ILLEGAL_DATA_ADDRESS, response);
1014
- } else {
1015
- int i, j;
1016
- for (i = address, j = 6; i < address + nb; i++, j += 2) {
1017
- /* 6 and 7 = first value */
1018
- mb_mapping->tab_holding_registers[i] =
1019
- (query[offset + j] << 8) + query[offset + j + 1];
1020
- }
1021
-
1022
- resp_length = build_response_basis(mb_param, &sft, response);
1023
- /* 4 to copy the address (2) and the no. of registers */
1024
- memcpy(response + resp_length, query + resp_length, 4);
1025
- resp_length += 4;
1026
- }
1027
- }
1028
- break;
1029
- case FC_READ_EXCEPTION_STATUS:
1030
- case FC_REPORT_SLAVE_ID:
1031
- printf("Not implemented\n");
1032
- break;
1033
- }
1034
-
1035
- modbus_send(mb_param, response, resp_length);
1036
- }
1037
-
1038
- /* Reads IO status */
1039
- static int read_io_status(modbus_param_t *mb_param, int function,
1040
- int start_addr, int nb, uint8_t *data_dest)
1041
- {
1042
- int ret;
1043
- int query_length;
1044
-
1045
- uint8_t query[MIN_QUERY_LENGTH];
1046
- uint8_t response[MAX_MESSAGE_LENGTH];
1047
-
1048
- query_length = build_query_basis(mb_param, function,
1049
- start_addr, nb, query);
1050
-
1051
- ret = modbus_send(mb_param, query, query_length);
1052
- if (ret > 0) {
1053
- int i, temp, bit;
1054
- int pos = 0;
1055
- int offset;
1056
- int offset_end;
1057
-
1058
- ret = modbus_receive(mb_param, query, response);
1059
- if (ret < 0)
1060
- return ret;
1061
-
1062
- offset = TAB_HEADER_LENGTH[mb_param->type_com];
1063
- offset_end = offset + ret;
1064
- for (i = offset; i < offset_end; i++) {
1065
- /* Shift reg hi_byte to temp */
1066
- temp = response[i + 2];
1067
-
1068
- for (bit = 0x01; (bit & 0xff) && (pos < nb);) {
1069
- data_dest[pos++] = (temp & bit) ? TRUE : FALSE;
1070
- bit = bit << 1;
1071
- }
1072
-
1073
- }
1074
- }
1075
-
1076
- return ret;
1077
- }
1078
-
1079
- /* Reads the boolean status of coils and sets the array elements
1080
- in the destination to TRUE or FALSE. */
1081
- int read_coil_status(modbus_param_t *mb_param, int start_addr,
1082
- int nb, uint8_t *data_dest)
1083
- {
1084
- int status;
1085
-
1086
- if (nb > MAX_STATUS) {
1087
- printf("ERROR Too many coils status requested (%d > %d)\n",
1088
- nb, MAX_STATUS);
1089
- return INVALID_DATA;
1090
- }
1091
-
1092
- status = read_io_status(mb_param, FC_READ_COIL_STATUS,
1093
- start_addr, nb, data_dest);
1094
-
1095
- if (status > 0)
1096
- status = nb;
1097
-
1098
- return status;
1099
- }
1100
-
1101
-
1102
- /* Same as read_coil_status but reads the slaves input table */
1103
- int read_input_status(modbus_param_t *mb_param, int start_addr,
1104
- int nb, uint8_t *data_dest)
1105
- {
1106
- int status;
1107
-
1108
- if (nb > MAX_STATUS) {
1109
- printf("ERROR Too many input status requested (%d > %d)\n",
1110
- nb, MAX_STATUS);
1111
- return INVALID_DATA;
1112
- }
1113
-
1114
- status = read_io_status(mb_param, FC_READ_INPUT_STATUS,
1115
- start_addr, nb, data_dest);
1116
-
1117
- if (status > 0)
1118
- status = nb;
1119
-
1120
- return status;
1121
- }
1122
-
1123
- /* Reads the data from a modbus slave and put that data into an array */
1124
- static int read_registers(modbus_param_t *mb_param, int function,
1125
- int start_addr, int nb, uint16_t *data_dest)
1126
- {
1127
- int ret;
1128
- int query_length;
1129
- uint8_t query[MIN_QUERY_LENGTH];
1130
- uint8_t response[MAX_MESSAGE_LENGTH];
1131
-
1132
- if (nb > MAX_REGISTERS) {
1133
- printf("ERROR Too many holding registers requested (%d > %d)\n",
1134
- nb, MAX_REGISTERS);
1135
- return INVALID_DATA;
1136
- }
1137
-
1138
- query_length = build_query_basis(mb_param, function,
1139
- start_addr, nb, query);
1140
-
1141
- ret = modbus_send(mb_param, query, query_length);
1142
- if (ret > 0) {
1143
- int offset;
1144
- int i;
1145
-
1146
- ret = modbus_receive(mb_param, query, response);
1147
-
1148
- offset = TAB_HEADER_LENGTH[mb_param->type_com];
1149
-
1150
- /* If ret is negative, the loop is jumped ! */
1151
- for (i = 0; i < ret; i++) {
1152
- /* shift reg hi_byte to temp OR with lo_byte */
1153
- data_dest[i] = (response[offset + 2 + (i << 1)] << 8) |
1154
- response[offset + 3 + (i << 1)];
1155
- }
1156
- }
1157
-
1158
- return ret;
1159
- }
1160
-
1161
- /* Reads the holding registers in a slave and put the data into an
1162
- array */
1163
- int read_holding_registers(modbus_param_t *mb_param,
1164
- int start_addr, int nb, uint16_t *data_dest)
1165
- {
1166
- int status;
1167
-
1168
- if (nb > MAX_REGISTERS) {
1169
- printf("ERROR Too many holding registers requested (%d > %d)\n",
1170
- nb, MAX_REGISTERS);
1171
- return INVALID_DATA;
1172
- }
1173
-
1174
- status = read_registers(mb_param, FC_READ_HOLDING_REGISTERS,
1175
- start_addr, nb, data_dest);
1176
- return status;
1177
- }
1178
-
1179
- /* Reads the input registers in a slave and put the data into
1180
- an array */
1181
- int read_input_registers(modbus_param_t *mb_param, int start_addr, int nb,
1182
- uint16_t *data_dest)
1183
- {
1184
- int status;
1185
-
1186
- if (nb > MAX_REGISTERS) {
1187
- printf("ERROR Too many input registers requested (%d > %d)\n",
1188
- nb, MAX_REGISTERS);
1189
- return INVALID_DATA;
1190
- }
1191
-
1192
- status = read_registers(mb_param, FC_READ_INPUT_REGISTERS,
1193
- start_addr, nb, data_dest);
1194
-
1195
- return status;
1196
- }
1197
-
1198
- /* Sends a value to a register in a slave.
1199
- Used by force_single_coil and preset_single_register */
1200
- static int set_single(modbus_param_t *mb_param, int function,
1201
- int addr, int value)
1202
- {
1203
- int ret;
1204
- int query_length;
1205
- uint8_t query[MIN_QUERY_LENGTH];
1206
-
1207
- query_length = build_query_basis(mb_param, function,
1208
- addr, value, query);
1209
-
1210
- ret = modbus_send(mb_param, query, query_length);
1211
- if (ret > 0) {
1212
- /* Used by force_single_coil and
1213
- * preset_single_register */
1214
- uint8_t response[MIN_QUERY_LENGTH];
1215
- ret = modbus_receive(mb_param, query, response);
1216
- }
1217
-
1218
- return ret;
1219
- }
1220
-
1221
- /* Turns ON or OFF a single coil in the slave device */
1222
- int force_single_coil(modbus_param_t *mb_param, int coil_addr, int state)
1223
- {
1224
- int status;
1225
-
1226
- if (state)
1227
- state = 0xFF00;
1228
-
1229
- status = set_single(mb_param, FC_FORCE_SINGLE_COIL,
1230
- coil_addr, state);
1231
-
1232
- return status;
1233
- }
1234
-
1235
- /* Sets a value in one holding register in the slave device */
1236
- int preset_single_register(modbus_param_t *mb_param, int reg_addr, int value)
1237
- {
1238
- int status;
1239
-
1240
- status = set_single(mb_param, FC_PRESET_SINGLE_REGISTER,
1241
- reg_addr, value);
1242
-
1243
- return status;
1244
- }
1245
-
1246
- /* Sets/resets the coils in the slave from an array in argument */
1247
- int force_multiple_coils(modbus_param_t *mb_param, int start_addr, int nb,
1248
- const uint8_t *data_src)
1249
- {
1250
- int ret;
1251
- int i;
1252
- int byte_count;
1253
- int query_length;
1254
- int coil_check = 0;
1255
- int pos = 0;
1256
-
1257
- uint8_t query[MAX_MESSAGE_LENGTH];
1258
-
1259
- if (nb > MAX_STATUS) {
1260
- printf("ERROR Writing to too many coils (%d > %d)\n",
1261
- nb, MAX_STATUS);
1262
- return INVALID_DATA;
1263
- }
1264
-
1265
- query_length = build_query_basis(mb_param, FC_FORCE_MULTIPLE_COILS,
1266
- start_addr, nb, query);
1267
- byte_count = (nb / 8) + ((nb % 8) ? 1 : 0);
1268
- query[query_length++] = byte_count;
1269
-
1270
- for (i = 0; i < byte_count; i++) {
1271
- int bit;
1272
-
1273
- bit = 0x01;
1274
- query[query_length] = 0;
1275
-
1276
- while ((bit & 0xFF) && (coil_check++ < nb)) {
1277
- if (data_src[pos++])
1278
- query[query_length] |= bit;
1279
- else
1280
- query[query_length] &=~ bit;
1281
-
1282
- bit = bit << 1;
1283
- }
1284
- query_length++;
1285
- }
1286
-
1287
- ret = modbus_send(mb_param, query, query_length);
1288
- if (ret > 0) {
1289
- uint8_t response[MAX_MESSAGE_LENGTH];
1290
- ret = modbus_receive(mb_param, query, response);
1291
- }
1292
-
1293
-
1294
- return ret;
1295
- }
1296
-
1297
- /* Copies the values in the slave from the array given in argument */
1298
- int preset_multiple_registers(modbus_param_t *mb_param, int start_addr, int nb,
1299
- const uint16_t *data_src)
1300
- {
1301
- int ret;
1302
- int i;
1303
- int query_length;
1304
- int byte_count;
1305
-
1306
- uint8_t query[MAX_MESSAGE_LENGTH];
1307
-
1308
- if (nb > MAX_REGISTERS) {
1309
- printf("ERROR Trying to write to too many registers (%d > %d)\n",
1310
- nb, MAX_REGISTERS);
1311
- return INVALID_DATA;
1312
- }
1313
-
1314
- query_length = build_query_basis(mb_param, FC_PRESET_MULTIPLE_REGISTERS,
1315
- start_addr, nb, query);
1316
- byte_count = nb * 2;
1317
- query[query_length++] = byte_count;
1318
-
1319
- for (i = 0; i < nb; i++) {
1320
- query[query_length++] = data_src[i] >> 8;
1321
- query[query_length++] = data_src[i] & 0x00FF;
1322
- }
1323
-
1324
- ret = modbus_send(mb_param, query, query_length);
1325
- if (ret > 0) {
1326
- uint8_t response[MAX_MESSAGE_LENGTH];
1327
- ret = modbus_receive(mb_param, query, response);
1328
- }
1329
-
1330
- return ret;
1331
- }
1332
-
1333
- /* Returns the slave id! */
1334
- int report_slave_id(modbus_param_t *mb_param, uint8_t *data_dest)
1335
- {
1336
- int ret;
1337
- int query_length;
1338
- uint8_t query[MIN_QUERY_LENGTH];
1339
-
1340
- query_length = build_query_basis(mb_param, FC_REPORT_SLAVE_ID, 0, 0, query);
1341
-
1342
- /* HACKISH, start_addr and count are not used */
1343
- query_length -= 4;
1344
-
1345
- ret = modbus_send(mb_param, query, query_length);
1346
- if (ret > 0) {
1347
- int i;
1348
- int offset;
1349
- int offset_end;
1350
- uint8_t response[MAX_MESSAGE_LENGTH];
1351
-
1352
- /* Byte count, slave id, run indicator status,
1353
- additional data */
1354
- ret = modbus_receive(mb_param, query, response);
1355
- if (ret < 0)
1356
- return ret;
1357
-
1358
- offset = TAB_HEADER_LENGTH[mb_param->type_com] - 1;
1359
- offset_end = offset + ret;
1360
-
1361
- for (i = offset; i < offset_end; i++)
1362
- data_dest[i] = response[i];
1363
- }
1364
-
1365
- return ret;
1366
- }
1367
-
1368
- /* Initializes the modbus_param_t structure for RTU
1369
- - device: "/dev/ttyS0"
1370
- - baud: 9600, 19200, 57600, 115200, etc
1371
- - parity: "even", "odd" or "none"
1372
- - data_bits: 5, 6, 7, 8
1373
- - stop_bits: 1, 2
1374
- */
1375
- void modbus_init_rtu(modbus_param_t *mb_param, const char *device,
1376
- int baud, const char *parity, int data_bit,
1377
- int stop_bit, int slave)
1378
- {
1379
- memset(mb_param, 0, sizeof(modbus_param_t));
1380
- strcpy(mb_param->device, device);
1381
- mb_param->baud = baud;
1382
- strcpy(mb_param->parity, parity);
1383
- mb_param->debug = FALSE;
1384
- mb_param->data_bit = data_bit;
1385
- mb_param->stop_bit = stop_bit;
1386
- mb_param->type_com = RTU;
1387
- mb_param->error_handling = FLUSH_OR_CONNECT_ON_ERROR;
1388
- mb_param->slave = slave;
1389
- }
1390
-
1391
- /* Initializes the modbus_param_t structure for TCP.
1392
- - ip : "192.168.0.5"
1393
- - port : 1099
1394
-
1395
- Set the port to MODBUS_TCP_DEFAULT_PORT to use the default one
1396
- (502). It's convenient to use a port number greater than or equal
1397
- to 1024 because it's not necessary to be root to use this port
1398
- number.
1399
- */
1400
- void modbus_init_tcp(modbus_param_t *mb_param, const char *ip, int port, int slave)
1401
- {
1402
- memset(mb_param, 0, sizeof(modbus_param_t));
1403
- strncpy(mb_param->ip, ip, sizeof(char)*16);
1404
- mb_param->port = port;
1405
- mb_param->type_com = TCP;
1406
- mb_param->error_handling = FLUSH_OR_CONNECT_ON_ERROR;
1407
- mb_param->slave = slave;
1408
- }
1409
-
1410
- /* By default, the error handling mode used is FLUSH_OR_CONNECT_ON_ERROR.
1411
-
1412
- With FLUSH_OR_CONNECT_ON_ERROR, the library will attempt an immediate
1413
- reconnection which may hang for several seconds if the network to
1414
- the remote target unit is down.
1415
-
1416
- With NOP_ON_ERROR, it is expected that the application will
1417
- check for error returns and deal with them as necessary.
1418
- */
1419
- void modbus_set_error_handling(modbus_param_t *mb_param,
1420
- error_handling_t error_handling)
1421
- {
1422
- if (error_handling == FLUSH_OR_CONNECT_ON_ERROR ||
1423
- error_handling == NOP_ON_ERROR) {
1424
- mb_param->error_handling = error_handling;
1425
- } else {
1426
- printf("Invalid setting for error handling (not changed)\n");
1427
- }
1428
- }
1429
-
1430
-
1431
- /* Sets up a serial port for RTU communications */
1432
- static int modbus_connect_rtu(modbus_param_t *mb_param)
1433
- {
1434
- struct termios tios;
1435
- speed_t speed;
1436
-
1437
- if (mb_param->debug) {
1438
- printf("Opening %s at %d bauds (%s)\n",
1439
- mb_param->device, mb_param->baud, mb_param->parity);
1440
- }
1441
-
1442
- /* The O_NOCTTY flag tells UNIX that this program doesn't want
1443
- to be the "controlling terminal" for that port. If you
1444
- don't specify this then any input (such as keyboard abort
1445
- signals and so forth) will affect your process
1446
-
1447
- Timeouts are ignored in canonical input mode or when the
1448
- NDELAY option is set on the file via open or fcntl */
1449
- mb_param->fd = open(mb_param->device, O_RDWR | O_NOCTTY | O_NDELAY);
1450
- if (mb_param->fd < 0) {
1451
- perror("open");
1452
- printf("ERROR Can't open the device %s (%s)\n",
1453
- mb_param->device, strerror(errno));
1454
- return -1;
1455
- }
1456
-
1457
- /* Save */
1458
- tcgetattr(mb_param->fd, &(mb_param->old_tios));
1459
-
1460
- memset(&tios, 0, sizeof(struct termios));
1461
-
1462
- /* C_ISPEED Input baud (new interface)
1463
- C_OSPEED Output baud (new interface)
1464
- */
1465
- switch (mb_param->baud) {
1466
- case 110:
1467
- speed = B110;
1468
- break;
1469
- case 300:
1470
- speed = B300;
1471
- break;
1472
- case 600:
1473
- speed = B600;
1474
- break;
1475
- case 1200:
1476
- speed = B1200;
1477
- break;
1478
- case 2400:
1479
- speed = B2400;
1480
- break;
1481
- case 4800:
1482
- speed = B4800;
1483
- break;
1484
- case 9600:
1485
- speed = B9600;
1486
- break;
1487
- case 19200:
1488
- speed = B19200;
1489
- break;
1490
- case 38400:
1491
- speed = B38400;
1492
- break;
1493
- case 57600:
1494
- speed = B57600;
1495
- break;
1496
- case 115200:
1497
- speed = B115200;
1498
- break;
1499
- default:
1500
- speed = B9600;
1501
- printf("WARNING Unknown baud rate %d for %s (B9600 used)\n",
1502
- mb_param->baud, mb_param->device);
1503
- }
1504
-
1505
- /* Set the baud rate */
1506
- if ((cfsetispeed(&tios, speed) < 0) ||
1507
- (cfsetospeed(&tios, speed) < 0)) {
1508
- perror("cfsetispeed/cfsetospeed\n");
1509
- return -1;
1510
- }
1511
-
1512
- /* C_CFLAG Control options
1513
- CLOCAL Local line - do not change "owner" of port
1514
- CREAD Enable receiver
1515
- */
1516
- tios.c_cflag |= (CREAD | CLOCAL);
1517
- /* CSIZE, HUPCL, CRTSCTS (hardware flow control) */
1518
-
1519
- /* Set data bits (5, 6, 7, 8 bits)
1520
- CSIZE Bit mask for data bits
1521
- */
1522
- tios.c_cflag &= ~CSIZE;
1523
- switch (mb_param->data_bit) {
1524
- case 5:
1525
- tios.c_cflag |= CS5;
1526
- break;
1527
- case 6:
1528
- tios.c_cflag |= CS6;
1529
- break;
1530
- case 7:
1531
- tios.c_cflag |= CS7;
1532
- break;
1533
- case 8:
1534
- default:
1535
- tios.c_cflag |= CS8;
1536
- break;
1537
- }
1538
-
1539
- /* Stop bit (1 or 2) */
1540
- if (mb_param->stop_bit == 1)
1541
- tios.c_cflag &=~ CSTOPB;
1542
- else /* 2 */
1543
- tios.c_cflag |= CSTOPB;
1544
-
1545
- /* PARENB Enable parity bit
1546
- PARODD Use odd parity instead of even */
1547
- if (strncmp(mb_param->parity, "none", 4) == 0) {
1548
- tios.c_cflag &=~ PARENB;
1549
- } else if (strncmp(mb_param->parity, "even", 4) == 0) {
1550
- tios.c_cflag |= PARENB;
1551
- tios.c_cflag &=~ PARODD;
1552
- } else {
1553
- /* odd */
1554
- tios.c_cflag |= PARENB;
1555
- tios.c_cflag |= PARODD;
1556
- }
1557
-
1558
- /* Read the man page of termios if you need more information. */
1559
-
1560
- /* This field isn't used on POSIX systems
1561
- tios.c_line = 0;
1562
- */
1563
-
1564
- /* C_LFLAG Line options
1565
-
1566
- ISIG Enable SIGINTR, SIGSUSP, SIGDSUSP, and SIGQUIT signals
1567
- ICANON Enable canonical input (else raw)
1568
- XCASE Map uppercase \lowercase (obsolete)
1569
- ECHO Enable echoing of input characters
1570
- ECHOE Echo erase character as BS-SP-BS
1571
- ECHOK Echo NL after kill character
1572
- ECHONL Echo NL
1573
- NOFLSH Disable flushing of input buffers after
1574
- interrupt or quit characters
1575
- IEXTEN Enable extended functions
1576
- ECHOCTL Echo control characters as ^char and delete as ~?
1577
- ECHOPRT Echo erased character as character erased
1578
- ECHOKE BS-SP-BS entire line on line kill
1579
- FLUSHO Output being flushed
1580
- PENDIN Retype pending input at next read or input char
1581
- TOSTOP Send SIGTTOU for background output
1582
-
1583
- Canonical input is line-oriented. Input characters are put
1584
- into a buffer which can be edited interactively by the user
1585
- until a CR (carriage return) or LF (line feed) character is
1586
- received.
1587
-
1588
- Raw input is unprocessed. Input characters are passed
1589
- through exactly as they are received, when they are
1590
- received. Generally you'll deselect the ICANON, ECHO,
1591
- ECHOE, and ISIG options when using raw input
1592
- */
1593
-
1594
- /* Raw input */
1595
- tios.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG);
1596
-
1597
- /* C_IFLAG Input options
1598
-
1599
- Constant Description
1600
- INPCK Enable parity check
1601
- IGNPAR Ignore parity errors
1602
- PARMRK Mark parity errors
1603
- ISTRIP Strip parity bits
1604
- IXON Enable software flow control (outgoing)
1605
- IXOFF Enable software flow control (incoming)
1606
- IXANY Allow any character to start flow again
1607
- IGNBRK Ignore break condition
1608
- BRKINT Send a SIGINT when a break condition is detected
1609
- INLCR Map NL to CR
1610
- IGNCR Ignore CR
1611
- ICRNL Map CR to NL
1612
- IUCLC Map uppercase to lowercase
1613
- IMAXBEL Echo BEL on input line too long
1614
- */
1615
- if (strncmp(mb_param->parity, "none", 4) == 0) {
1616
- tios.c_iflag &= ~INPCK;
1617
- } else {
1618
- tios.c_iflag |= INPCK;
1619
- }
1620
-
1621
- /* Software flow control is disabled */
1622
- tios.c_iflag &= ~(IXON | IXOFF | IXANY);
1623
-
1624
- /* C_OFLAG Output options
1625
- OPOST Postprocess output (not set = raw output)
1626
- ONLCR Map NL to CR-NL
1627
-
1628
- ONCLR ant others needs OPOST to be enabled
1629
- */
1630
-
1631
- /* Raw ouput */
1632
- tios.c_oflag &=~ OPOST;
1633
-
1634
- /* C_CC Control characters
1635
- VMIN Minimum number of characters to read
1636
- VTIME Time to wait for data (tenths of seconds)
1637
-
1638
- UNIX serial interface drivers provide the ability to
1639
- specify character and packet timeouts. Two elements of the
1640
- c_cc array are used for timeouts: VMIN and VTIME. Timeouts
1641
- are ignored in canonical input mode or when the NDELAY
1642
- option is set on the file via open or fcntl.
1643
-
1644
- VMIN specifies the minimum number of characters to read. If
1645
- it is set to 0, then the VTIME value specifies the time to
1646
- wait for every character read. Note that this does not mean
1647
- that a read call for N bytes will wait for N characters to
1648
- come in. Rather, the timeout will apply to the first
1649
- character and the read call will return the number of
1650
- characters immediately available (up to the number you
1651
- request).
1652
-
1653
- If VMIN is non-zero, VTIME specifies the time to wait for
1654
- the first character read. If a character is read within the
1655
- time given, any read will block (wait) until all VMIN
1656
- characters are read. That is, once the first character is
1657
- read, the serial interface driver expects to receive an
1658
- entire packet of characters (VMIN bytes total). If no
1659
- character is read within the time allowed, then the call to
1660
- read returns 0. This method allows you to tell the serial
1661
- driver you need exactly N bytes and any read call will
1662
- return 0 or N bytes. However, the timeout only applies to
1663
- the first character read, so if for some reason the driver
1664
- misses one character inside the N byte packet then the read
1665
- call could block forever waiting for additional input
1666
- characters.
1667
-
1668
- VTIME specifies the amount of time to wait for incoming
1669
- characters in tenths of seconds. If VTIME is set to 0 (the
1670
- default), reads will block (wait) indefinitely unless the
1671
- NDELAY option is set on the port with open or fcntl.
1672
- */
1673
- /* Unused because we use open with the NDELAY option */
1674
- tios.c_cc[VMIN] = 0;
1675
- tios.c_cc[VTIME] = 0;
1676
-
1677
- if (tcsetattr(mb_param->fd, TCSANOW, &tios) < 0) {
1678
- perror("tcsetattr\n");
1679
- return -1;
1680
- }
1681
-
1682
- return 0;
1683
- }
1684
-
1685
- /* Establishes a modbus TCP connection with a modbus slave */
1686
- static int modbus_connect_tcp(modbus_param_t *mb_param)
1687
- {
1688
- int ret;
1689
- int option;
1690
- struct sockaddr_in addr;
1691
-
1692
- mb_param->fd = socket(PF_INET, SOCK_STREAM, 0);
1693
- if (mb_param->fd < 0) {
1694
- return mb_param->fd;
1695
- }
1696
-
1697
- /* Set the TCP no delay flag */
1698
- /* SOL_TCP = IPPROTO_TCP */
1699
- option = 1;
1700
- ret = setsockopt(mb_param->fd, IPPROTO_TCP, TCP_NODELAY,
1701
- (const void *)&option, sizeof(int));
1702
- if (ret < 0) {
1703
- perror("setsockopt");
1704
- close(mb_param->fd);
1705
- return ret;
1706
- }
1707
-
1708
- #if (!HAVE_DECL___CYGWIN__)
1709
- /**
1710
- * Cygwin defines IPTOS_LOWDELAY but can't handle that flag so it's
1711
- * necessary to workaround that problem.
1712
- **/
1713
- /* Set the IP low delay option */
1714
- option = IPTOS_LOWDELAY;
1715
- ret = setsockopt(mb_param->fd, IPPROTO_TCP, IP_TOS,
1716
- (const void *)&option, sizeof(int));
1717
- if (ret < 0) {
1718
- perror("setsockopt");
1719
- close(mb_param->fd);
1720
- return ret;
1721
- }
1722
- #endif
1723
-
1724
- if (mb_param->debug) {
1725
- printf("Connecting to %s\n", mb_param->ip);
1726
- }
1727
-
1728
- addr.sin_family = AF_INET;
1729
- addr.sin_port = htons(mb_param->port);
1730
- addr.sin_addr.s_addr = inet_addr(mb_param->ip);
1731
- ret = connect(mb_param->fd, (struct sockaddr *)&addr,
1732
- sizeof(struct sockaddr_in));
1733
- if (ret < 0) {
1734
- perror("connect");
1735
- close(mb_param->fd);
1736
- return ret;
1737
- }
1738
-
1739
- return 0;
1740
- }
1741
-
1742
- /* Establishes a modbus connexion.
1743
- Returns 0 on success or -1 on failure. */
1744
- int modbus_connect(modbus_param_t *mb_param)
1745
- {
1746
- int ret;
1747
-
1748
- if (mb_param->type_com == RTU)
1749
- ret = modbus_connect_rtu(mb_param);
1750
- else
1751
- ret = modbus_connect_tcp(mb_param);
1752
-
1753
- return ret;
1754
- }
1755
-
1756
- /* Closes the file descriptor in RTU mode */
1757
- static void modbus_close_rtu(modbus_param_t *mb_param)
1758
- {
1759
- if (tcsetattr(mb_param->fd, TCSANOW, &(mb_param->old_tios)) < 0)
1760
- perror("tcsetattr");
1761
-
1762
- close(mb_param->fd);
1763
- }
1764
-
1765
- /* Closes the network connection and socket in TCP mode */
1766
- static void modbus_close_tcp(modbus_param_t *mb_param)
1767
- {
1768
- shutdown(mb_param->fd, SHUT_RDWR);
1769
- close(mb_param->fd);
1770
- }
1771
-
1772
- /* Closes a modbus connection */
1773
- void modbus_close(modbus_param_t *mb_param)
1774
- {
1775
- if (mb_param->type_com == RTU)
1776
- modbus_close_rtu(mb_param);
1777
- else
1778
- modbus_close_tcp(mb_param);
1779
- }
1780
-
1781
- /* Activates the debug messages */
1782
- void modbus_set_debug(modbus_param_t *mb_param, int boolean)
1783
- {
1784
- mb_param->debug = boolean;
1785
- }
1786
-
1787
- /* Allocates 4 arrays to store coils, input status, input registers and
1788
- holding registers. The pointers are stored in modbus_mapping structure.
1789
-
1790
- Returns 0 on success and -1 on failure.
1791
- */
1792
- int modbus_mapping_new(modbus_mapping_t *mb_mapping,
1793
- int nb_coil_status, int nb_input_status,
1794
- int nb_holding_registers, int nb_input_registers)
1795
- {
1796
- /* 0X */
1797
- mb_mapping->nb_coil_status = nb_coil_status;
1798
- mb_mapping->tab_coil_status =
1799
- (uint8_t *) malloc(nb_coil_status * sizeof(uint8_t));
1800
- memset(mb_mapping->tab_coil_status, 0,
1801
- nb_coil_status * sizeof(uint8_t));
1802
- if (mb_mapping->tab_coil_status == NULL)
1803
- return -1;
1804
-
1805
- /* 1X */
1806
- mb_mapping->nb_input_status = nb_input_status;
1807
- mb_mapping->tab_input_status =
1808
- (uint8_t *) malloc(nb_input_status * sizeof(uint8_t));
1809
- memset(mb_mapping->tab_input_status, 0,
1810
- nb_input_status * sizeof(uint8_t));
1811
- if (mb_mapping->tab_input_status == NULL) {
1812
- free(mb_mapping->tab_coil_status);
1813
- return -1;
1814
- }
1815
-
1816
- /* 4X */
1817
- mb_mapping->nb_holding_registers = nb_holding_registers;
1818
- mb_mapping->tab_holding_registers =
1819
- (uint16_t *) malloc(nb_holding_registers * sizeof(uint16_t));
1820
- memset(mb_mapping->tab_holding_registers, 0,
1821
- nb_holding_registers * sizeof(uint16_t));
1822
- if (mb_mapping->tab_holding_registers == NULL) {
1823
- free(mb_mapping->tab_coil_status);
1824
- free(mb_mapping->tab_input_status);
1825
- return -1;
1826
- }
1827
-
1828
- /* 3X */
1829
- mb_mapping->nb_input_registers = nb_input_registers;
1830
- mb_mapping->tab_input_registers =
1831
- (uint16_t *) malloc(nb_input_registers * sizeof(uint16_t));
1832
- memset(mb_mapping->tab_input_registers, 0,
1833
- nb_input_registers * sizeof(uint16_t));
1834
- if (mb_mapping->tab_input_registers == NULL) {
1835
- free(mb_mapping->tab_coil_status);
1836
- free(mb_mapping->tab_input_status);
1837
- free(mb_mapping->tab_holding_registers);
1838
- return -1;
1839
- }
1840
-
1841
- return 0;
1842
- }
1843
-
1844
- /* Frees the 4 arrays */
1845
- void modbus_mapping_free(modbus_mapping_t *mb_mapping)
1846
- {
1847
- free(mb_mapping->tab_coil_status);
1848
- free(mb_mapping->tab_input_status);
1849
- free(mb_mapping->tab_holding_registers);
1850
- free(mb_mapping->tab_input_registers);
1851
- }
1852
-
1853
- /* Listens for any query from one or many modbus masters in TCP */
1854
- int modbus_slave_listen_tcp(modbus_param_t *mb_param, int nb_connection)
1855
- {
1856
- int new_socket;
1857
- int yes;
1858
- struct sockaddr_in addr;
1859
-
1860
- new_socket = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
1861
- if (new_socket < 0) {
1862
- perror("socket");
1863
- return -1;
1864
- }
1865
-
1866
- yes = 1;
1867
- if (setsockopt(new_socket, SOL_SOCKET, SO_REUSEADDR,
1868
- (char *) &yes, sizeof(yes)) < 0) {
1869
- perror("setsockopt");
1870
- close(new_socket);
1871
- return -1;
1872
- }
1873
-
1874
- memset(&addr, 0, sizeof(addr));
1875
- addr.sin_family = AF_INET;
1876
- /* If the modbus port is < to 1024, we need the setuid root. */
1877
- addr.sin_port = htons(mb_param->port);
1878
- addr.sin_addr.s_addr = INADDR_ANY;
1879
- if (bind(new_socket, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
1880
- perror("bind");
1881
- close(new_socket);
1882
- return -1;
1883
- }
1884
-
1885
- if (listen(new_socket, nb_connection) < 0) {
1886
- perror("listen");
1887
- close(new_socket);
1888
- return -1;
1889
- }
1890
-
1891
- return new_socket;
1892
- }
1893
-
1894
- int modbus_slave_accept_tcp(modbus_param_t *mb_param, int *socket)
1895
- {
1896
- struct sockaddr_in addr;
1897
- socklen_t addrlen;
1898
-
1899
- addrlen = sizeof(struct sockaddr_in);
1900
- mb_param->fd = accept(*socket, (struct sockaddr *)&addr, &addrlen);
1901
- if (mb_param->fd < 0) {
1902
- perror("accept");
1903
- close(*socket);
1904
- *socket = 0;
1905
- } else {
1906
- printf("The client %s is connected\n",
1907
- inet_ntoa(addr.sin_addr));
1908
- }
1909
-
1910
- return mb_param->fd;
1911
- }
1912
-
1913
- /** Utils **/
1914
-
1915
- /* Sets many input/coil status from a single byte value (all 8 bits of
1916
- the byte value are set) */
1917
- void set_bits_from_byte(uint8_t *dest, int address, const uint8_t value)
1918
- {
1919
- int i;
1920
-
1921
- for (i=0; i<8; i++) {
1922
- dest[address+i] = (value & (1 << i)) ? ON : OFF;
1923
- }
1924
- }
1925
-
1926
- /* Sets many input/coil status from a table of bytes (only the bits
1927
- between address and address + nb_bits are set) */
1928
- void set_bits_from_bytes(uint8_t *dest, int address, int nb_bits,
1929
- const uint8_t tab_byte[])
1930
- {
1931
- int i;
1932
- int shift = 0;
1933
-
1934
- for (i = address; i < address + nb_bits; i++) {
1935
- dest[i] = tab_byte[(i - address) / 8] & (1 << shift) ? ON : OFF;
1936
- /* gcc doesn't like: shift = (++shift) % 8; */
1937
- shift++;
1938
- shift %= 8;
1939
- }
1940
- }
1941
-
1942
- /* Gets the byte value from many input/coil status.
1943
- To obtain a full byte, set nb_bits to 8. */
1944
- uint8_t get_byte_from_bits(const uint8_t *src, int address, int nb_bits)
1945
- {
1946
- int i;
1947
- uint8_t value = 0;
1948
-
1949
- if (nb_bits > 8) {
1950
- printf("Error: nb_bits is too big\n");
1951
- nb_bits = 8;
1952
- }
1953
-
1954
- for (i=0; i < nb_bits; i++) {
1955
- value |= (src[address+i] << i);
1956
- }
1957
-
1958
- return value;
1959
- }