| 1 | package Modbus::Client; | ||
| 2 | |||
| 3 | =head1 DESCRIPTION | ||
| 4 | |||
| 5 | This module provides a basic Modbus client for reading from and writing to | ||
| 6 | various ModBus serial slaves using RTU or ASCII modes. | ||
| 7 | |||
| 8 | =cut | ||
| 9 | |||
| 10 | use strict; | ||
| 11 | use 5.004; | ||
| 12 | use Exporter; | ||
| 13 | use POSIX ':termios_h'; | ||
| 14 | use FileHandle; | ||
| 15 | |||
| 16 | use vars qw($VERSION @ISA @EXPORT); | ||
| 17 | |||
| 18 | $VERSION = '1.03'; | ||
| 19 | @ISA = qw(Exporter); | ||
| 20 | @EXPORT = qw(M_RTU M_ASCII); | ||
| 21 | my ($RCSVERSION) = '$Revision: 1.3 $ ' =~ /\$Revision:\s+([^\s]+)/; | ||
| 22 | |||
| 23 | # There is magic in the values chosen for these constants, specifically in how | ||
| 24 | # many bytes are read from the device. | ||
| 25 | use constant M_RTU => 1; | ||
| 26 | use constant M_ASCII => 2; | ||
| 27 | |||
| 28 | =head1 METHODS | ||
| 29 | |||
| 30 | The Modbus::Client module defines the following methods: | ||
| 31 | |||
| 32 | =over 4 | ||
| 33 | |||
| 34 | =item Modbus::Client->new() | ||
| 35 | |||
| 36 | Create a new serial client to talk to a ModBus. Accepts two kinds of | ||
| 37 | parameters - the first kind is the serial device the modbus is connected to. | ||
| 38 | If this type of parameter is specified, Modbus::Client optionally accept a | ||
| 39 | second paramater to define the baud rate. By default, Modbus::Client will | ||
| 40 | initiate communications at 9600 baud, no parity. | ||
| 41 | |||
| 42 | $bus = new Modbus::Client "/dev/cua00", POSIX::B19200; | ||
| 43 | |||
| 44 | The second type of parameter is a file handle. If this parameter is passed, | ||
| 45 | it is assumed that you have initiated the connection, and Modbus::Client will | ||
| 46 | simply use the connection you have already established. This allows you to | ||
| 47 | easily use different baud rates or to connect to a TCP port associated with a | ||
| 48 | serial-to-ether adapter, such as the Digi One SP. For devices like this, | ||
| 49 | make sure you DISABLE software flow control! | ||
| 50 | |||
| 51 | use FileHandle; | ||
| 52 | use Socket; | ||
| 53 | $fd = new FileHandle; | ||
| 54 | $host = "something.yournet.com"; | ||
| 55 | $port = 2101; | ||
| 56 | $remote = inet_aton($host) || die "No such host $host"; | ||
| 57 | socket($fd, PF_INET, SOCK_STREAM, getprotobyname('tcp')) | ||
| 58 | || die "Can't create socket - $!"; | ||
| 59 | $paddr = sockaddr_in($port, $remote); | ||
| 60 | connect($fd, $paddr) || die "Can't connect to $host:$port - $!"; | ||
| 61 | $fd->autoflush(1); | ||
| 62 | $bus = Modbus::Client->new($fd); | ||
| 63 | |||
| 64 | NOTE FOR WINDOWS USERS: For finer control of the serial connection, it is | ||
| 65 | I<possibly> better if you open the connection and pass the FileHandle to the | ||
| 66 | I<new> method. This is because Windows does not implement POSIX::Termios. | ||
| 67 | |||
| 68 | =cut | ||
| 69 | |||
| 70 | sub new { | ||
| 71 | my ($class, $device, $speed, $addr) = @_; | ||
| 72 | die "Missing device or filehandle in call to $class->new\n" unless $device; | ||
| 73 | my ($serial, $self); | ||
| 74 | if (ref $device eq "FileHandle" || ref $device eq "GLOB") { | ||
| 75 | $serial = $device; | ||
| 76 | } | ||
| 77 | else { | ||
| 78 | if ($^O ne "MSWin32") { | ||
| 79 | $serial = new FileHandle($device, O_RDWR | O_NDELAY | O_NOCTTY) | ||
| 80 | or die "Can't open $device $!\n"; | ||
| 81 | |||
| 82 | # | ||
| 83 | # System dependent? | ||
| 84 | # 1) Open enersure non-blocking, but then reset that flag (has to do | ||
| 85 | # with DTR not being asserted) | ||
| 86 | # 2) Set baud rate | ||
| 87 | # 3) Enable reader, don't monitor DTR, etc, 8 bits, 2 stop bits | ||
| 88 | # | ||
| 89 | my $cflag = CS8 | HUPCL | CREAD | CLOCAL; | ||
| 90 | my $lflag = 0; # No local processing (raw mode) | ||
| 91 | my $iflag = IGNBRK | IGNPAR; | ||
| 92 | my $oflag = 0; # No output post-processing | ||
| 93 | my $termios = POSIX::Termios->new(); | ||
| 94 | |||
| 95 | $termios->getattr($serial->fileno()) | ||
| 96 | or die "getattr failed: $!\n"; | ||
| 97 | |||
| 98 | $termios->setcflag($cflag); | ||
| 99 | $termios->setlflag($lflag); | ||
| 100 | $termios->setiflag($iflag); | ||
| 101 | $termios->setoflag($oflag); | ||
| 102 | $termios->setcc(VTIME, 10); # 10 * .1 == 1 sec timeout on read | ||
| 103 | $termios->setcc(VMIN, 0); # Purely time-based timeouts | ||
| 104 | |||
| 105 | $termios->setattr($serial->fileno(),TCSANOW) | ||
| 106 | or die "setattr failed 1: $!\n"; | ||
| 107 | $termios->setospeed($speed || POSIX::B9600) | ||
| 108 | or die "setospeed failed: \$!\n"; | ||
| 109 | $termios->setispeed($speed || POSIX::B9600) | ||
| 110 | or die "setispeed failed: \$!\n"; | ||
| 111 | $termios->setattr($serial->fileno(),TCSANOW) | ||
| 112 | or die "setattr 2 failed: $!\n"; | ||
| 113 | |||
| 114 | # This gets rid of all the special characters.. | ||
| 115 | $termios->getattr($serial->fileno()) | ||
| 116 | or die "getattr failed: $!\n"; | ||
| 117 | } | ||
| 118 | |||
| 119 | $serial = new FileHandle($device, O_RDWR | O_NOCTTY) | ||
| 120 | or die "Can't open $device $!\n"; | ||
| 121 | } | ||
| 122 | $serial->autoflush(0); | ||
| 123 | |||
| 124 | $self = bless { | ||
| 125 | fh => $serial, | ||
| 126 | clump => 125, | ||
| 127 | mode => M_RTU, | ||
| 128 | debug => 0, | ||
| 129 | }, $class; | ||
| 130 | $self->{bus} = $self; # Makes {mode} coding easier to self-reference | ||
| 131 | |||
| 132 | return $self; | ||
| 133 | } | ||
| 134 | |||
| 135 | =item $bus->device() | ||
| 136 | |||
| 137 | Create a new device on a Modbus. The single parameter is the device number. | ||
| 138 | Note that according to the Modbus spec, a device number of 0 is the broadcast | ||
| 139 | address. | ||
| 140 | |||
| 141 | $unit = $bus->device(1); | ||
| 142 | |||
| 143 | =cut | ||
| 144 | |||
| 145 | sub device { | ||
| 146 | my ($self, $addr) = @_; | ||
| 147 | die "$self does not look like a Modbus conection\n" unless ref $self; | ||
| 148 | die "Missing device address in device()\n" unless defined $addr; | ||
| 149 | |||
| 150 | return bless { | ||
| 151 | addr => $addr, | ||
| 152 | bus => $self, | ||
| 153 | %{ $self } | ||
| 154 | }, ref $self; | ||
| 155 | } | ||
| 156 | |||
| 157 | sub _my_read { | ||
| 158 | my ($self, undef, $cnt) = @_; | ||
| 159 | my ($buf, $chr, $rin, $rout); | ||
| 160 | my $total = 0; | ||
| 161 | |||
| 162 | vec($rin, $self->{fh}->fileno, 1) = 1; | ||
| 163 | while ($cnt--) { | ||
| 164 | last unless select($rout=$rin, undef, undef, 1); | ||
| 165 | last unless sysread($self->{fh}, $chr, 1); | ||
| 166 | $buf .= $chr; | ||
| 167 | $total++; | ||
| 168 | } | ||
| 169 | if ($self->{bus}->{debug}) { | ||
| 170 | print STDERR "Modbus::Client Reading $total chars: "; | ||
| 171 | if ($self->{bus}->{mode} == M_RTU) { | ||
| 172 | for (0..length($buf)-1) { | ||
| 173 | printf STDERR "%02x", ord(substr($buf,$_,1)); | ||
| 174 | } | ||
| 175 | print STDERR "\n"; | ||
| 176 | } | ||
| 177 | else { | ||
| 178 | print STDERR "'$buf'\n"; | ||
| 179 | } | ||
| 180 | } | ||
| 181 | $_[1] = $buf; | ||
| 182 | return $total; | ||
| 183 | } | ||
| 184 | |||
| 185 | =item $unit->read_one() | ||
| 186 | |||
| 187 | The I<read_one> method is a convenience routine that is called with a single | ||
| 188 | modbus address to read, and it returns a single scalar value from that | ||
| 189 | register. The I<read> method is more powerful, but also more complicated. | ||
| 190 | |||
| 191 | The API for the I<read_one> method does not distinguish between ModBus Coils, | ||
| 192 | Status Registers, Holding Registers, or Input Registers. It makes the | ||
| 193 | necessary ModBus calls to get all of them to work. | ||
| 194 | |||
| 195 | =cut | ||
| 196 | |||
| 197 | sub read_one { | ||
| 198 | my $self = shift; | ||
| 199 | my $reg = shift; | ||
| 200 | |||
| 201 | die "You must read_one from a specific device, not a modbus\n" | ||
| 202 | unless $self->{addr}; | ||
| 203 | |||
| 204 | return ($self->read($reg))[0]; | ||
| 205 | } | ||
| 206 | |||
| 207 | =item $unit->read() | ||
| 208 | |||
| 209 | The I<read> method may be called with two kinds of parameters: a list of | ||
| 210 | addresses to read, or a reference to hash table (where the keys are the | ||
| 211 | addresses to read, and the values will be filled in by the method). | ||
| 212 | |||
| 213 | It may also be called in an array context (in which case it returns the | ||
| 214 | values of the registers that were read. The order in which they are returned | ||
| 215 | is equal to the order specified (when called with an array of values) or in | ||
| 216 | sorted key order (when called with a reference to a hash table). | ||
| 217 | |||
| 218 | @array = $unit->read(30001..30010); | ||
| 219 | $hash = $unit->read(10001..10037); | ||
| 220 | |||
| 221 | %hash = map {$_, 1} (20007, 20012..20015, 30029, 40006) | ||
| 222 | @array = $unit->read(\%hash); | ||
| 223 | $hash = $unit->read(\%hash); | ||
| 224 | |||
| 225 | If the method is called in a scalar context, then a reference to a hash table | ||
| 226 | is returned (where the keys are the register addresses and the values are the | ||
| 227 | values read). The referenced hash will be the same as the input hash, or if | ||
| 228 | an array of addresses is passed as a parameter, the referenced hash will be | ||
| 229 | an anonymous one. | ||
| 230 | |||
| 231 | The API for the I<read> method does not distinguish between ModBus Coils, | ||
| 232 | Status Registers, Holding Registers, or Input Registers. It makes the | ||
| 233 | necessary ModBus calls to get all of them to work, even if they are mixed in a | ||
| 234 | single invocation of the I<read> method. | ||
| 235 | |||
| 236 | General Reference registers are not presently supported, neither are FIFO | ||
| 237 | queues - ask and ye shall receive, though... | ||
| 238 | |||
| 239 | =cut | ||
| 240 | |||
| 241 | my @exception = ("", # 0 == no exception | ||
| 242 | "ILLEGAL FUNCTION", | ||
| 243 | "ILLEGAL DATA ADRESS", | ||
| 244 | "ILLEGAL DATA VALUE". | ||
| 245 | "SLAVE DEVICE FAILURE", | ||
| 246 | "ACKNOWLEDGE", | ||
| 247 | "SLAVE DEVICE BUSY", | ||
| 248 | "NEGATIVE ACKNOWLEDGE", | ||
| 249 | "MEMORY PARITY ERROR", | ||
| 250 | ); | ||
| 251 | |||
| 252 | sub read { | ||
| 253 | my $self = shift; | ||
| 254 | my @regs = @_; | ||
| 255 | my (@this_set, @retval, $regs, $base, $fn, $start, $cmd, | ||
| 256 | $icnt, $ocnt, $tally); | ||
| 257 | |||
| 258 | die "You must read from a specific device, not a modbus\n" | ||
| 259 | unless $self->{addr}; | ||
| 260 | |||
| 261 | if (@regs == 1 && ref $regs[0] eq "HASH") { | ||
| 262 | $regs = $regs[0]; | ||
| 263 | @regs = sort { $a <=> $b } keys %$regs; | ||
| 264 | } | ||
| 265 | else { | ||
| 266 | $regs = { }; | ||
| 267 | } | ||
| 268 | while (@regs) { | ||
| 269 | # Collect adjacent registers into a set to read... | ||
| 270 | @this_set = (); | ||
| 271 | push @this_set, shift @regs; | ||
| 272 | $tally = 1; | ||
| 273 | CLUMP: while (@regs) { | ||
| 274 | last CLUMP if $regs[0] != $this_set[-1] + 1; # Must be adjacent | ||
| 275 | last CLUMP if ++$tally > $self->{clump}; # Limit clump size | ||
| 276 | push @this_set, shift @regs; | ||
| 277 | } | ||
| 278 | if ($this_set[0] > 0 && $this_set[0] < 10000) { | ||
| 279 | $base = 00001; | ||
| 280 | $fn = 0x01; | ||
| 281 | } | ||
| 282 | elsif ($this_set[0] > 10000 && $this_set[0] < 20000) { | ||
| 283 | $base = 10001; | ||
| 284 | $fn = 0x02; | ||
| 285 | } | ||
| 286 | elsif ($this_set[0] > 30000 && $this_set[0] < 40000) { | ||
| 287 | $base = 30001; | ||
| 288 | $fn = 0x04; | ||
| 289 | } | ||
| 290 | elsif ($this_set[0] > 40000 && $this_set[0] < 50000) { | ||
| 291 | $base = 40001; | ||
| 292 | $fn = 0x03; | ||
| 293 | } | ||
| 294 | else { | ||
| 295 | die "I don't know how to read registers like $this_set[0]\n"; | ||
| 296 | } | ||
| 297 | $start = $this_set[0] - $base; | ||
| 298 | $cmd = pack('ccnn', $self->{addr}, $fn, $start, scalar(@this_set)); | ||
| 299 | if ($self->{bus}->{mode} == M_ASCII) { | ||
| 300 | $cmd =~ s/(.)/sprintf "%02x", ord($1)/ges; | ||
| 301 | _append_lrc($cmd); | ||
| 302 | $cmd = ":$cmd\r\n"; | ||
| 303 | if ($self->{bus}->{debug}) { | ||
| 304 | print STDERR "Modbus::Client Writing: $cmd"; | ||
| 305 | } | ||
| 306 | } | ||
| 307 | else { | ||
| 308 | _append_crc($cmd); | ||
| 309 | if ($self->{bus}->{debug}) { | ||
| 310 | print STDERR "Modbus::Client Writing: "; | ||
| 311 | for (0..length($cmd)-1) { | ||
| 312 | printf STDERR "%02x", ord(substr($cmd,$_,1)); | ||
| 313 | } | ||
| 314 | print STDERR "\n"; | ||
| 315 | } | ||
| 316 | } | ||
| 317 | syswrite($self->{fh}, $cmd); | ||
| 318 | my ($buf, $tmp, $nbytes, $want, $got); | ||
| 319 | # Read the echoed address | ||
| 320 | $ocnt = $self->_my_read($tmp, $icnt = 1 * $self->{bus}->{mode}); | ||
| 321 | die "Unexpected return from Modbus device (@{[$ocnt||0]} bytes)" | ||
| 322 | unless $ocnt == $icnt; | ||
| 323 | $want = $self->{addr}; | ||
| 324 | $got = $self->{bus}->{mode} == M_ASCII ? hex($tmp) : ord($tmp); | ||
| 325 | if ($got != $want) { | ||
| 326 | die "Unexpected return from Modbus device (addr echo mismatch)" | ||
| 327 | } | ||
| 328 | $buf .= $tmp; | ||
| 329 | # Read the echoed command | ||
| 330 | $ocnt = $self->_my_read($tmp, $icnt = 1 * $self->{bus}->{mode}); | ||
| 331 | die "Unexpected return from Modbus device (@{[$ocnt||0]} bytes)" | ||
| 332 | unless $ocnt == $icnt; | ||
| 333 | $buf .= $tmp; | ||
| 334 | $want = $fn; | ||
| 335 | $got = $self->{bus}->{mode} == M_ASCII ? hex($tmp) : ord($tmp); | ||
| 336 | if ($got != $want) { | ||
| 337 | # Error handling... | ||
| 338 | if (($got & 0x7f) == $want) { | ||
| 339 | my $err; | ||
| 340 | $ocnt = $self->_my_read($tmp, $icnt = 1 * $self->{bus}->{mode}); | ||
| 341 | die "Unexpected return from Modbus device (@{[$ocnt||0]} bytes)" | ||
| 342 | unless $ocnt == $icnt; | ||
| 343 | $buf .= $tmp; | ||
| 344 | $got = $self->{bus}->{mode} == M_ASCII ? hex($tmp) : ord($tmp); | ||
| 345 | $ocnt = $self->_my_read($tmp, $icnt = 2); | ||
| 346 | die "Unexpected return from Modbus device (@{[$ocnt||0]} bytes)" | ||
| 347 | unless $ocnt == $icnt; | ||
| 348 | $buf .= $tmp; | ||
| 349 | if ($self->{bus}->{mode} == M_ASCII) { | ||
| 350 | if (_verify_lrc($buf)) { | ||
| 351 | $err = hex(substr($buf, 4, 2)); | ||
| 352 | warn "Modbus Exception: $exception[$err]"; | ||
| 353 | } | ||
| 354 | else { | ||
| 355 | warn "Bad error LRC from device\n"; | ||
| 356 | } | ||
| 357 | } | ||
| 358 | else { | ||
| 359 | if (_verify_crc($buf)) { | ||
| 360 | $err = ord(substr($buf, 2, 1)); | ||
| 361 | warn "Modbus Exception: $exception[$err]"; | ||
| 362 | } | ||
| 363 | else { | ||
| 364 | warn "Bad error CRC from device\n"; | ||
| 365 | } | ||
| 366 | } | ||
| 367 | } | ||
| 368 | else { | ||
| 369 | die "Unexpected return from Modbus device (cmd echo mismatch)" | ||
| 370 | } | ||
| 371 | return undef; | ||
| 372 | } | ||
| 373 | # Read the byte count | ||
| 374 | $ocnt = $self->_my_read($tmp, $icnt = 1 * $self->{bus}->{mode}); | ||
| 375 | if ($self->{bus}->{mode} == M_ASCII) { | ||
| 376 | $nbytes = hex($tmp); | ||
| 377 | } | ||
| 378 | else { | ||
| 379 | $nbytes = ord($tmp); | ||
| 380 | } | ||
| 381 | die "Odd byte count returned from device\n" if $fn > 0x3 && $nbytes & 1; | ||
| 382 | $buf .= $tmp; | ||
| 383 | if ($this_set[0] < 20000) { | ||
| 384 | my $nval = @this_set; | ||
| 385 | my $idx = $base + $start + 1; | ||
| 386 | my ($bit, $byte, $nbits); | ||
| 387 | for (1..$nbytes) { | ||
| 388 | $ocnt = $self->_my_read($tmp, $icnt = 1 * $self->{bus}->{mode}); | ||
| 389 | die "Didn't get byte $_ from device\n" unless $ocnt == $icnt; | ||
| 390 | $buf .= $tmp; | ||
| 391 | # | ||
| 392 | # All sorts of endian issues here. The MSB contains the first | ||
| 393 | # bit, but if there are fewer than 8 bits, they are 0 padded | ||
| 394 | # to the left. What idiot designed this? | ||
| 395 | # | ||
| 396 | if ($self->{bus}->{mode} == M_ASCII) { | ||
| 397 | $byte = hex($tmp); | ||
| 398 | } | ||
| 399 | else { | ||
| 400 | $byte = ord($tmp); | ||
| 401 | } | ||
| 402 | $bit = 0x01; | ||
| 403 | $nbits = $nval > 8 ? 8 : $nval; | ||
| 404 | for (1..$nbits) { | ||
| 405 | push @retval, ($regs->{$idx++} = ($byte & 1)); | ||
| 406 | $byte >>= 1; | ||
| 407 | $nval--; | ||
| 408 | } | ||
| 409 | } | ||
| 410 | } | ||
| 411 | elsif ($this_set[0] > 30000 && $this_set[0] < 50000) { | ||
| 412 | # Read each 16-bit return value | ||
| 413 | my $val; | ||
| 414 | for (1..$nbytes/2) { | ||
| 415 | $ocnt = $self->_my_read($tmp, $icnt = 2 * $self->{bus}->{mode}); | ||
| 416 | die "Didn't get @{[$ocnt||0]} != 2 bytes for data element $_ from device\n" | ||
| 417 | unless $ocnt == $icnt; | ||
| 418 | $buf .= $tmp; | ||
| 419 | if ($self->{bus}->{mode} == M_ASCII) { | ||
| 420 | $val = hex($tmp); | ||
| 421 | } | ||
| 422 | else { | ||
| 423 | $val = unpack('n', $tmp); | ||
| 424 | } | ||
| 425 | push @retval, $regs->{$_ + $base + $start - 1} = $val; | ||
| 426 | } | ||
| 427 | } | ||
| 428 | else { | ||
| 429 | die "Shouldn't get here!"; | ||
| 430 | } | ||
| 431 | # Finally, read the CRC/LRC and verify correctness | ||
| 432 | $ocnt = $self->_my_read($tmp, 2); | ||
| 433 | die "Didn't get @{[$ocnt||0]} != 2 bytes for CRC/LRC from device\n" | ||
| 434 | unless $ocnt == 2; | ||
| 435 | $buf .= $tmp; | ||
| 436 | if ($self->{bus}->{mode} == M_ASCII) { | ||
| 437 | warn "Bad LRC from device\n" unless _verify_lrc($buf); | ||
| 438 | } | ||
| 439 | else { | ||
| 440 | warn "Bad CRC from device\n" unless _verify_crc($buf); | ||
| 441 | } | ||
| 442 | } | ||
| 443 | if (wantarray) { | ||
| 444 | return @retval; | ||
| 445 | } | ||
| 446 | else { | ||
| 447 | return $regs; | ||
| 448 | } | ||
| 449 | } | ||
| 450 | |||
| 451 | =item $unit->write() | ||
| 452 | |||
| 453 | The I<write> method is called with a hash table or a reference to hash table | ||
| 454 | as a paremeter (where the keys of the hash are the addresses to write, and the | ||
| 455 | values of the hash are written to the corresponding addresses). | ||
| 456 | |||
| 457 | $unit->write(6 => 1, 8 => 0, 2007 => 10, 2008 => 2); | ||
| 458 | %hash = (6 => 1, 8 => 0, 2007 => 10, 2008 => 2); | ||
| 459 | $unit->write(%hash); | ||
| 460 | $unit->write(\%hash); | ||
| 461 | |||
| 462 | The API for the I<write> method does not distinguish between ModBus Coils or | ||
| 463 | Holding Registers. It makes the necessary ModBus calls to get all of them to | ||
| 464 | work, even if they are mixed in a single invocation of the I<write> method. | ||
| 465 | |||
| 466 | General Reference registers are not presently supported, neeither are Mask | ||
| 467 | Write nor combined Read/Write functions - ask and ye shall receive, though... | ||
| 468 | |||
| 469 | =cut | ||
| 470 | |||
| 471 | sub write { | ||
| 472 | my $self = shift; | ||
| 473 | my (@this_set, @retval, @regs, %regs, $base, $fn, $start, $cmd, $resp, | ||
| 474 | $tally, $icnt, $ocnt); | ||
| 475 | |||
| 476 | die "You must write to a device (or broadcast), not a modbus\n" | ||
| 477 | unless defined $self->{addr}; | ||
| 478 | |||
| 479 | if (@_ == 1 && ref $_[0] eq "HASH") { | ||
| 480 | %regs = %{ $_[0] }; | ||
| 481 | } | ||
| 482 | else { | ||
| 483 | %regs = @_; | ||
| 484 | } | ||
| 485 | |||
| 486 | @regs = sort {$a <=> $b} keys %regs; | ||
| 487 | while (@regs) { | ||
| 488 | # Collect adjacent registers into a set to read... | ||
| 489 | @this_set = (); | ||
| 490 | push @this_set, shift @regs; | ||
| 491 | $tally = 1; | ||
| 492 | CLUMP: while (@regs) { | ||
| 493 | last CLUMP if $regs[0] != $this_set[-1] + 1; # Must be adjacent | ||
| 494 | last CLUMP if ++$tally > $self->{clump}; # Limit clump size | ||
| 495 | push @this_set, shift @regs; | ||
| 496 | } | ||
| 497 | if ($this_set[0] > 0 && $this_set[0] < 10000) { | ||
| 498 | $base = 00001; | ||
| 499 | $start = $this_set[0] - $base; | ||
| 500 | if (@this_set == 1) { | ||
| 501 | $fn = 0x05; | ||
| 502 | $cmd = pack('ccnn', $self->{addr}, $fn, $start, | ||
| 503 | $regs{$this_set[0]} ? 0xff00 : 0x0000); | ||
| 504 | $resp = $cmd; | ||
| 505 | } | ||
| 506 | else { | ||
| 507 | my ($bit, $byte, @subset); | ||
| 508 | $fn = 0x0f; | ||
| 509 | $cmd = pack('ccnn', $self->{addr}, $fn, $start, | ||
| 510 | scalar(@this_set)); | ||
| 511 | $resp = $cmd; | ||
| 512 | $cmd .= pack('c', int((@this_set+7)/8)); # Byte cnt | ||
| 513 | while (@subset = splice(@this_set, 0, 8)) { | ||
| 514 | # | ||
| 515 | # All sorts of endian issues here. The MSB contains the | ||
| 516 | # first bit, but if there are fewer than 8 bits, they are | ||
| 517 | # 0 padded to the left. What idiot designed this? | ||
| 518 | # | ||
| 519 | $byte = 0; | ||
| 520 | $bit = 0x01; | ||
| 521 | for my $n (@subset) { | ||
| 522 | $byte |= $regs{$n} ? $bit : 0; | ||
| 523 | $bit <<= 1; | ||
| 524 | } | ||
| 525 | $cmd .= pack('c', $byte); | ||
| 526 | } | ||
| 527 | } | ||
| 528 | } | ||
| 529 | elsif ($this_set[0] > 40000 && $this_set[0] < 50000) { | ||
| 530 | $base = 40001; | ||
| 531 | $start = $this_set[0] - $base; | ||
| 532 | if (@this_set == 1) { | ||
| 533 | $fn = 0x06; | ||
| 534 | $cmd = pack('ccnn', $self->{addr}, $fn, $start, | ||
| 535 | $regs{$this_set[0]}); | ||
| 536 | $resp = $cmd; | ||
| 537 | } | ||
| 538 | else { | ||
| 539 | $fn = 0x10; | ||
| 540 | $cmd = pack('ccnn', $self->{addr}, $fn, $start, | ||
| 541 | scalar(@this_set)); | ||
| 542 | $resp = $cmd; | ||
| 543 | $cmd .= pack('c', @this_set * 2); | ||
| 544 | for my $n (@this_set) { | ||
| 545 | $cmd .= pack('n', $regs{$n}); | ||
| 546 | } | ||
| 547 | } | ||
| 548 | } | ||
| 549 | else { | ||
| 550 | die "I don't know how to write registers like $this_set[0]\n"; | ||
| 551 | } | ||
| 552 | if ($self->{bus}->{mode} == M_ASCII) { | ||
| 553 | $cmd =~ s/(.)/sprintf "%02x", ord($1)/ges; | ||
| 554 | _append_lrc($cmd); | ||
| 555 | _append_lrc($resp); | ||
| 556 | $cmd = ":$cmd\r\n"; | ||
| 557 | if ($self->{bus}->{debug}) { | ||
| 558 | print STDERR "Modbus::Client Writing: $cmd"; | ||
| 559 | } | ||
| 560 | } | ||
| 561 | else { | ||
| 562 | _append_crc($cmd); | ||
| 563 | _append_crc($resp); | ||
| 564 | if ($self->{bus}->{debug}) { | ||
| 565 | print STDERR "Modbus::Client Writing: "; | ||
| 566 | for (0..length($cmd)-1) { | ||
| 567 | printf STDERR "%02x", ord(substr($cmd,$_,1)); | ||
| 568 | } | ||
| 569 | print STDERR "\n"; | ||
| 570 | } | ||
| 571 | } | ||
| 572 | syswrite($self->{fh}, $cmd); | ||
| 573 | my ($buf, $nbytes, $err); | ||
| 574 | # Read the echoed address and command | ||
| 575 | $ocnt = $self->_my_read($buf, $icnt = length($resp)); | ||
| 576 | if ($ocnt != $icnt || $buf ne $resp) { | ||
| 577 | if ($self->{bus}->{mode} == M_ASCII) { | ||
| 578 | if ($self->{bus}->{debug}) { | ||
| 579 | print STDERR "Modbus::Client Expected: $resp\n"; | ||
| 580 | print STDERR "Modbus::Client Got : $buf\n"; | ||
| 581 | } | ||
| 582 | if (_verify_lrc($buf)) { | ||
| 583 | $err = hex(substr($buf, 4, 2)); | ||
| 584 | warn "Modbus Exception: $exception[$err]"; | ||
| 585 | } | ||
| 586 | else { | ||
| 587 | warn "Bad error LRC from device\n"; | ||
| 588 | } | ||
| 589 | } | ||
| 590 | else { | ||
| 591 | if ($self->{bus}->{debug}) { | ||
| 592 | print STDERR "Modbus::Client Expected: "; | ||
| 593 | for (0..length($resp)-1) { | ||
| 594 | printf STDERR "%02x", ord(substr($resp,$_,1)); | ||
| 595 | } | ||
| 596 | print STDERR "\n"; | ||
| 597 | print STDERR "Modbus::Client Got : "; | ||
| 598 | for (0..length($buf)-1) { | ||
| 599 | printf STDERR "%02x", ord(substr($buf,$_,1)); | ||
| 600 | } | ||
| 601 | print STDERR "\n"; | ||
| 602 | } | ||
| 603 | if (_verify_crc($buf)) { | ||
| 604 | $err = ord(substr($buf, 2, 1)); | ||
| 605 | warn "Modbus Exception: $exception[$err]"; | ||
| 606 | } | ||
| 607 | else { | ||
| 608 | warn "Bad error CRC from device\n"; | ||
| 609 | } | ||
| 610 | } | ||
| 611 | return undef; | ||
| 612 | } | ||
| 613 | } | ||
| 614 | } | ||
| 615 | |||
| 616 | # Yes, I know that there are CRC routines in the CPAN - and it seems that | ||
| 617 | # the ModBus CRC uses a non-standard polynomial value. So... here you go. | ||
| 618 | |||
| 619 | sub _crc { | ||
| 620 | my $str = shift; | ||
| 621 | my $crc = 0xFFFF; | ||
| 622 | my ($chr, $lsb); | ||
| 623 | |||
| 624 | for my $i (0..length($str)-1) { | ||
| 625 | $chr = ord(substr($str, $i, 1)); | ||
| 626 | $crc ^= $chr; | ||
| 627 | for (1..8) { | ||
| 628 | $lsb = $crc & 1; | ||
| 629 | $crc >>= 1; | ||
| 630 | $crc ^= 0xA001 if $lsb; | ||
| 631 | } | ||
| 632 | } | ||
| 633 | return $crc; | ||
| 634 | } | ||
| 635 | |||
| 636 | sub _append_crc { | ||
| 637 | my $crc = _crc($_[0]); | ||
| 638 | |||
| 639 | $_[0] .= pack 'v', $crc; | ||
| 640 | } | ||
| 641 | |||
| 642 | sub _verify_crc { | ||
| 643 | my $str = shift; | ||
| 644 | my $crc = unpack('v', substr($str, -2)); | ||
| 645 | substr($str, -2) = ""; | ||
| 646 | |||
| 647 | return $crc == _crc($str); | ||
| 648 | } | ||
| 649 | |||
| 650 | sub _lrc { | ||
| 651 | my $str = shift; | ||
| 652 | my $lrc = 0; | ||
| 653 | |||
| 654 | for my $char (split //, $str) { | ||
| 655 | $lrc += ord($char); | ||
| 656 | } | ||
| 657 | return sprintf "%02x", -$lrc & 0xFF; | ||
| 658 | } | ||
| 659 | |||
| 660 | sub _append_lrc { | ||
| 661 | my $lrc = _lrc($_[0]); | ||
| 662 | |||
| 663 | $_[0] .= $lrc; | ||
| 664 | } | ||
| 665 | |||
| 666 | sub _verify_lrc { | ||
| 667 | my $str = shift; | ||
| 668 | my $lrc = substr($str, -2); | ||
| 669 | substr($str, -2) = ""; | ||
| 670 | |||
| 671 | return $lrc eq _lrc($str); | ||
| 672 | } | ||
| 673 | |||
| 674 | =item $clump_size = $self->clump([$new_clump_size])) | ||
| 675 | |||
| 676 | The clump method is used to set the number of elements that may be read or | ||
| 677 | written in a single operation. Note that read() and write() will always | ||
| 678 | operate on as many elements as are specified, but to reduce the possibility | ||
| 679 | of errors, it will break them up into clumps. This routine specifies the | ||
| 680 | maximum size of such a clump. The initial value is 125 (as implied by the | ||
| 681 | Modbus spec), and may in any event not exceed 127 (since the byte count in | ||
| 682 | returned data is stored in an 8 bit field, and 127 16-bit registers is 254 | ||
| 683 | bytes). | ||
| 684 | |||
| 685 | Setting the clump size on a device changes the behavior of that device only. | ||
| 686 | Setting the clump size on a modbus changes the behavior of all devices that | ||
| 687 | are created I<after> the change (that is, there is only partial inheritance). | ||
| 688 | |||
| 689 | =cut | ||
| 690 | |||
| 691 | sub clump { | ||
| 692 | my ($self, $clump) = @_; | ||
| 693 | |||
| 694 | if (defined $clump) { | ||
| 695 | if ($clump < 1) { | ||
| 696 | $self->{clump} = 32; | ||
| 697 | } | ||
| 698 | elsif ($clump > 127) { | ||
| 699 | $self->{clump} = 127; | ||
| 700 | } | ||
| 701 | else { | ||
| 702 | $self->{clump} = $clump; | ||
| 703 | } | ||
| 704 | } | ||
| 705 | return $self->{clump}; | ||
| 706 | } | ||
| 707 | |||
| 708 | =item $mode = $self->mode([M_RTU | M_ASCII])) | ||
| 709 | |||
| 710 | The mode method is used to set the communication mode to the device. The | ||
| 711 | two choices are M_ASCII and M_RTU (both are constants exported by the | ||
| 712 | Modbus::Client package, the default mode is M_RTU). ASCII mode is more | ||
| 713 | readable (for debugging), RTU mode is faster (using fewer bytes). The method | ||
| 714 | returns the current mode. | ||
| 715 | |||
| 716 | Setting the mode on a device or an a modbus changes the mode for all devices | ||
| 717 | on the bus (since according to the spec, all devices must comunicate using the | ||
| 718 | same mode). | ||
| 719 | |||
| 720 | =cut | ||
| 721 | |||
| 722 | sub mode { | ||
| 723 | my ($self, $mode) = @_; | ||
| 724 | |||
| 725 | if (defined $mode) { | ||
| 726 | if ($mode == M_ASCII) { | ||
| 727 | $self->{bus}->{mode} = M_ASCII; | ||
| 728 | } | ||
| 729 | elsif ($mode == M_RTU) { | ||
| 730 | $self->{bus}->{mode} = M_RTU; | ||
| 731 | } | ||
| 732 | else { | ||
| 733 | warn "Unknown value for mode ($mode) ignored"; | ||
| 734 | } | ||
| 735 | } | ||
| 736 | return $self->{bus}->{mode}; | ||
| 737 | } | ||
| 738 | |||
| 739 | |||
| 740 | =item $mode = $self->debug(1 | 0)) | ||
| 741 | |||
| 742 | The debug method is used to enable or disable communication debugging. | ||
| 743 | |||
| 744 | Setting debug mode on a device or an a modbus changes the mode for all devices | ||
| 745 | on the bus. | ||
| 746 | |||
| 747 | =cut | ||
| 748 | |||
| 749 | sub debug { | ||
| 750 | my ($self, $debug) = @_; | ||
| 751 | |||
| 752 | if (defined $debug) { | ||
| 753 | $self->{bus}->{debug} = $debug; | ||
| 754 | } | ||
| 755 | return $self->{bus}->{debug}; | ||
| 756 | } | ||
| 757 | |||
| 758 | =back | ||
| 759 | |||
| 760 | =head1 AUTHOR | ||
| 761 | |||
| 762 | Daniel V. Klein E<lt>L<dan@klein.com>E<gt> | ||
| 763 | |||
| 764 | =head1 SEE ALSO | ||
| 765 | |||
| 766 | L<http://www.modbus.org/specs.php> for the complete Modbus specifications | ||
| 767 | |||
| 768 | =cut | ||
| 769 | |||
| 770 | 'Another module by Daniel V. Klein <dan@klein.com>'; |