La séptima vida

...o el gato así lo espera/teme

A simple Modbus client in Perl

UPDATE: The code below has been updated to work with the latest version of Device::Modbus as of October 3, 2015.

This week ends with the test of the Modbus RTU client. I simply plugged a temperature controller to the program below and it worked! It was great!

The controller is a CH3000 from a Chinese company, Taisuo. The program below reads the temperature set-point:

#! /usr/bin/env perl

use Device::Modbus::RTU::Client;
use Data::Dumper;
use strict;
use warnings;
use v5.10;

my $client = Device::Modbus::RTU::Client->new(
    port     => '/dev/ttyUSB0',
    baudrate => 19200,
    parity   => 'none',
);

my $req = $client->read_holding_registers(
    unit     => 3
 address => 0, quantity => 1, ); say "->" . Dumper $req; $client->send_request($req); my $resp = $client->receive_response; say "<-" . Dumper $resp;

And sure enough, this is the output:

julio@julio-lap$ perl -Ilib -I../../Device-Modbus/lib examples/simple_client_rtu.pl 
->$VAR1 = bless( {
                 'unit' => 3,
                 'function' => 'Read Holding Registers',
                 'quantity' => 1,
                 'address' => 0,
                 'code' => 3
               }, 'Device::Modbus::Request' );

<-$VAR1 = bless( {
                 'unit' => 3,
                 'crc' => 47289,
                 'message' => bless( {
                                       'bytes' => 2,
                                       'function' => 'Read Holding Registers',
                                       'values' => [
                                                     400
                                                   ],
                                       'code' => 3
                                     }, 'Device::Modbus::Response' )
               }, 'Device::Modbus::RTU::ADU' );

This little program does not use the ADU interface, which allows for reading directly the 'values' and the function fields. It also lets you know if the request was successful.