Bus/MODBUS_RS232.pm untested

filter: Statementstmt 0.0% 0 / 221 Branchbran 0.0% 0 / 66 Conditioncond 0.0% 0 / 52 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 17 Podpod 0.0% 0 / 8 totaltotal 0.0% 0 / 364 SCAR 70.8
CC
34
Cov
0%
connection_read
210.0
connection_write
210.0
new
12.0
CRAP 1190.0
1 package Lab::Bus::MODBUS_RS232;
2 #ABSTRACT: RS232/RS485 MODBUS RTU protocol bus
3 $Lab::Bus::MODBUS_RS232::VERSION = '3.881';
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__
379  
380 =pod
381  
382 =encoding utf-8
383  
384 =head1 NAME
385  
386 Lab::Bus::MODBUS_RS232 - RS232/RS485 MODBUS RTU protocol bus
387  
388 =head1 VERSION
389  
390 version 3.881
391  
392 =head1 SYNOPSIS
393  
394 use Lab::Bus::MODBUS_RS232;
395 my $h = Lab::Bus::MODBUS_RS232->new({
396 Interface => 'RS232',
397 Port => 'COM1|/dev/ttyUSB1'
398 slave_address => '1'
399 });
400  
401 C<COM1> is the Windows notation, C</dev/ttyUSB1> the Linux equivalent. Use as needed.
402  
403 =head1 DESCRIPTION
404  
405 This is an interface package for Lab::Measurement to communicate via RS232/RS485 with a
406 MODBUS RTU enabled device. It uses Lab::Bus::RS232 (RS485 can be done using a
407 RS232<->RS485 converter for now). It's main use is to calculate the checksums needed by
408 MODBUS RTU.
409  
410 Refer to your device for the correct port configuration.
411  
412 As of yet, this driver does NOT fully implement all MODBUS RTU functions. Only the function
413 codes 3 and 6 are provided.
414  
415 =head1 CONSTRUCTOR
416  
417 =head2 new
418  
419 All parameters are used as by C<Device::SerialPort> respectively C<Lab::Bus::RS232>.
420 'port' is needed in every case. Default value for timeout is 500ms and can be set by the
421 parameter "Timeout". Other options you probably have to set: Handshake, Baudrate, Databits, Stopbits and Parity.
422  
423 =head1 METHODS
424  
425 Used by C<Lab::Connection>. Not for direct use!!!
426  
427 =head2 connectionRead
428  
429 Reads data. Arguments:
430 function (0x01,0x02,0x03,0x04 - "Read Coils", "Read Discrete Inputs", "Read Holding Registers", "Read Input Registers")
431 slave_address (0xFF)
432 mem_address ( 0xFFFF, Address of first word )
433 mem_count ( 0xFFFF, Count of words to read )
434  
435 =head2 connectionWrite
436  
437 Send data to instrument. Arguments:
438  
439 function (0x05,0x06,0x0F,0x10 - "Write Single Coil", "Write Single Register", "Write Multiple Coils", "Write Multiple Registers")
440  
441 Currently only 0x06 is implemented.
442  
443 slave_address (0xFF)
444  
445 mem_address ( 0xFFFF, Address of word )
446
447 Value ( 0xFFFF, value to write to mem_address )
448  
449 =head1 CAVEATS/BUGS
450  
451 This is a prototype...
452  
453 =head1 SEE ALSO
454  
455 =over 4
456  
457 =item * L<Lab::Bus>
458  
459 =item * L<Lab::Bus::RS232>
460  
461 =item * L<Lab::Connection>
462  
463 =item * L<Win32::SerialPort>
464  
465 =item * L<Device::SerialPort>
466  
467 =back
468  
469 =head1 COPYRIGHT AND LICENSE
470  
471 This software is copyright (c) 2023 by the Lab::Measurement team; in detail:
472  
473 Copyright 2011-2012 Andreas K. Huettel, Florian Olbrich
474 2016 Simon Reinhardt
475 2017 Andreas K. Huettel
476 2020 Andreas K. Huettel
477  
478  
479 This is free software; you can redistribute it and/or modify it under
480 the same terms as the Perl 5 programming language system itself.
481  
482 =cut