-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathmb_ascii.c
1769 lines (1463 loc) · 57.7 KB
/
mb_ascii.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 (c) 2002,2016 Mario de Sousa (msousa@fe.up.pt)
*
* This file is part of the Modbus library for Beremiz and matiec.
*
* This Modbus library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General 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
* General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this Modbus library. If not, see <http://www.gnu.org/licenses/>.
*
* This code is made available on the understanding that it will not be
* used in safety-critical situations without a full and competent review.
*/
#include <fcntl.h> /* File control definitions */
#include <stdio.h> /* Standard input/output */
#include <string.h>
#include <stdlib.h>
#include <termio.h> /* POSIX terminal control definitions */
#include <sys/time.h> /* Time structures for select() */
#include <unistd.h> /* POSIX Symbolic Constants */
#include <assert.h>
#include <errno.h> /* Error definitions */
#include <ctype.h>
#include <time.h> /* clock_gettime() */
#include <limits.h> /* required for INT_MAX */
#include "mb_layer1.h"
#include "mb_ascii_private.h"
/* #define DEBUG */ /* uncomment to see the data sent and received */
/************************************/
/** **/
/** Include common code... **/
/** **/
/************************************/
#include "mb_ds_util.h" /* data structures... */
#include "mb_time_util.h" /* time conversion routines... */
/**************************************************************/
/**************************************************************/
/**** ****/
/**** ****/
/**** Purpose and Formats ****/
/**** ****/
/**** ****/
/**************************************************************/
/**************************************************************/
/*
This file implements the ascii formating of the modbus protocol.
Many values, protocol related, are hardcoded into the code, as it
seems very unlikely this code will ever get re-used for anything
else but this specific protocol.
Modbus ASCII frames have no timing restrictions whatsoever, and
abide by the following format:
Header
------
size : 1 byte
value: ':' (i.e. '\0x3A')
Body
----
size : variable, multiple of 2
value: binary data converted to ascii format,
i.e. each binary data byte is converted into two ascii characters
representing the byte in hexadecimal. Allowable characters are
'0' to '9' and 'A' to 'D'
LRC
---
size : 2 bytes
value: Longitudinal Redundancy Check of data, excluding any headers, tails,
etc...
Tail
----
size : 2 bytes
value: 'CR' + 'LF' (i.e. '\0x0D' + '\0x0A')
*/
/**************************************************************/
/**************************************************************/
/**** ****/
/**** ****/
/**** Forward Declarations ****/
/**** and Defaults ****/
/**** ****/
/**************************************************************/
/**************************************************************/
typedef enum {fp_header, fp_body, fp_lrc, fp_tail, fp_done} frame_part_t;
/**************************************************************/
/**************************************************************/
/**** ****/
/**** ****/
/**** Local Utility functions... ****/
/**** ****/
/**** ****/
/**************************************************************/
/**************************************************************/
/*****************************************/
/** **/
/** lrc functions **/
/** **/
/*****************************************/
static inline void lrc_init(u8 *lrc) {
*lrc = 0;
}
static inline void lrc_add_single(u8 *lrc, u8 data) {
*lrc += data;
}
static inline void lrc_add_many(u8 *lrc, u8 *data, int count) {
for (; count > 0; count--, *lrc += *data++);
}
static inline void lrc_end(u8 *lrc) {
*lrc = 1 + ~(*lrc);
}
/**************************************/
/** **/
/** Initialise a struct termios **/
/** **/
/**************************************/
static int termios_init(struct termios *tios,
int baud,
int parity,
int data_bits,
int stop_bits) {
speed_t baud_rate;
if (tios == NULL)
return -1;
/* reset all the values... */
/* NOTE: the following are initialised later on...
tios->c_iflag = 0;
tios->c_oflag = 0;
tios->c_cflag = 0;
tios->c_lflag = 0;
*/
tios->c_line = 0;
/* The minimum number of characters that should be received
* to satisfy a call to read().
*/
tios->c_cc[VMIN ] = 0;
/* The maximum inter-arrival interval between two characters,
* in deciseconds.
*
* NOTE: we could use this to detect the end of RTU frames,
* but we prefer to use select() that has higher resolution,
* even though this higher resolution is most probably not
* supported, and the effective resolution is 10ms,
* one tenth of a decisecond.
*/
tios->c_cc[VTIME] = 0;
/* configure the input modes... */
tios->c_iflag = IGNBRK | /* ignore BREAK condition on input */
IGNPAR | /* ignore framing errors and parity errors */
IXANY; /* enable any character to restart output */
/* BRKINT Only active if IGNBRK is not set.
* generate SIGINT on BREAK condition,
* otherwise read BREAK as character \0.
* PARMRK Only active if IGNPAR is not set.
* replace bytes with parity errors with
* \377 \0, instead of \0.
* INPCK enable input parity checking
* ISTRIP strip off eighth bit
* IGNCR ignore carriage return on input
* INLCR only active if IGNCR is not set.
* translate newline to carriage return on input
* ICRNL only active if IGNCR is not set.
* translate carriage return to newline on input
* IUCLC map uppercase characters to lowercase on input
* IXON enable XON/XOFF flow control on output
* IXOFF enable XON/XOFF flow control on input
* IMAXBEL ring bell when input queue is full
*/
/* configure the output modes... */
tios->c_oflag = OPOST; /* enable implementation-defined output processing */
/* ONOCR don't output CR at column 0
* OLCUC map lowercase characters to uppercase on output
* ONLCR map NL to CR-NL on output
* OCRNL map CR to NL on output
* OFILL send fill characters for a delay, rather than
* using a timed delay
* OFDEL fill character is ASCII DEL. If unset, fill
* character is ASCII NUL
* ONLRET don't output CR
* NLDLY NL delay mask. Values are NL0 and NL1.
* CRDLY CR delay mask. Values are CR0, CR1, CR2, or CR3.
* TABDLY horizontal tab delay mask. Values are TAB0, TAB1,
* TAB2, TAB3, or XTABS. A value of XTABS expands
* tabs to spaces (with tab stops every eight columns).
* BSDLY backspace delay mask. Values are BS0 or BS1.
* VTDLY vertical tab delay mask. Values are VT0 or VT1.
* FFDLY form feed delay mask. Values are FF0 or FF1.
*/
/* configure the control modes... */
tios->c_cflag = CREAD | /* enable receiver. */
CLOCAL; /* ignore modem control lines */
/* HUPCL lower modem control lines after last process
* closes the device (hang up).
* CRTSCTS flow control (Request/Clear To Send).
*/
if (data_bits == 5) tios->c_cflag |= CS5;
else if (data_bits == 6) tios->c_cflag |= CS6;
else if (data_bits == 7) tios->c_cflag |= CS7;
else if (data_bits == 8) tios->c_cflag |= CS8;
else return -1;
if (stop_bits == 1) tios->c_cflag &=~ CSTOPB;
else if (stop_bits == 2) tios->c_cflag |= CSTOPB;
else return -1;
if(parity == 0) { /* none */
tios->c_cflag &=~ PARENB;
tios->c_cflag &=~ PARODD;
} else if(parity == 2) { /* even */
tios->c_cflag |= PARENB;
tios->c_cflag &=~ PARODD;
} else if(parity == 1) { /* odd */
tios->c_cflag |= PARENB;
tios->c_cflag |= PARODD;
} else return -1;
/* configure the local modes... */
tios->c_lflag = IEXTEN; /* enable implementation-defined input processing */
/* ISIG when any of the characters INTR, QUIT, SUSP, or DSUSP
* are received, generate the corresponding signal.
* ICANON enable canonical mode. This enables the special
* characters EOF, EOL, EOL2, ERASE, KILL, REPRINT,
* STATUS, and WERASE, and buffers by lines.
* ECHO echo input characters.
*/
/* Set the baud rate */
/* Must be done before reseting all the values to 0! */
switch(baud) {
case 110: baud_rate = B110; break;
case 300: baud_rate = B300; break;
case 600: baud_rate = B600; break;
case 1200: baud_rate = B1200; break;
case 2400: baud_rate = B2400; break;
case 4800: baud_rate = B4800; break;
case 9600: baud_rate = B9600; break;
case 19200: baud_rate = B19200; break;
case 38400: baud_rate = B38400; break;
case 57600: baud_rate = B57600; break;
case 115200: baud_rate = B115200; break;
default: return -1;
} /* switch() */
if ((cfsetispeed(tios, baud_rate) < 0) ||
(cfsetospeed(tios, baud_rate) < 0))
return -1;;
return 0;
}
/*****************************************/
/** **/
/** u8/ascii conversion functions **/
/** **/
/*****************************************/
/* Convert binary data to ascii format.
* Both xxx_data_lengths specify the available bytes in
* in the respective arrays.
*/
/* NOTE: this function is only called from a single location
* so we might just as well make it inline...
*/
static inline int bin_2_asc(u8 *bin_data, int bin_data_length,
u8 *asc_data, int asc_data_length) {
u8 nibble;
int count = 0;
u8 *last_bin_data = bin_data + bin_data_length;
/* we need L2_TO_ASC_CODING ascii bytes for each bin byte, therefore the
* '- (L2_TO_ASC_CODING - 1)'
*/
u8 *last_asc_data = asc_data + asc_data_length - (L2_TO_ASC_CODING - 1);
while ((bin_data < last_bin_data) &&
(asc_data < last_asc_data)) {
nibble = (*bin_data & 0xF0) >> 4;
*(asc_data++) = (nibble <= 9)?nibble + '0':nibble - 10 + 'A';
nibble = (*bin_data & 0x0F);
*(asc_data++) = (nibble <= 9)?nibble + '0':nibble - 10 + 'A';
count++;
bin_data++;
}
/* return number of bytes converted... */
return count;
}
/* Convert from lowercase to upper case. */
/* It probably does not make sense calling the generic toupper()
* whose functionality depends on the current locale.
* Our own specific function is most probably much faster...
*/
static inline u8 local_toupper(u8 val) {
if ((val >= 'a') && (val <= 'z'))
return val - 'a' + 'A';
return val;
}
/* Convert ascii data to bin format.
* *asc_data must be a two byte array.
*
* If a non-ascii character is found, returns -1
*/
/* NOTE: this function is only called from a single location
* so we might just as well make it inline...
*/
static inline int asc_2_bin(u8 *asc_data, u8 *bin_data) {
if ((isxdigit(asc_data[0]) == 0) ||
(isxdigit(asc_data[1]) == 0))
return -1;
asc_data[0] = local_toupper(asc_data[0]);
asc_data[1] = local_toupper(asc_data[1]);
/* hi */ *(bin_data) = ((asc_data[0] <= '9')?
(asc_data[0] - '0'):(asc_data[0] - 'A' + 10)) * 0x10;
/* lo */ *(bin_data) += (asc_data[1] <= '9')?
(asc_data[1] - '0'):(asc_data[1] - 'A' + 10);
return 0;
}
/************************************/
/** **/
/** A data structure - send buffer **/
/** **/
/************************************/
/* data structure used to store the data to be sent in ascii format. */
/* The binary data is converted into ascii format before transmission. The
* frame is not converted as a single whole, but is rather done in chunks.
* The size of the chunks depends on the data size of the send_buffer.
*
* A lrc variable keeps a tab on the current value of the lrc as the data
* is being converted.
*
* Three special functions add the header, lrc and tail to the ascii frame.
*/
/* NOTE: The algorithms in the insert functions require a minimum buffer
* size to work correctly...
*/
#define SEND_BUF_MIN_LENGTH ASC_FRAME_MIN_ELE_LENGTH
typedef struct {
lb_buf_t data_buf;
u8 lrc; /* the current value of the lrc, in binary format */
} send_buf_t;
/* A small auxiliary function... */
static inline u8 *send_buf_init(send_buf_t *buf, int size, int max_data_start) {
/* The algorithms in other functions require a minimum size
* to work correctly...
*/
if (size < SEND_BUF_MIN_LENGTH)
return NULL;
lrc_init(&buf->lrc);
return lb_init(&buf->data_buf, size, max_data_start);
}
/* A small auxiliary function... */
static inline void send_buf_done(send_buf_t *buf) {
lb_done(&buf->data_buf);
}
/* A small auxiliary function... */
static inline void send_buf_reset(send_buf_t *buf) {
lrc_init(&buf->lrc);
lb_data_purge_all(&buf->data_buf);
}
/* A small auxiliary function... */
static inline int send_buf_data_count(send_buf_t *buf) {
return lb_data_count(&buf->data_buf);
}
/* A small auxiliary function... */
static inline int send_buf_free_count(send_buf_t *buf) {
return lb_free_count(&buf->data_buf);
}
/* A small auxiliary function... */
static inline u8 *send_buf_data(send_buf_t *buf) {
return lb_data(&buf->data_buf);
}
/* A small auxiliary function... */
static inline u8 *send_buf_free(send_buf_t *buf) {
return lb_free(&buf->data_buf);
}
/* A small auxiliary function... */
static inline int send_buf_data_add(send_buf_t *buf, u8 *data, int data_count) {
int res = bin_2_asc(data, data_count, send_buf_free(buf), send_buf_free_count(buf));
if (res <=0) return res;
lb_data_add(&buf->data_buf, L2_TO_ASC_CODING * res);
lrc_add_many(&buf->lrc, data, res);
return res;
}
/* A small auxiliary function... */
static inline void send_buf_data_purge(send_buf_t *buf, int count) {
lb_data_purge(&buf->data_buf, count);
}
/* A small auxiliary function... */
static inline void send_buf_data_purge_all(send_buf_t *buf) {
lb_data_purge_all(&buf->data_buf);
}
/* A small auxiliary function... */
static inline int send_buf_lrc_append(send_buf_t *buf) {
#if ASC_FRAME_LRC_LENGTH != 2
#error Code assumes LRC length of 2 bytes, but ASC_FRAME_LRC_LENGTH != 2
#endif
if (lb_free_count(&buf->data_buf) < ASC_FRAME_LRC_LENGTH)
return -1;
lrc_end(&buf->lrc);
bin_2_asc(&buf->lrc, sizeof(buf->lrc),
lb_free(&buf->data_buf), ASC_FRAME_LRC_LENGTH);
lb_data_add(&buf->data_buf, ASC_FRAME_LRC_LENGTH);
return 0;
}
static inline int send_buf_header_append(send_buf_t *buf) {
#if ASC_FRAME_HEADER_LENGTH != 1
#error Code assumes HEADER length of 1 bytes, but ASC_FRAME_HEADER_LENGTH != 1
#endif
if (lb_free_count(&buf->data_buf) < ASC_FRAME_HEADER_LENGTH)
return -1;
/* add the ':' frame header */
*lb_free(&buf->data_buf) = ASC_FRAME_HEADER;
lb_data_add(&buf->data_buf, ASC_FRAME_HEADER_LENGTH);
return 0;
}
static inline int send_buf_tail_append(send_buf_t *buf) {
#if ASC_FRAME_TAIL_LENGTH != 2
#error Code assumes TAIL length of 2 bytes, but ASC_FRAME_TAIL_LENGTH != 2
#endif
if (lb_free_count(&buf->data_buf) < ASC_FRAME_TAIL_LENGTH)
return -1;
/* add the CR+LF frame delimiter */
lb_free(&buf->data_buf)[0] = ASC_FRAME_TAIL_0;
lb_free(&buf->data_buf)[1] = ASC_FRAME_TAIL_1;
lb_data_add(&buf->data_buf, ASC_FRAME_TAIL_LENGTH);
return 0;
}
/************************************/
/** **/
/** A data structure - recv buffer **/
/** **/
/************************************/
/* data structure used to store the data received from the bus. */
/* The ascii data received from the bus is added to the buffer, and is
* dynamically converted to binary format. Once a valid frame has been
* converted, conversion stops until this valid frame is deleted/purged.
*/
/* NOTE: The algorithms in the insert functions require a minimum buffer
* size to work correctly...
*/
#define RECV_BUF_MIN_LENGTH ASC_FRAME_MIN_ELE_LENGTH
#define RECV_BUF_BIN_BUF_SIZE (MAX_L2_FRAME_LENGTH + \
ASC_FRAME_LRC_LENGTH / L2_TO_ASC_CODING)
typedef struct {
lb_buf_t asc_data_buf;
u8 bin_data_buf[RECV_BUF_BIN_BUF_SIZE];
int bin_data_free_ofs;
frame_part_t frame_part;
u8 lrc; /* the current value of the lrc, in binary format */
u8 lrc_1; /* the previous value of the lrc... */
/* NOTE: We do a running conversion between ascii and binary format,
* i.e. we start converting from ascii to binary before we
* have received the complete ascii frame. This means that
* we also do a running computation of our local version of
* the frame lrc.
* The lrc, transmitted at the end of the ascii frame,
* but before the frame tail, also gets converted to binary
* before we get a chance to realize that it is the lrc value,
* and should therefore not be taken into account when computing
* our local version of the lrc.
* So we keep the previous value of the running lrc, and use
* that to confirm whether we have a valid frame.
*/
} recv_buf_t;
/* A small auxiliary function... */
static inline u8 *recv_buf_init(recv_buf_t *buf, int size, int max_data_start) {
/* The algorithms in other functions require a minimum size
* to work correctly...
*/
if (size < RECV_BUF_MIN_LENGTH)
return NULL;
lrc_init(&buf->lrc);
buf->bin_data_free_ofs = 0;
buf->frame_part = fp_header;
return lb_init(&buf->asc_data_buf, size, max_data_start);
}
/* A small auxiliary function... */
static inline void recv_buf_done(recv_buf_t *buf) {
lb_done(&buf->asc_data_buf);
}
/* A small auxiliary function... */
static inline void recv_buf_reset(recv_buf_t *buf) {
lrc_init(&buf->lrc);
buf->bin_data_free_ofs = 0;
buf->frame_part = fp_header;
lb_data_purge_all(&buf->asc_data_buf);
}
/* A small auxiliary function... */
static inline u8 *recv_buf_data(recv_buf_t *buf) {
return lb_data(&buf->asc_data_buf);
}
/* A small auxiliary function... */
static inline u8 *recv_buf_free(recv_buf_t *buf) {
return lb_free(&buf->asc_data_buf);
}
/* The function that really does all the conversion work... */
/* It finds frame limits, converts the data into binary format,
* and checks for correct lrc in the received frame.
*/
/* NOTE: called indirectly from various locations! Do NOT inline! */
static void recv_buf_data_parse(recv_buf_t *buf) {
int count;
u8 *data;
data = lb_data(&buf->asc_data_buf);
count = lb_data_count(&buf->asc_data_buf);
/* NOTE: We need at least ASC_FRAME_MIN_ELE_LENGTH bytes to
* to be able to find that element of minimum length
*/
while ((count >= ASC_FRAME_MIN_ELE_LENGTH) && (buf->frame_part != fp_done)) {
/* Check for frame header... */
/* The following few lines of code assume that ASC_FRAME_HEADER_LENGTH is 1! */
#if ASC_FRAME_HEADER_LENGTH != 1
#error The code is written in such a way that can only handle ASC_FRAME_HEADER_LENGTH == 1
#endif
if (data[0] == ASC_FRAME_HEADER) {
/* found the beginning of a frame...
* Even if we were previously converting a frame without errors,
* if we receive a new frame header we discard the previous
* frame that went unfinished!
*/
data += ASC_FRAME_HEADER_LENGTH;
count -= ASC_FRAME_HEADER_LENGTH;
buf->frame_part = fp_body;
lrc_init(&buf->lrc);
buf->bin_data_free_ofs = 0;
continue;
}
/* Check for frame tail... */
/*
* Note that the while() condition guarantees that we have at least
* two ascii bytes to handle.
*/
/* The following few lines of code assume that ASC_FRAME_TAIL_LENGTH is 2! */
#if ASC_FRAME_TAIL_LENGTH != 2
#error The code is written in such a way that can only handle ASC_FRAME_TAIL_LENGTH == 2
#endif
if ((data[0] == ASC_FRAME_TAIL_0) &&
(data[1] == ASC_FRAME_TAIL_1)) {
/* end of binary data... */
data += ASC_FRAME_TAIL_LENGTH;
count -= ASC_FRAME_TAIL_LENGTH;
/* let's check the lrc... */
if (buf->bin_data_free_ofs <= 0)
/* we have reached the end of a frame that did not include
* any binary data, not even the lrc value itself!
*/
goto frame_error;
/* Remember that we do not use the most recent lrc value, as this
* incorrectly includes the ascii bytes in the frame that code the
* frame's lrc. (pls read the note in the recv_but_t typedef)
*/
/* The following few lines of code assume that
* (ASC_FRAME_LRC_LENGTH / L2_TO_ASC_CODING) is 1!
*/
#if L2_TO_ASC_CODING != ASC_FRAME_LRC_LENGTH
#error The code is written in such a way that can only handle L2_TO_ASC_CODING == ASC_FRAME_LRC_LENGTH
#endif
lrc_end(&(buf->lrc_1));
if (buf->lrc_1 == buf->bin_data_buf[buf->bin_data_free_ofs-1]) {
/* we have received a correct frame... */
buf->frame_part = fp_done;
continue;
} else {
/* we have found a frame with an lrc error */
goto frame_error;
}
}
if (buf->frame_part == fp_header) {
/* we are searching for beginning of a frame...
* but we did not find it in the previous condition!
* We continue looking in the next ascii byte
*/
data++;
count--;
continue;
}
if (buf->frame_part == fp_body) {
/* we have previously found the beginning of a frame,
* and are now converting the body into binary format...
*
* Note that the while() condition guarantees that we have at least
* two ascii bytes to convert into binary format.
*/
/* this is normal data... let's convert... */
if (asc_2_bin(data, buf->bin_data_buf + buf->bin_data_free_ofs) < 0)
/* error converting from ascii to binary.
* This must be due to an invalid ascii character in the ascii data.
* We discard the current frame...
*
* Note that we *do not* increment the data pointer,
* nor do we decrement the count variable. One of the ascii bytes could
* be the begining of a new valid frame, and we don't want to skip it!
*/
goto frame_error;
buf->lrc_1 = buf->lrc;
lrc_add_single(&(buf->lrc), *(buf->bin_data_buf + buf->bin_data_free_ofs));
data += L2_TO_ASC_CODING;
count -= L2_TO_ASC_CODING;
if (++(buf->bin_data_free_ofs) >= RECV_BUF_BIN_BUF_SIZE)
/* Whoops, this shouldn't be hapening!
* The frame we are receiving is larger than the alocated buffer!
* Our only alternative is to discard the frame
* we are currently receiving...
*/
goto frame_error;
continue;
}
/* if none of the above, then it must be some transmission error */
/* Actually, the code will never fall through since if we are in this loop,
* (frame_part == header) || (frame_part == body) is always true!
*/
data++;
count--;
frame_error:
lrc_init(&buf->lrc);
buf->bin_data_free_ofs = 0;
buf->frame_part = fp_header;
} /* while () */
lb_data_purge(&buf->asc_data_buf, lb_data_count(&buf->asc_data_buf) - count);
}
/* A small auxiliary function... */
static inline void recv_buf_search_frame(recv_buf_t *buf) {
if (buf->frame_part != fp_done)
recv_buf_data_parse(buf);
}
/* add ascii format data to buffer */
static inline void recv_buf_data_add(recv_buf_t *buf, int count) {
lb_data_add(&buf->asc_data_buf, count);
}
/* A small auxiliary function... */
static inline int recv_buf_data_count(recv_buf_t *buf) {
return lb_data_count(&buf->asc_data_buf);
}
/* A small auxiliary function... */
static inline int recv_buf_free_count(recv_buf_t *buf) {
return lb_free_count(&buf->asc_data_buf);
}
/* Return pointer to frame, if a valid frame is available */
static inline u8 *recv_buf_frame(recv_buf_t *buf) {
recv_buf_search_frame(buf);
if (buf->frame_part == fp_done)
/* we have found a frame...! */
return buf->bin_data_buf;
/* no frame... */
return NULL;
}
/* Return number of bytes in frame, if a valid frame is available */
static inline int recv_buf_frame_count(recv_buf_t *buf) {
recv_buf_search_frame(buf);
if (buf->frame_part == fp_done)
/* we have found a frame...! */
return buf->bin_data_free_ofs - ASC_FRAME_LRC_LENGTH/L2_TO_ASC_CODING;
/* no frame... */
return -1;
}
/* Delete valid binary format frame! */
static inline void recv_buf_frame_purge(recv_buf_t *buf) {
/* NOTE: we only delete valid frames!!
* Partially converted frames are not deleted, the
* remaining bytes may be received later!
*/
if (buf->frame_part == fp_done) {
buf->frame_part = fp_header;
buf->bin_data_free_ofs = 0;
}
}
/************************************/
/** **/
/** A data structure - nd entry **/
/** **/
/************************************/
/* NOTE: nd = node descriptor */
typedef struct {
/* The file descriptor associated with this node */
/* NOTE: if the node is not yet in use, i.e. if the node is free,
* then fd will be set to -1
*/
int fd;
struct timeval time_15_char_;
/* Modbus ascii frames are delimited by a ':' (colon) at the begining of
* a frame, and CR-LF sequence at the end the frame.
*
* Unless we want to take 'ages' reading the data off the serial line
* one byte at a time, we risk reading beyond the boundary of the
* frame currently being interpreted. The extra data belongs to the
* subsequent frame, and must therefore be buffered to be handled
* when the next frame is being interpreted.
*
* The receive buffer is therefore a static variable.
*/
recv_buf_t recv_buf_;
/* The send ascii buffer could be a local function variable
* instead of a static variable, but we might just as well
* allocate the memory at startup and not risk running out
* of memory while the module is running.
*/
send_buf_t send_buf_;
/* The old settings of the serial port, to be reset when the library is closed... */
struct termios old_tty_settings_;
/* ignore echo flag.
* If set to 1, then it means that we will be reading every byte we
* ourselves write out to the bus, so we must ignore those bytes read
* before we really read the data sent by remote nodes.
*
* This comes in useful when using a RS232-RS485 converter that does
* not correctly control the RTS-CTS lines...
*/
int ignore_echo;
} nd_entry_t;
static inline void nd_entry_init(nd_entry_t *nde) {
nde->fd = -1; /* The node is free... */
}
static int nd_entry_connect(nd_entry_t *nde,
node_addr_t *node_addr,
optimization_t opt) {
int parity_bits, start_bits, char_bits;
struct termios settings;
int buf_size;
/*
if (nde == NULL)
goto error_exit_0;
*/
if (nde->fd >= 0)
goto error_exit_0;
/* initialise the termios data structure */
if (termios_init(&settings,
node_addr->addr.ascii.baud,
node_addr->addr.ascii.parity,
node_addr->addr.ascii.data_bits,
node_addr->addr.ascii.stop_bits)
< 0) {
#ifdef DEBUG
fprintf(stderr, "Invalid serial line settings"
"(baud=%d, parity=%d, data_bits=%d, stop_bits=%d)",
node_addr->addr.ascii.baud,
node_addr->addr.ascii.parity,
node_addr->addr.ascii.data_bits,
node_addr->addr.ascii.stop_bits);
#endif
goto error_exit_1;
}
/* set the ignore_echo flag */
nde->ignore_echo = node_addr->addr.ascii.ignore_echo;
/* initialise send buffer */
buf_size = (opt == optimize_size)?SEND_BUFFER_SIZE_SMALL:
SEND_BUFFER_SIZE_LARGE;
if (send_buf_init(&nde->send_buf_, buf_size, buf_size - SEND_BUF_MIN_LENGTH)
== NULL) {
#ifdef DEBUG
fprintf(stderr, "Out of memory: error initializing send buffer");
#endif
goto error_exit_1;
}
/* initialise recv buffer */
buf_size = (opt == optimize_size)?RECV_BUFFER_SIZE_SMALL:
RECV_BUFFER_SIZE_LARGE;
if (recv_buf_init(&nde->recv_buf_, buf_size, buf_size - RECV_BUF_MIN_LENGTH)
== NULL) {
#ifdef DEBUG
fprintf(stderr, "Out of memory: error initializing receive buffer");
#endif
goto error_exit_2;
}
/* open the serial port */
if((nde->fd = open(node_addr->addr.ascii.device, O_RDWR | O_NOCTTY | O_NDELAY))
< 0) {
#ifdef DEBUG
fprintf(stderr, "Error opening device %s (errno=%d)",
node_addr->addr.ascii.device, errno);
#endif
goto error_exit_3;
}
if(tcgetattr(nde->fd, &nde->old_tty_settings_) < 0) {
#ifdef DEBUG
fprintf(stderr, "Error reading device's %s original settings.",
node_addr->addr.ascii.device);
#endif
goto error_exit_4;
}
if(tcsetattr(nde->fd, TCSANOW, &settings) < 0) {
#ifdef DEBUG
fprintf(stderr, "Error configuring device %s"
"(baud=%d, parity=%d, data_bits=%d, stop_bits=%d)",
node_addr->addr.ascii.device,
node_addr->addr.ascii.baud,
node_addr->addr.ascii.parity,
node_addr->addr.ascii.data_bits,
node_addr->addr.ascii.stop_bits);
#endif
goto error_exit_4;
}
parity_bits = (node_addr->addr.ascii.parity == 0)?0:1;
start_bits = 1;
char_bits = start_bits + node_addr->addr.ascii.data_bits +
parity_bits + node_addr->addr.ascii.stop_bits;
/* time_35_char_ = d_to_timeval(3.5*char_bits/baud); */
nde->time_15_char_ = d_to_timeval(1.5*char_bits/node_addr->addr.ascii.baud);
#ifdef DEBUG
printf("nd_entry_connect(): %s open\n", node_addr->addr.ascii.device );
printf("nd_entry_connect(): returning fd=%d\n", nde->fd);
#endif
return nde->fd;
error_exit_4:
close(nde->fd);
error_exit_3:
recv_buf_done(&nde->recv_buf_);
error_exit_2:
send_buf_done(&nde->send_buf_);
error_exit_1:
nde->fd = -1; /* set the node as free... */
error_exit_0:
return -1;
}
static int nd_entry_free(nd_entry_t *nde) {
if (nde->fd < 0)
/* already free */
return -1;
/* reset the tty device old settings... */
if(tcsetattr(nde->fd, TCSANOW, &nde->old_tty_settings_) < 0)
fprintf(stderr, "Error reconfiguring serial port to it's original settings.");
recv_buf_done(&nde->recv_buf_);
send_buf_done(&nde->send_buf_);
close(nde->fd);
nde->fd = -1;
return 0;
}
static inline int nd_entry_is_free(nd_entry_t *nde) {
return (nde->fd < 0);
}
/************************************/
/** **/
/** A data structure - nd table **/
/** **/
/************************************/