forked from mtconnect/adapter
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmodbus.c
executable file
·2089 lines (1795 loc) · 73.3 KB
/
modbus.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright © 2001-2008 Stéphane Raimbault <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser Public License for more details.
*
* You should have received a copy of the GNU Lesser Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/*
The library is designed to send and receive data from a device that
communicate via the Modbus protocol.
The function names used are inspired by the Modicon Modbus Protocol
Reference Guide which can be obtained from Schneider at
www.schneiderautomation.com.
Documentation:
http://www.easysw.com/~mike/serial/serial.html
http://copyleft.free.fr/wordpress/index.php/libmodbus/
*/
#include <internal.hpp>
#ifndef WIN32
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdint.h>
#include <termios.h>
#include <sys/time.h>
#include <unistd.h>
#include <errno.h>
#include <limits.h>
#include <fcntl.h>
/* TCP */
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <netinet/tcp.h>
#include <arpa/inet.h>
#else
#include <tchar.h>
#endif
#include "modbus.h"
#define UNKNOWN_ERROR_MSG "Not defined in modbus specification"
/* This structure reduces the number of params in functions and so
* optimizes the speed of execution (~ 37%). */
typedef struct {
int slave;
int function;
int t_id;
} sft_t;
static const uint8_t NB_TAB_ERROR_MSG = 12;
static const char *TAB_ERROR_MSG[] = {
/* 0x00 */ UNKNOWN_ERROR_MSG,
/* 0x01 */ "Illegal function code",
/* 0x02 */ "Illegal data address",
/* 0x03 */ "Illegal data value",
/* 0x04 */ "Slave device or server failure",
/* 0x05 */ "Acknowledge",
/* 0x06 */ "Slave device or server busy",
/* 0x07 */ "Negative acknowledge",
/* 0x08 */ "Memory parity error",
/* 0x09 */ UNKNOWN_ERROR_MSG,
/* 0x0A */ "Gateway path unavailable",
/* 0x0B */ "Target device failed to respond"
};
/* Table of CRC values for high-order byte */
static uint8_t table_crc_hi[] = {
0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0,
0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41,
0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0,
0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40,
0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1,
0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41,
0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1,
0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41,
0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0,
0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40,
0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1,
0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40,
0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0,
0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40,
0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0,
0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40,
0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0,
0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41,
0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0,
0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41,
0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0,
0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40,
0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1,
0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41,
0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0,
0x80, 0x41, 0x00, 0xC1, 0x81, 0x40
};
/* Table of CRC values for low-order byte */
static uint8_t table_crc_lo[] = {
0x00, 0xC0, 0xC1, 0x01, 0xC3, 0x03, 0x02, 0xC2, 0xC6, 0x06,
0x07, 0xC7, 0x05, 0xC5, 0xC4, 0x04, 0xCC, 0x0C, 0x0D, 0xCD,
0x0F, 0xCF, 0xCE, 0x0E, 0x0A, 0xCA, 0xCB, 0x0B, 0xC9, 0x09,
0x08, 0xC8, 0xD8, 0x18, 0x19, 0xD9, 0x1B, 0xDB, 0xDA, 0x1A,
0x1E, 0xDE, 0xDF, 0x1F, 0xDD, 0x1D, 0x1C, 0xDC, 0x14, 0xD4,
0xD5, 0x15, 0xD7, 0x17, 0x16, 0xD6, 0xD2, 0x12, 0x13, 0xD3,
0x11, 0xD1, 0xD0, 0x10, 0xF0, 0x30, 0x31, 0xF1, 0x33, 0xF3,
0xF2, 0x32, 0x36, 0xF6, 0xF7, 0x37, 0xF5, 0x35, 0x34, 0xF4,
0x3C, 0xFC, 0xFD, 0x3D, 0xFF, 0x3F, 0x3E, 0xFE, 0xFA, 0x3A,
0x3B, 0xFB, 0x39, 0xF9, 0xF8, 0x38, 0x28, 0xE8, 0xE9, 0x29,
0xEB, 0x2B, 0x2A, 0xEA, 0xEE, 0x2E, 0x2F, 0xEF, 0x2D, 0xED,
0xEC, 0x2C, 0xE4, 0x24, 0x25, 0xE5, 0x27, 0xE7, 0xE6, 0x26,
0x22, 0xE2, 0xE3, 0x23, 0xE1, 0x21, 0x20, 0xE0, 0xA0, 0x60,
0x61, 0xA1, 0x63, 0xA3, 0xA2, 0x62, 0x66, 0xA6, 0xA7, 0x67,
0xA5, 0x65, 0x64, 0xA4, 0x6C, 0xAC, 0xAD, 0x6D, 0xAF, 0x6F,
0x6E, 0xAE, 0xAA, 0x6A, 0x6B, 0xAB, 0x69, 0xA9, 0xA8, 0x68,
0x78, 0xB8, 0xB9, 0x79, 0xBB, 0x7B, 0x7A, 0xBA, 0xBE, 0x7E,
0x7F, 0xBF, 0x7D, 0xBD, 0xBC, 0x7C, 0xB4, 0x74, 0x75, 0xB5,
0x77, 0xB7, 0xB6, 0x76, 0x72, 0xB2, 0xB3, 0x73, 0xB1, 0x71,
0x70, 0xB0, 0x50, 0x90, 0x91, 0x51, 0x93, 0x53, 0x52, 0x92,
0x96, 0x56, 0x57, 0x97, 0x55, 0x95, 0x94, 0x54, 0x9C, 0x5C,
0x5D, 0x9D, 0x5F, 0x9F, 0x9E, 0x5E, 0x5A, 0x9A, 0x9B, 0x5B,
0x99, 0x59, 0x58, 0x98, 0x88, 0x48, 0x49, 0x89, 0x4B, 0x8B,
0x8A, 0x4A, 0x4E, 0x8E, 0x8F, 0x4F, 0x8D, 0x4D, 0x4C, 0x8C,
0x44, 0x84, 0x85, 0x45, 0x87, 0x47, 0x46, 0x86, 0x82, 0x42,
0x43, 0x83, 0x41, 0x81, 0x80, 0x40
};
/* Treats errors and flush or close connection if necessary */
static void error_treat(modbus_param_t *mb_param, int code, const char *string)
{
printf("\nERROR %s (%d)\n", string, code);
if (mb_param->error_handling == FLUSH_OR_RECONNECT_ON_ERROR) {
switch (code) {
case ILLEGAL_DATA_VALUE:
case ILLEGAL_DATA_ADDRESS:
case ILLEGAL_FUNCTION:
break;
default:
if (mb_param->type_com == RTU) {
#ifndef WIN32
tcflush(mb_param->sock, TCIOFLUSH);
#endif
} else {
modbus_close(mb_param);
modbus_connect(mb_param);
}
}
}
}
/* Computes the length of the expected response */
static unsigned int compute_response_length(modbus_param_t *mb_param,
uint8_t *query)
{
int resp_length;
int offset;
offset = mb_param->header_length;
switch (query[offset + 1]) {
case FC_READ_COIL_STATUS:
case FC_READ_INPUT_STATUS: {
/* Header + nb values (code from force_multiple_coils) */
int nb = (query[offset + 4] << 8) | query[offset + 5];
resp_length = 3 + (nb / 8) + ((nb % 8) ? 1 : 0);
}
break;
case FC_READ_HOLDING_REGISTERS:
case FC_READ_INPUT_REGISTERS:
/* Header + 2 * nb values */
resp_length = 3 + 2 * (query[offset + 4] << 8 |
query[offset + 5]);
break;
case FC_READ_EXCEPTION_STATUS:
resp_length = 4;
break;
default:
resp_length = 6;
}
resp_length += offset + mb_param->checksum_length;
return resp_length;
}
/* Builds a RTU query header */
static int build_query_basis_rtu(int slave, int function,
int start_addr, int nb,
uint8_t *query)
{
query[0] = slave;
query[1] = function;
query[2] = start_addr >> 8;
query[3] = start_addr & 0x00ff;
query[4] = nb >> 8;
query[5] = nb & 0x00ff;
return PRESET_QUERY_LENGTH_RTU;
}
/* Builds a TCP query header */
static int build_query_basis_tcp(int slave, int function,
int start_addr, int nb,
uint8_t *query)
{
/* Extract from MODBUS Messaging on TCP/IP Implementation
Guide V1.0b (page 23/46):
The transaction identifier is used to associate the future
response with the request. So, at a time, on a TCP
connection, this identifier must be unique.
*/
static uint16_t t_id = 0;
/* Transaction ID */
if (t_id < UINT16_MAX)
t_id++;
else
t_id = 0;
query[0] = t_id >> 8;
query[1] = t_id & 0x00ff;
/* Protocol Modbus */
query[2] = 0;
query[3] = 0;
/* Length to fix later with set_query_length_tcp (4 and 5) */
query[6] = slave;
query[7] = function;
query[8] = start_addr >> 8;
query[9] = start_addr & 0x00ff;
query[10] = nb >> 8;
query[11] = nb & 0x00ff;
return PRESET_QUERY_LENGTH_TCP;
}
static int build_query_basis(modbus_param_t *mb_param, int slave,
int function, int start_addr,
int nb, uint8_t *query)
{
if (mb_param->type_com == RTU)
return build_query_basis_rtu(slave, function, start_addr,
nb, query);
else
return build_query_basis_tcp(slave, function, start_addr,
nb, query);
}
/* Builds a RTU response header */
static int build_response_basis_rtu(sft_t *sft, uint8_t *response)
{
response[0] = sft->slave;
response[1] = sft->function;
return PRESET_RESPONSE_LENGTH_RTU;
}
/* Builds a TCP response header */
static int build_response_basis_tcp(sft_t *sft, uint8_t *response)
{
/* Extract from MODBUS Messaging on TCP/IP Implementation
Guide V1.0b (page 23/46):
The transaction identifier is used to associate the future
response with the request. */
response[0] = sft->t_id >> 8;
response[1] = sft->t_id & 0x00ff;
/* Protocol Modbus */
response[2] = 0;
response[3] = 0;
/* Length to fix later with set_message_length_tcp (4 and 5) */
response[6] = sft->slave;
response[7] = sft->function;
return PRESET_RESPONSE_LENGTH_TCP;
}
static int build_response_basis(modbus_param_t *mb_param, sft_t *sft,
uint8_t *response)
{
if (mb_param->type_com == RTU)
return build_response_basis_rtu(sft, response);
else
return build_response_basis_tcp(sft, response);
}
/* Sets the length of TCP message in the message (query and response) */
void set_message_length_tcp(uint8_t *msg, int msg_length)
{
/* Substract the header length to the message length */
int mbap_length = msg_length - 6;
msg[4] = mbap_length >> 8;
msg[5] = mbap_length & 0x00FF;
}
/* Fast CRC */
static uint16_t crc16(uint8_t *buffer, uint16_t buffer_length)
{
uint8_t crc_hi = 0xFF; /* high CRC byte initialized */
uint8_t crc_lo = 0xFF; /* low CRC byte initialized */
unsigned int i; /* will index into CRC lookup */
/* pass through message buffer */
while (buffer_length--) {
i = crc_hi ^ *buffer++; /* calculate the CRC */
crc_hi = crc_lo ^ table_crc_hi[i];
crc_lo = table_crc_lo[i];
}
return (crc_hi << 8 | crc_lo);
}
/* If CRC is correct returns 0 else returns INVALID_CRC */
static int check_crc16(modbus_param_t *mb_param,
uint8_t *msg,
const int msg_length)
{
int ret;
uint16_t crc_calc;
uint16_t crc_received;
crc_calc = crc16(msg, msg_length - 2);
crc_received = (msg[msg_length - 2] << 8) | msg[msg_length - 1];
/* Check CRC of msg */
if (crc_calc == crc_received) {
ret = 0;
} else {
char s_error[64];
sprintf(s_error,
"invalid crc received %0X - crc_calc %0X",
crc_received, crc_calc);
ret = INVALID_CRC;
error_treat(mb_param, ret, s_error);
}
return ret;
}
/* Sends a query/response over a serial or a TCP communication */
static int modbus_send(modbus_param_t *mb_param, uint8_t *query,
int query_length)
{
int ret;
uint16_t s_crc;
int i;
if (mb_param->type_com == RTU) {
s_crc = crc16(query, query_length);
query[query_length++] = s_crc >> 8;
query[query_length++] = s_crc & 0x00FF;
} else {
set_message_length_tcp(query, query_length);
}
if (mb_param->debug) {
for (i = 0; i < query_length; i++)
printf("[%.2X]", query[i]);
printf("\n");
}
if (mb_param->type_com == RTU)
{
#ifdef WIN32
int bytes_written;
if(WriteFile(mb_param->fd, query, query_length, &bytes_written, NULL) )
{
ret = bytes_written;
}
else
{
int errors;
COMSTAT status;
ClearCommError(mb_param->fd,&errors,&status);
ret = -1;
}
#else
ret = (int) write(mb_param->fd, query, query_length);
#endif
}
else
ret = (int) send(mb_param->sock, query, query_length, 0);
/* Return the number of bytes written (0 to n)
or PORT_SOCKET_FAILURE on error */
if ((ret == -1) || (ret != query_length)) {
ret = PORT_SOCKET_FAILURE;
error_treat(mb_param, ret, "Write port/socket failure");
}
return ret;
}
/* Computes the length of the header following the function code */
static uint8_t compute_query_length_header(int function)
{
int length;
if (function <= FC_FORCE_SINGLE_COIL ||
function == FC_PRESET_SINGLE_REGISTER)
/* Read and single write */
length = 4;
else if (function == FC_FORCE_MULTIPLE_COILS ||
function == FC_PRESET_MULTIPLE_REGISTERS)
/* Multiple write */
length = 5;
else
length = 0;
return length;
}
/* Computes the length of the data to write in the query */
static int compute_query_length_data(modbus_param_t *mb_param, uint8_t *msg)
{
int function = msg[mb_param->header_length + 1];
int length;
if (function == FC_FORCE_MULTIPLE_COILS ||
function == FC_PRESET_MULTIPLE_REGISTERS)
length = msg[mb_param->header_length + 6];
else
length = 0;
length += mb_param->checksum_length;
return length;
}
#ifdef WIN32
#define WAIT_DATA()
#else
#define WAIT_DATA() \
{ \
while ((select_ret = select(1, &rfds, NULL, NULL, &tv)) == -1) { \
if (errno == EINTR) { \
printf("A non blocked signal was caught\n"); \
/* Necessary after an error */ \
FD_ZERO(&rfds); \
FD_SET(mb_param->sock, &rfds); \
} else { \
error_treat(mb_param, SELECT_FAILURE, "Select failure"); \
return SELECT_FAILURE; \
} \
} \
\
if (select_ret == 0) { \
/* Call to error_treat is done later to manage exceptions */ \
return COMM_TIME_OUT; \
} \
}
#endif
/* Waits a reply from a modbus slave or a query from a modbus master.
This function blocks for timeout seconds if there is no reply.
In
- msg_length_computed must be set to MSG_LENGTH_UNDEFINED if undefined
Out
- msg is an array of uint8_t to receive the message
- p_msg_length, the variable is assigned to the number of
characters received. This value won't be greater than
msg_length_computed.
Returns 0 in success or a negative value if an error occured.
*/
static int receive_msg(modbus_param_t *mb_param,
int msg_length_computed,
uint8_t *msg, int *p_msg_length)
{
int select_ret;
int read_ret;
fd_set rfds;
struct timeval tv;
int length_to_read;
uint8_t *p_msg;
enum { FUNCTION, BYTE, COMPLETE };
int state;
if (mb_param->debug) {
if (msg_length_computed == MSG_LENGTH_UNDEFINED)
printf("Waiting for a message...\n");
else
printf("Waiting for a message (%d bytes)...\n",
msg_length_computed);
}
/* Add a file descriptor to the set */
FD_ZERO(&rfds);
FD_SET(mb_param->sock, &rfds);
if (msg_length_computed == MSG_LENGTH_UNDEFINED) {
/* Wait for a message */
tv.tv_sec = 60;
tv.tv_usec = 0;
/* The message length is undefined (query receiving) so
* we need to analyse the message step by step.
* At the first step, we want to reach the function
* code because all packets have that information. */
msg_length_computed = mb_param->header_length + 2;
state = FUNCTION;
} else {
tv.tv_sec = 0;
tv.tv_usec = TIME_OUT_BEGIN_OF_TRAME;
state = COMPLETE;
}
length_to_read = msg_length_computed;
select_ret = 1;
WAIT_DATA();
/* Initialize the readin the message */
(*p_msg_length) = 0;
p_msg = msg;
while (select_ret) {
if (mb_param->type_com == RTU)
{
#ifdef WIN32
int bytes_read;
if(ReadFile(mb_param->fd, p_msg, length_to_read, &bytes_read, NULL) ) {
read_ret = bytes_read;
}
else
{
int errors;
COMSTAT status;
ClearCommError(mb_param->fd, &errors, &status);
read_ret = -1;
}
#else
read_ret = read(mb_param->fd, p_msg, length_to_read);
#endif
}
else
read_ret = recv(mb_param->sock, p_msg, length_to_read, 0);
if (read_ret == 0) {
printf("Connection closed\n");
return CONNECTION_CLOSED;
} else if (read_ret < 0) {
/* The only negative possible value is -1 */
error_treat(mb_param, PORT_SOCKET_FAILURE,
"Read port/socket failure");
return PORT_SOCKET_FAILURE;
}
/* Sums bytes received */
(*p_msg_length) += read_ret;
/* Display the hex code of each character received */
if (mb_param->debug) {
int i;
for (i=0; i < read_ret; i++)
printf("<%.2X>", p_msg[i]);
}
if ((*p_msg_length) < msg_length_computed) {
/* Message incomplete */
length_to_read = msg_length_computed - (*p_msg_length);
} else {
switch (state) {
case FUNCTION:
/* Function code position */
length_to_read = compute_query_length_header(msg[mb_param->header_length + 1]);
msg_length_computed += length_to_read;
/* It's useless to check
p_msg_length_computed value in this
case (only defined values are used). */
state = BYTE;
break;
case BYTE:
length_to_read = compute_query_length_data(mb_param, msg);
msg_length_computed += length_to_read;
if (msg_length_computed > MAX_MESSAGE_LENGTH) {
error_treat(mb_param, TOO_MANY_DATA, "Too many data");
return TOO_MANY_DATA;
}
state = COMPLETE;
break;
case COMPLETE:
length_to_read = 0;
break;
}
}
/* Moves the pointer to receive other data */
p_msg = &(p_msg[read_ret]);
if (length_to_read > 0) {
/* If no character at the buffer wait
TIME_OUT_END_OF_TRAME before to generate an error. */
tv.tv_sec = 0;
tv.tv_usec = TIME_OUT_END_OF_TRAME;
WAIT_DATA();
} else {
/* All chars are received */
select_ret = FALSE;
}
}
if (mb_param->debug)
printf("\n");
if (mb_param->type_com == RTU) {
check_crc16(mb_param, msg, (*p_msg_length));
}
/* OK */
return 0;
}
/* Receives the response and checks values (and checksum in RTU).
Returns:
- the number of values (bits or word) if success or the response
length if no value is returned
- less than 0 for exception errors
Note: all functions used to send or receive data with modbus return
these values. */
static int modbus_receive(modbus_param_t *mb_param,
uint8_t *query,
uint8_t *response)
{
int ret;
int response_length;
int response_length_computed;
int offset = mb_param->header_length;
response_length_computed = compute_response_length(mb_param, query);
ret = receive_msg(mb_param, response_length_computed,
response, &response_length);
if (ret == 0) {
/* GOOD RESPONSE */
int query_nb_value;
int response_nb_value;
/* The number of values is returned if it's corresponding
* to the query */
switch (response[offset + 1]) {
case FC_READ_COIL_STATUS:
case FC_READ_INPUT_STATUS:
/* Read functions, 8 values in a byte (nb
* of values in the query and byte count in
* the response. */
query_nb_value = (query[offset+4] << 8) + query[offset+5];
query_nb_value = (query_nb_value / 8) + ((query_nb_value % 8) ? 1 : 0);
response_nb_value = response[offset + 2];
break;
case FC_READ_HOLDING_REGISTERS:
case FC_READ_INPUT_REGISTERS:
/* Read functions 1 value = 2 bytes */
query_nb_value = (query[offset+4] << 8) + query[offset+5];
response_nb_value = (response[offset + 2] / 2);
break;
case FC_FORCE_MULTIPLE_COILS:
case FC_PRESET_MULTIPLE_REGISTERS:
/* N Write functions */
query_nb_value = (query[offset+4] << 8) + query[offset+5];
response_nb_value = (response[offset + 4] << 8) | response[offset + 5];
break;
case FC_REPORT_SLAVE_ID:
/* Report slave ID (bytes received) */
query_nb_value = response_nb_value = response_length;
break;
default:
/* 1 Write functions & others */
query_nb_value = response_nb_value = 1;
}
if (query_nb_value == response_nb_value) {
ret = response_nb_value;
} else {
char *s_error = malloc(64 * sizeof(char));
sprintf(s_error, "Quantity (%d) not corresponding to the query (%d)",
response_nb_value, query_nb_value);
ret = ILLEGAL_DATA_VALUE;
error_treat(mb_param, ILLEGAL_DATA_VALUE, s_error);
free(s_error);
}
} else if (ret == COMM_TIME_OUT) {
if (response_length == (offset + 3 + mb_param->checksum_length)) {
/* EXCEPTION CODE RECEIVED */
/* Optimization allowed because exception response is
the smallest trame in modbus protocol (3) so always
raise a timeout error */
/* CRC must be checked here (not done in receive_msg) */
if (mb_param->type_com == RTU) {
ret = check_crc16(mb_param, response, response_length);
if (ret != 0)
return ret;
}
/* Check for exception response.
0x80 + function is stored in the exception
response. */
if (0x80 + query[offset + 1] == response[offset + 1]) {
int exception_code = response[offset + 2];
// FIXME check test
if (exception_code < NB_TAB_ERROR_MSG) {
error_treat(mb_param, -exception_code,
TAB_ERROR_MSG[response[offset + 2]]);
/* RETURN THE EXCEPTION CODE */
/* Modbus error code is negative */
return -exception_code;
} else {
/* The chances are low to hit this
case but it can avoid a vicious
segfault */
char *s_error = malloc(64 * sizeof(char));
sprintf(s_error,
"Invalid exception code %d",
response[offset + 2]);
error_treat(mb_param, INVALID_EXCEPTION_CODE,
s_error);
free(s_error);
return INVALID_EXCEPTION_CODE;
}
}
/* If doesn't return previously, return as
TIME OUT here */
}
/* COMMUNICATION TIME OUT */
error_treat(mb_param, ret, "Communication time out");
return ret;
}
return ret;
}
static int response_io_status(int address, int nb,
uint8_t *tab_io_status,
uint8_t *response, int offset)
{
int shift = 0;
int byte = 0;
int i;
for (i = address; i < address+nb; i++) {
byte |= tab_io_status[i] << shift;
if (shift == 7) {
/* Byte is full */
response[offset++] = byte;
byte = shift = 0;
} else {
shift++;
}
}
if (shift != 0)
response[offset++] = byte;
return offset;
}
/* Build the exception response */
static int response_exception(modbus_param_t *mb_param, sft_t *sft,
int exception_code, uint8_t *response)
{
int response_length;
sft->function = sft->function + 0x80;
response_length = build_response_basis(mb_param, sft, response);
/* Positive exception code */
response[response_length++] = -exception_code;
return response_length;
}
/* Manages the received query.
Analyses the query and constructs a response.
If an error occurs, this function construct the response
accordingly.
*/
void modbus_manage_query(modbus_param_t *mb_param, const uint8_t *query,
int query_length, modbus_mapping_t *mb_mapping)
{
int offset = mb_param->header_length;
int slave = query[offset];
int function = query[offset+1];
uint16_t address = (query[offset+2] << 8) + query[offset+3];
uint8_t response[MAX_MESSAGE_LENGTH];
int resp_length = 0;
sft_t sft;
sft.slave = slave;
sft.function = function;
if (mb_param->type_com == TCP)
sft.t_id = (query[0] << 8) + query[1];
else
sft.t_id = 0;
switch (function) {
case FC_READ_COIL_STATUS: {
int nb = (query[offset+4] << 8) + query[offset+5];
if ((address + nb) > mb_mapping->nb_coil_status) {
printf("Illegal data address %0X in read_coil_status\n",
address + nb);
resp_length = response_exception(mb_param, &sft,
ILLEGAL_DATA_ADDRESS, response);
} else {
resp_length = build_response_basis(mb_param, &sft, response);
response[resp_length++] = (nb / 8) + ((nb % 8) ? 1 : 0);
resp_length = response_io_status(address, nb,
mb_mapping->tab_coil_status,
response, resp_length);
}
}
break;
case FC_READ_INPUT_STATUS: {
/* Similar to coil status (but too much arguments to use a
* function) */
int nb = (query[offset+4] << 8) + query[offset+5];
if ((address + nb) > mb_mapping->nb_input_status) {
printf("Illegal data address %0X in read_input_status\n",
address + nb);
resp_length = response_exception(mb_param, &sft,
ILLEGAL_DATA_ADDRESS, response);
} else {
resp_length = build_response_basis(mb_param, &sft, response);
response[resp_length++] = (nb / 8) + ((nb % 8) ? 1 : 0);
resp_length = response_io_status(address, nb,
mb_mapping->tab_input_status,
response, resp_length);
}
}
break;
case FC_READ_HOLDING_REGISTERS: {
int nb = (query[offset+4] << 8) + query[offset+5];
if ((address + nb) > mb_mapping->nb_holding_registers) {
printf("Illegal data address %0X in read_holding_registers\n",
address + nb);
resp_length = response_exception(mb_param, &sft,
ILLEGAL_DATA_ADDRESS, response);
} else {
int i;
resp_length = build_response_basis(mb_param, &sft, response);
response[resp_length++] = nb << 1;
for (i = address; i < address + nb; i++) {
response[resp_length++] = mb_mapping->tab_holding_registers[i] >> 8;
response[resp_length++] = mb_mapping->tab_holding_registers[i] & 0xFF;
}
}
}
break;
case FC_READ_INPUT_REGISTERS: {
/* Similar to holding registers (but too much arguments to use a
* function) */
int nb = (query[offset+4] << 8) + query[offset+5];
if ((address + nb) > mb_mapping->nb_input_registers) {
printf("Illegal data address %0X in read_input_registers\n",
address + nb);
resp_length = response_exception(mb_param, &sft,
ILLEGAL_DATA_ADDRESS, response);
} else {
int i;
resp_length = build_response_basis(mb_param, &sft, response);
response[resp_length++] = nb << 1;
for (i = address; i < address + nb; i++) {
response[resp_length++] = mb_mapping->tab_input_registers[i] >> 8;
response[resp_length++] = mb_mapping->tab_input_registers[i] & 0xFF;
}
}
}
break;
case FC_FORCE_SINGLE_COIL:
if (address >= mb_mapping->nb_coil_status) {
printf("Illegal data address %0X in force_singe_coil\n", address);
resp_length = response_exception(mb_param, &sft,
ILLEGAL_DATA_ADDRESS, response);
} else {
int data = (query[offset+4] << 8) + query[offset+5];
if (data == 0xFF00 || data == 0x0) {
mb_mapping->tab_coil_status[address] = (data) ? ON : OFF;
/* In RTU mode, the CRC is computed
and added to the query by modbus_send */
memcpy(response, query, query_length - mb_param->checksum_length);
resp_length = query_length;
} else {
printf("Illegal data value %0X in force_single_coil request at address %0X\n",
data, address);
resp_length = response_exception(mb_param, &sft,
ILLEGAL_DATA_VALUE, response);
}
}
break;
case FC_PRESET_SINGLE_REGISTER:
if (address >= mb_mapping->nb_holding_registers) {
printf("Illegal data address %0X in preset_holding_register\n", address);
resp_length = response_exception(mb_param, &sft,
ILLEGAL_DATA_ADDRESS, response);
} else {
int data = (query[offset+4] << 8) + query[offset+5];
mb_mapping->tab_holding_registers[address] = data;
memcpy(response, query, query_length - mb_param->checksum_length);
resp_length = query_length;
}
break;
case FC_FORCE_MULTIPLE_COILS: {
int nb = (query[offset+4] << 8) + query[offset+5];
if ((address + nb) > mb_mapping->nb_coil_status) {
printf("Illegal data address %0X in force_multiple_coils\n",
address + nb);
resp_length = response_exception(mb_param, &sft,
ILLEGAL_DATA_ADDRESS, response);
} else {
/* 6 = byte count, 7 = first byte of data */
set_bits_from_bytes(mb_mapping->tab_coil_status, address, nb, &query[offset + 7]);
resp_length = build_response_basis(mb_param, &sft, response);
/* 4 to copy the coil address (2) and the quantity of coils */
memcpy(response + resp_length, query + resp_length, 4);
resp_length += 4;
}
}
break;
case FC_PRESET_MULTIPLE_REGISTERS: {
int nb = (query[offset+4] << 8) + query[offset+5];
if ((address + nb) > mb_mapping->nb_holding_registers) {
printf("Illegal data address %0X in preset_multiple_registers\n",
address + nb);
resp_length = response_exception(mb_param, &sft,
ILLEGAL_DATA_ADDRESS, response);
} else {
int i, j;
for (i = address, j = 0; i < address + nb; i++, j += 2) {
/* 6 = byte count, 7 and 8 = first value */
mb_mapping->tab_holding_registers[i] =
(query[offset + 7 + j] << 8) + query[offset + 8 + j];
}
resp_length = build_response_basis(mb_param, &sft, response);
/* 4 to copy the address (2) and the no. of registers */
memcpy(response + resp_length, query + resp_length, 4);
resp_length += 4;
}
}
break;
case FC_READ_EXCEPTION_STATUS:
case FC_REPORT_SLAVE_ID:
printf("Not implemented\n");
break;
}
modbus_send(mb_param, response, resp_length);
}
/* Listens any message on a socket or file descriptor.
Returns:
- 0 if OK, or a negative error number if the request fails
- query, message received
- query_length, length in bytes of the message */
int modbus_listen(modbus_param_t *mb_param, uint8_t *query, int *query_length)
{