Bus/MODBUS_RS232.pm untested

filter: Statementstmt 0.0% 0 / 221 Branchbran 0.0% 0 / 66 Conditioncond 0.0% 0 / 52 MC/DCmcdc 0.0% 0 / 29 Subroutinesub 0.0% 0 / 17 Podpod 0.0% 0 / 8 totaltotal 0.0% 0 / 393 CC 34 SCAR 47.9
CC
34
Cov
0%
connection_read
210.0
connection_write
210.0
new
12.0
CRAP 120.4
1 package Lab::Bus::MODBUS_RS232;
2 #ABSTRACT: RS232/RS485 MODBUS RTU protocol bus
3 $Lab::Bus::MODBUS_RS232::VERSION = '3.899';
4 use v5.20;
5  
6 #
7 # MODBUS bus driver.
8 # The MODBUS standard defines a protocol to access the memory of connected devices,
9 # possible interfaces are RS485/RS232 and Ethernet.
10 # For now this driver uses Lab::Bus::RS232 as backend. It's main use is to
11 # generate the checksums used by MODBUS RTU. The memory addresses are device specific and
12 # have to be stored in the according device driver packages.
13 #
14  
15 use strict;
16  
17 use Lab::Bus::RS232;
18 use Carp;
19 use Data::Dumper;
20  
21 use Scalar::Util qw(weaken);
22  
23 use threads;
24 use Thread::Semaphore;
25  
26 # setup this variable to add inherited functions later
27 our @ISA = ("Lab::Bus::RS232");
28  
29 our $INS_DEBUG = 0; # do we need additional output?
30  
31 my @crctab = ();
32  
33 my $ConnSemaphore = Thread::Semaphore->new()
34 ; # a semaphore to prevent simultaneous use of the bus by multiple threads
35  
36 our %fields = (
37 type => 'RS232',
38 crc_init => 0xFFFF,
39 crc_poly => 0xA001,
40 max_crc_errors => 3,
41 );
42  
43 sub new {
44 my $proto = shift;
45 my $class = ref($proto) || $proto;
46 my $twin = undef;
47 my $self = $class->SUPER::new(@_)
48 ; # getting fields and _permitted from parent class
49 $self->${ \( __PACKAGE__ . '::_construct' ) }(__PACKAGE__);
50  
51 # search for twin in %Lab::Bus::BusList. If there's none, place $self there and weaken it.
52 # note to self: put this in base class/_construct if possible
53 # note to self2: think about how to block access to this RS232 port for a plain Lab::Bus::RS232 bus.
54 if ( $class eq __PACKAGE__ )
55 { # careful - do only if this is not a parent class constructor
56 if ( $twin = $self->_search_twin() ) {
57 undef $self;
58 return $twin; # ...and that's it.
59 }
60 else {
61 $Lab::Bus::BusList{ $self->type() }->{ $self->port() } = $self;
62 weaken( $Lab::Bus::BusList{ $self->type() }->{ $self->port() } );
63 }
64 }
65  
66 $self->_crc_inittab(); # Precalculations for checksum generation
67  
68 return $self;
69 }
70  
71 sub connection_new {
72 my $self = shift;
73 my $args = undef;
74 if ( ref $_[0] eq 'HASH' ) {
75 $args = shift;
76 } # try to be flexible about options as hash/hashref
77 else { $args = {@_} }
78  
79 my $connection_handle = undef;
80 my $slave_address = undef;
81  
82 if ( exists $args->{'slave_address'}
83 && $args->{'slave_address'} =~ /[0-9]*/
84 && $args->{'slave_address'} > 0
85 && $args->{'slave_address'} < 255 ) {
86 $slave_address = $args->{'slave_address'};
87 }
88 else {
89 Lab::Exception::CorruptParameter->throw(
90 error =>
91 'No or invalid MODBUS Slave Address given. I can\'t work like this!',
92 );
93 }
94  
95 $connection_handle = {
96 valid => 1,
97 type => "MODBUS_RS232",
98 slave_address => $slave_address
99 };
100  
101 return $connection_handle;
102 }
103  
104 #
105 # returns the read values as an array of bytes (characters!)
106 # don't be fooled, these are integers
107 # note to self: think this through again
108 #
109 sub connection_read
110 { # @_ = ( $connection_handle, $args = { function, mem_address, mem_count }
111 my $self = shift;
112 my $connection_handle = shift;
113 my $args = undef;
114 if ( ref $_[0] eq 'HASH' ) {
115 $args = shift;
116 } # try to be flexible about options as hash/hashref
117 else { $args = {@_} }
118  
119 use bytes
120 ; # important! no unicode below, just plain 8-bit-encoding. We are receiving bytestrings via RS232, too much smart can blow us to hell.
121  
122 my $function = int( $args->{'function'} ) || undef;
123 my $mem_address = int( $args->{'mem_address'} ) || undef;
124 my $mem_count = int( $args->{'mem_count'} || 1 );
125 my @Result = ();
126 my $Success = 0;
127 my $ErrCount = 0;
128 my $Message = "";
129 my @MessageArr = ();
130 my @AnswerArr = ();
131 my @TmpArr = ();
132  
133 if ( !defined $function || $function != 3 ) {
134 Lab::Exception::CorruptParameter->throw(
135 error => 'Undefined or unimplemented function code', );
136 }
137 if ( !defined $mem_address || $mem_address < 0 || $mem_address > 0xFFFF )
138 {
139 Lab::Exception::CorruptParameter->throw(
140 error => 'Invalid memory address', );
141 }
142 if ( $mem_count < 1 ) {
143 Lab::Exception::CorruptParameter->throw(
144 error => 'Invalid count of registers to be read', );
145 }
146  
147 @MessageArr = $self->_MB_CRC(
148 pack( 'C', $connection_handle->{slave_address} ),
149 pack( 'C', $function ),
150 pack( 'n', $mem_address ),
151 pack( 'n', $mem_count )
152 );
153 $Message = join( '', $self->_chrlist(@MessageArr) );
154  
155 $Success = 0;
156 $ErrCount = 0;
157 $ConnSemaphore->down();
158 do {
159 $self->SUPER::_direct_write( command => $Message );
160 @AnswerArr
161 = split( //, $self->SUPER::_direct_read( read_length => 'all' ) );
162 if ( scalar(@AnswerArr) == 0 ) {
163 warn "Error, no answer received - retrying\n";
164 $ErrCount++;
165 }
166 else {
167 @TmpArr = $self->_MB_CRC(@AnswerArr);
168 if ( $TmpArr[-2] != 0 || $TmpArr[-1] != 0 )
169 { # CRC over the message including its correct CRC results in a "CRC" of zero.
170 $ErrCount++;
171 $ErrCount < $self->max_crc_errors()
172 ? warn "Error in MODBUS response - retrying\n"
173 : warn "Error in MODBUS response\n";
174 }
175 else {
176 warn "...Success\n" if $ErrCount > 0;
177 $Success = 1;
178 }
179 }
180 } until ( $Success == 1 || $ErrCount >= $self->max_crc_errors() );
181 $ConnSemaphore->up();
182 warn
183 "Too many CRC errors, giving up after ${\$self->max_crc_errors()} times.\n"
184 unless $Success;
185 return undef unless $Success;
186  
187 # formally correct - check response
188 if ( scalar(@AnswerArr) == 5 ) { # Error answer received?
189 $Success = 0;
190  
191 # Now: warn and tell error code. Later: throw exception
192 warn "Received MODBUS error message with error code"
193 . ord( $AnswerArr[2] ) . "\n";
194 }
195 elsif ( scalar(@AnswerArr) < ord( $AnswerArr[2] ) + 5 )
196 { # correct message length? carries all bytes it says it does?
197 $Success = 0;
198 }
199  
200 if ( $Success == 1 ) { # read result, as an array of bytes
201 for my $item ( @AnswerArr[ 3 .. 3 + ord( $AnswerArr[2] ) - 1 ] ) {
202 push( @Result, $item );
203 }
204 return @Result;
205 }
206 else {
207 return undef;
208 }
209 }
210  
211 sub connection_write
212 { # @_ = ( $connection_handle, $args = { function, mem_address, (int_16)mem_value }
213 my $self = shift;
214 my $connection_handle = shift;
215 my $args = undef;
216 if ( ref $_[0] eq 'HASH' ) { $args = shift }
217 else { $args = {@_} }
218  
219 my $function = int( $args->{'function'} ) || undef;
220 my $mem_address = int( $args->{'mem_address'} ) || undef;
221 my $mem_value = int( $args->{'mem_value'} );
222 my $SendValue = pack( 'n!', $mem_value );
223 my $Result = undef;
224 my $Message = "";
225 my @MessageArr = ();
226 my $Success = 0;
227 my @AnswerArr;
228 my @TmpArr = ();
229 my $ErrCount = 3;
230  
231 if ( !defined $function || $function != 6 ) {
232 Lab::Exception::CorruptParameter->throw(
233 error => 'Undefined or unimplemented function code', );
234 }
235 if ( !defined $mem_address || $mem_address < 0 || $mem_address > 0xFFFF )
236 {
237 Lab::Exception::CorruptParameter->throw(
238 error => 'Invalid memory address', );
239 }
240 if ( unpack( 'n!', $SendValue ) != $mem_value ) {
241 Lab::Exception::CorruptParameter->throw(
242 error => "Invalid Memory Value $mem_value", );
243 }
244  
245 @MessageArr = $self->_MB_CRC(
246 pack( 'C', $connection_handle->{slave_address} ),
247 pack( 'C', $function ),
248 pack( 'n', $mem_address ), $SendValue
249 );
250 $Message = join( '', $self->_chrlist(@MessageArr) );
251  
252 $Success = 0;
253 $ErrCount = 0;
254 $ConnSemaphore->down();
255 do {
256 $self->SUPER::_direct_write( command => $Message );
257 @AnswerArr
258 = split( //, $self->SUPER::_direct_read( read_length => 'all' ) );
259 if ( scalar(@AnswerArr) == 0 ) {
260 warn "Error, no answer received - retrying\n";
261 $ErrCount++;
262 }
263 else {
264 @TmpArr = $self->_MB_CRC(@AnswerArr);
265 if ( $TmpArr[-2] != 0 || $TmpArr[-1] != 0 )
266 { # CRC over the message including its correct CRC results in a "CRC" of zero
267 $ErrCount++;
268 $ErrCount < $self->max_crc_errors()
269 ? warn "Error in MODBUS response - retrying\n"
270 : warn "Error in MODBUS response\n";
271 }
272 else {
273 warn "...Success\n" if $ErrCount > 0;
274 $Success = 1;
275 }
276 }
277 } until ( $Success == 1 || $ErrCount >= $self->max_crc_errors() );
278 $ConnSemaphore->up();
279 warn
280 "Too many CRC errors, giving up after ${\$self->max_crc_errors()} times.\n"
281 unless $Success;
282 return undef unless $Success;
283  
284 # formally correct - check response;
285 @AnswerArr = $self->_ordlist(@AnswerArr);
286 if ( scalar(@AnswerArr) == 5 )
287 { # Error answer received? Error answers are 5 bytes long.
288 $Success = 0;
289  
290 # Now: warn and tell error code. Later: throw exception
291 warn "Received MODBUS error message with error code $AnswerArr[2] \n";
292 }
293 if ( $Success == 1 ) {
294  
295 # compare sent message and answer. equality signals success.
296 for ( my $i = 0; $i < scalar(@AnswerArr); $i++ ) {
297 if ( $AnswerArr[$i] ne $MessageArr[$i] ) {
298 $Success = 0;
299 $i = scalar(@AnswerArr);
300 }
301 }
302 }
303  
304 return $Success;
305 }
306  
307 #
308 # MODBUS RTU infrastructure below.
309 #
310  
311 sub _ordlist { # @list of chars
312 my $self = shift;
313 my @list = @_;
314 for (@list) { $_ = ord }
315 return @list;
316 }
317  
318 sub _chrlist { # @list of integers
319 my $self = shift;
320 my @list = @_;
321 for (@list) { $_ = chr }
322 return @list;
323 }
324  
325 sub _crc_inittab () {
326 my $self = shift;
327 my $crc = 0;
328 my $c = 0;
329 my $i = 0;
330 my $j = 0;
331  
332 my $crc_poly = $self->crc_poly();
333  
334 for ( $i = 0; $i < 256; $i++ ) {
335 $crc = 0;
336 $c = $i;
337  
338 for ( $j = 0; $j < 8; $j++ ) {
339  
340 if ( ( $crc ^ $c ) & 0x0001 ) { $crc = ( $crc >> 1 ) ^ $crc_poly }
341 else { $crc = ( $crc >> 1 ) }
342  
343 $c = ( $c >> 1 );
344 }
345  
346 $crctab[$i] = $crc;
347 }
348 }
349  
350 # generate MODBUS CRC for given message
351 # takes a message in the form of a (list of) binary string(s) like output by pack().
352 # generates crc and returns the message including the crc as a list of integers
353 sub _MB_CRC
354 { # @Message as character array, e.g. ( chr(1), pack('C',$address), split(//,pack('n',$stuff))
355 my $self = shift;
356 my @message = $self->_ordlist( split( //, join( '', @_ ) ) );
357 _crc_inittab() if ( !@crctab );
358  
359 my $crc_poly = $self->crc_poly();
360 my $crc_init = $self->crc_init();
361  
362 my $size = @message;
363 if ( $size == 0 ) { warn('Empty message!'); return undef; }
364 my $remainder = $crc_init;
365 my $tmp = 0;
366 my $i = 0;
367  
368 for ( $i = 0; $i < $size; $i++ ) {
369 $tmp = $remainder ^ ( 0x00ff & $message[$i] );
370 $remainder = ( $remainder >> 8 ) ^ $crctab[ $tmp & 0xff ];
371 }
372  
373 return ( @message, $remainder & 0x00FF, ( $remainder & 0xFF00 ) >> 8 );
374 }
375  
376 1;
377  
378 __END__