File Coverage

blib/lib/Protocol/Modbus/Transport/TCP.pm
Criterion Covered Total %
statement 18 48 37.5
branch 0 10 0.0
condition 0 4 0.0
subroutine 6 11 54.5
pod 4 5 80.0
total 28 78 35.9


line stmt bran cond sub pod time code
1             package Protocol::Modbus::Transport::TCP;
2              
3 1     1   594 use strict;
  1         2  
  1         28  
4 1     1   5 use warnings;
  1         1  
  1         30  
5 1     1   10 use base 'Protocol::Modbus::Transport';
  1         1  
  1         154  
6 1     1   4 use Carp ();
  1         2  
  1         15  
7 1     1   1132 use IO::Socket::INET;
  1         43385  
  1         8  
8              
9 1     1   710 use constant DEFAULT_PORT => 502;
  1         2  
  1         445  
10              
11             sub connect {
12 0     0 1   my $self = $_[0];
13 0           my $sock;
14 0           my $opt = $self->options();
15              
16 0 0         if (!$self->connected()) {
17 0           my $address = $opt->{address};
18 0   0       my $port = $opt->{port} || DEFAULT_PORT;
19              
20 0   0       $sock = IO::Socket::INET->new(
21             PeerAddr => $address,
22             PeerPort => $port,
23             Timeout => $opt->{timeout} || 3,
24             );
25              
26 0 0         if (!$sock) {
27 0           Carp::croak("Can't connect to Modbus server on $address:$port");
28 0           return (0);
29             }
30              
31             # Store socket handle inside object
32 0           $self->{_handle} = $sock;
33              
34             }
35             else {
36 0           $sock = $self->{_handle};
37             }
38              
39 0 0         return ($sock ? 1 : 0);
40             }
41              
42             sub connected {
43 0     0 0   my $self = $_[0];
44 0           return $self->{_handle};
45             }
46              
47             # Send request object
48             sub send {
49 0     0 1   my ($self, $req) = @_;
50              
51 0           my $sock = $self->{_handle};
52 0 0         return undef unless $sock;
53              
54             # Send request PDU and wait 100 msec
55 0           my $ok = $sock->send($req->pdu());
56 0           select(undef, undef, undef, 0.10);
57              
58 0           return ($ok);
59             }
60              
61             sub receive {
62 0     0 1   my ($self, $req) = @_;
63              
64             # Get socket
65 0           my $sock = $self->{_handle};
66              
67 0           $sock->recv(my $data, 256);
68              
69             #warn('Received: [' . unpack('H*', $data) . ']');
70              
71 0           return ($data);
72             }
73              
74             sub disconnect {
75 0     0 1   my $self = $_[0];
76 0           my $sock = $self->{_handle};
77 0 0         return unless $sock;
78 0           $self->{_handle} = undef;
79 0           $sock->close();
80             }
81              
82             1;