blib/lib/Net/IEC104.pm

filter: Statementstmt 88.2% 15 / 17 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 6 / 6 Podpod n/a totaltotal 91.3% 21 / 23 CC 1 SCAR 0.5
CC
1
Cov
88%
BEGIN
1.3
BEGIN
1.0
BEGIN
1.0
CRAP 1.0
↑ Summary
1 package Net::IEC104;
2  
3 1 ▶use 5.008008;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 1 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 1 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 1 ▶use Carp;
Subroutine BEGIN: called CC=1 SCAR=0.0
7 1 ▶use IO::Socket::INET;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 0 ▶use Event::Lib;
Subroutine BEGIN: called CC=1 SCAR=2.6
9 use Date::Manip;
10 use Time::HiRes qw/ gettimeofday tv_interval /;
11  
12 require Exporter;
13  
14 our @ISA = qw(Exporter);
15  
16 # Items to export into callers namespace by default. Note: do not export
17 # names by default without a very good reason. Use EXPORT_OK instead.
18 # Do not simply export all your public functions/methods/constants.
19  
20 # This allows declaration use Net::IEC104 ':all';
21 # If you do not need this, moving things directly into @EXPORT or @EXPORT_OK
22 # will save memory.
23 our %EXPORT_TAGS = (
24 'all' => [
25 qw(
26 &connect &listen &send &main_loop &disconnect
27 )
28 ]
29 );
30  
31 our @EXPORT_OK = ( @{ $EXPORT_TAGS{'all'} } );
32  
33 our @EXPORT = qw(
34  
35 );
36  
37 our $VERSION = '0.03';
38  
39 ###############################################################################
40  
41 $| = 1;
42  
43 our $debug = 0;
44 our $MAX_ASDU_SIZE = 248;
45 our $MAX_S_QUEUE = 100;
46  
47 our %asdu_type = (
48  
49 # Infromation to control direction, ASDU: 1-44
50 30 => {
51 "size" => 8,
52 "name" => "M_SP_TB_1",
53 type => "TS",
54 "parse_cb" => \&parse_asdu_type_0_44,
55 "write_cb" => \&send_asdu_type_0_44
56 },
57 35 => {
58 "size" => 10,
59 "name" => "M_ME_TE_1",
60 type => "TI",
61 "parse_cb" => \&parse_asdu_type_0_44,
62 "write_cb" => \&send_asdu_type_0_44
63 },
64 36 => {
65 "size" => 12,
66 "name" => "M_ME_TF_1",
67 type => "TI",
68 "parse_cb" => \&parse_asdu_type_0_44,
69 "write_cb" => \&send_asdu_type_0_44
70 },
71 37 => {
72 "size" => 12,
73 "name" => "M_IT_TB_1",
74 type => "TII",
75 "parse_cb" => \&parse_asdu_type_0_44,
76 "write_cb" => \&send_asdu_type_0_44
77 },
78  
79 # System information to controlled direction, ASDU: 100-109
80 100 => {
81 "size" => 1,
82 "name" => "C_IC_NA_1",
83 type => "",
84 "parse_cb" => \&parse_asdu_type_100,
85 "write_cb" => \&send_asdu_type_100
86 },
87 103 => {
88 "size" => 7,
89 "name" => "C_CS_NA_1",
90 type => "",
91 "parse_cb" => \&parse_asdu_type_103,
92 "write_cb" => \&send_asdu_type_103
93 },
94 );
95  
96 # Constructor
97 sub new {
98 my $self = shift;
99 my %h = @_;
100 my $class = ref($self) || $self;
101 croak "wrong type of Net::IEC104"
102 if ( $h{type} ne "slave" and $h{type} ne "master" );
103  
104 $h{retry_timeout} = ( exists $h{retry_timeout} ) ? $h{retry_timeout} : 5;
105 $h{ip} = ( exists $h{ip} ) ? $h{ip} : "0.0.0.0";
106 $h{port} = ( exists $h{port} ) ? $h{port} : "2404";
107  
108 bless \%h, $class;
109 }
110  
111 # Print debug messages
112 sub DEBUG {
113 my $d = shift;
114 if ( $debug >= $d ) {
115 print @_;
116 if ( $d < 0 ) {
117 printf "<-- at %s:%s", (caller)[ 1, 2 ];
118 }
119 unless ( $_[$#_] =~ /\s$/ ) {
120 print "\n";
121 }
122 }
123 }
124  
125 # Pack ip-port pair as ID of connection
126 sub get_id {
127 my $sock = shift;
128 return pack( "C4S", split( /\./, $sock->peerhost ), $sock->peerport );
129 }
130  
131 # Unpack ip-port pair to printable form
132 sub sid2hex {
133 return join( ".", map { sprintf "%d", $_ } unpack( "C4S", shift ) );
134 }
135  
136 # Print hex-codes of raw data
137 sub raw2hex {
138 return join( ",", map { sprintf "%02X", $_ } unpack( "C*", shift ) );
139 }
140  
141 # convert from cp56_2a format of time to gettimeofday
142 sub cp56_2a_2_time {
143 my $data = shift;
144 my @tm = unpack( "SC5", $data );
145 my $tm = Date_SecsSince1970GMT(
146 $tm[4] & 0xF,
147 $tm[3] & 0x1F,
148 2000 + ( $tm[5] & 0x7F ),
149 $tm[2] & 0x1F,
150 $tm[1] & 0x3F,
151 int( $tm[0] / 1000 )
152 );
153 my $ms = ( $tm[0] % 1000 ) * 1000;
154 return ( $tm, $ms );
155 }
156  
157 # convert from gettimeofday format to cp56_2a
158 sub time_2_cp56_2a {
159 my $tm = shift;
160 my $ms = shift;
161 $ms = int( $ms / 1000 );
162 my @tm = localtime($tm);
163 return pack( "SC5",
164 ( $tm[0] * 1000 + $ms ),
165 $tm[1],
166 $tm[2] | ( $tm[8] << 7 ),
167 $tm[3] | ( $tm[6] << 5 ),
168 ++$tm[4], $tm[5] % 100 );
169 }
170  
171 # debug info about connection
172 sub sidinfo {
173 my $self = shift;
174 my $sid = shift;
175 my $report;
176 my $s = \%{ $self->{sids}{$sid} };
177  
178 $report =
179 "=====================\n"
180 . "TYPE: "
181 . $s->{type} . "\n"
182 . sprintf( "IP: %d.%d.%d.%d\n" . "PORT: %d\n", unpack( "C4S", $sid ) )
183 . "UFUNC: "
184 . $s->{ufunc} . "\n"
185 . "VS: "
186 . $s->{vs} . "\n"
187 . "VR: "
188 . $s->{vr} . "\n"
189 . "AS: "
190 . $s->{as} . "\n"
191 . "AR: "
192 . $s->{ar} . "\n"
193 . "s_queue: "
194 . $#{ $s->{s_queue} } . "\n";
195 foreach my $timer (
196 "t0_timer", "t1_timer", "t2_timer", "t3_timer",
197 "ci_timer", "sync_timer"
198 )
199 {
200 $report .= $timer . ": ";
201 if ( $s->{$timer}->pending ) {
202 $report .= "pending\n";
203 }
204 else {
205 $report .= "not started\n";
206 }
207 }
208 return $report;
209 }
210  
211 # public method listen()
212 # start IEC slave station (server)
213 sub listen {
214 my $self = shift;
215 my %h = @_;
216 carp "called without a reference" if ( !ref($self) );
217  
218 my $server = IO::Socket::INET->new(
219 LocalAddr => $self->{ip},
220 LocalPort => $self->{port},
221 Proto => 'tcp',
222 ReuseAddr => SO_REUSEADDR,
223 Listen => 1,
224 Blocking => 0,
225 ) or carp $@;
226 return -1 unless ($server);
227 &DEBUG( 1, "Listen on ", $self->{ip}, ":", $self->{port} );
228 my $main =
229 event_new( $server, EV_READ | EV_PERSIST, \&handle_incoming, $self );
230 $main->add;
231 }
232  
233 # public method connect()
234 # start IEC master session
235 sub connect {
236 my $self = shift;
237 carp "called without a reference" if ( !ref($self) );
238  
239 my $client = IO::Socket::INET->new(
240 Proto => 'tcp',
241 PeerAddr => $self->{ip},
242 PeerPort => $self->{port},
243 Blocking => 0
244 ) or carp $@;
245  
246 my $main = event_new( $client, EV_WRITE, \&on_connect, $self );
247 $main->add(2);
248 }
249  
250 sub on_connect {
251 my ( $e, $type, $self ) = @_;
252 my $error = 1;
253  
254 if ( $type == EV_TIMEOUT ) {
255 &DEBUG( 0, "Can't connect to ",
256 $self->{ip}, ":", $self->{port}, ", connection timeout" );
257 }
258 elsif ( $type == EV_WRITE ) {
259 my $client = $e->fh;
260 unless ( $client->connected ) {
261 &DEBUG( 0, "Can't connect to ",
262 $self->{ip}, ":", $self->{port}, ", connection rejected" );
263 }
264 else {
265 $self->{retry_count} = 0;
266 $error = 0;
267 &DEBUG( 1, "connected to ", $self->{ip}, ":", $self->{port} );
268 my $sid = &get_id($client);
269 my $main = event_new( $client, EV_READ | EV_PERSIST,
270 \&handle_client, $self, $sid );
271 $self->init_new_conn(
272 sid => $sid,
273 event => $main,
274 type => "MASTER"
275 );
276 $main->add;
277  
278 $self->frame_u_send( $sid, "STARTDTACT" );
279 }
280 }
281  
282 if ( $error && $self->{persist} ) {
283 my $timer = timer_new( \&reconnect, $self );
284 $timer->add( $self->{retry_timeout} );
285 }
286 }
287  
288 # Main event loop
289 sub main_loop {
290 event_mainloop;
291 }
292  
293 # Sync time
294 sub sync_time {
295 my ( $cause, $s, $data );
296 my $self = shift;
297 my $csid = undef;
298  
299 if ( $#_ != -1 && defined( $_[0] ) ) {
300 $csid = shift;
301 }
302  
303 if ( $self->{type} eq "master" ) {
304 $cause = 6; # activation
305 }
306 else {
307 $cause = 3; # sporadic
308 }
309  
310 foreach my $sid ( keys %{ $self->{sids} } ) {
311 next if ( defined($csid) && $csid ne $sid );
312 $s = \%{ $self->{sids}{$sid} };
313 &DEBUG( 2, "Sync time for CA: ",
314 $s->{ca}, ", My current time: ", time() );
315 $data =
316 pack( "C2S3C", 103, 1, $cause, $s->{ca}, 1, 0 )
317 . &time_2_cp56_2a(gettimeofday);
318 $self->frame_i_send( $sid, $data );
319 }
320 }
321  
322 # handle incoming connections
323 sub handle_incoming {
324 my $e = shift;
325 my $etype = shift;
326 my $self = shift;
327 my $h = $e->fh;
328 my $client = $h->accept or croak "$!";
329 $client->blocking(0);
330 &DEBUG( 1, "accept connection from ",
331 $client->peerhost, ":", $client->peerport );
332  
333 my $sid = &get_id($client);
334  
335 # set up a new event that watches the client socket
336 my $event =
337 event_new( $client, EV_READ | EV_PERSIST, \&handle_client, $self, $sid );
338 $self->init_new_conn(
339 sid => $sid,
340 event => $event,
341 type => "SLAVE"
342 );
343 $event->add;
344 }
345  
346 # init new structure for connection
347 sub init_new_conn {
348 my $self = shift;
349 my %h = @_;
350 my $sid = $h{"sid"} or croak $@;
351  
352 $self->{sids}{$sid} = ();
353 my $s = \%{ $self->{sids}{$sid} };
354  
355 $s->{type} = ( $h{type} ) ? $h{type} : "SLAVE";
356 $s->{event} = $h{"event"} or croak $@;
357 $s->{ufunc} = ( $self->{ufunc} ) ? $self->{ufunc} : "STOPDT";
358 $s->{ca} = ( $self->{ca} ) ? $self->{ca} : 1; # common address of asdu
359 $s->{t0} = ( $self->{t0} ) ? $self->{t0} : 30; # t0 timeout, sec
360 $s->{t1} = ( $self->{t1} ) ? $self->{t1} : 15; # t1 timeout, sec
361 $s->{t2} = ( $self->{t2} ) ? $self->{t2} : 10; # t2 timeout, sec
362 $s->{t3} = ( $self->{t3} ) ? $self->{t3} : 20; # t3 timeout, sec
363 $s->{w} = ( $self->{w} ) ? $self->{w} : 8; # w
364 $s->{k} = ( $self->{k} ) ? $self->{k} : 12; # k
365 $s->{vs} = 0; # Number S sended
366 $s->{vr} = 0; # Number S received
367 $s->{as} = 0; # Number S ack by me
368 $s->{ar} = 0; # Number S ack by peer
369  
370 $s->{rcb} =
371 ( $self->{read_callback} ) ? $self->{read_callback} : \&default_read_cb;
372 $s->{wcb} =
373 ( $self->{write_callback} )
374 ? $self->{write_callback}
375 : \&default_write_cb;
376  
377 $s->{ts_fn} = ( $self->{ts_func_num} ) ? $self->{ts_func_num} : 30;
378 $s->{ti_fn} = ( $self->{ti_func_num} ) ? $self->{ti_func_num} : 36;
379 $s->{tii_fn} = ( $self->{tii_func_num} ) ? $self->{tii_func_num} : 37;
380  
381 $s->{s_queue} = []; # Send queue
382 $s->{r_buf} = undef; # Receive buffer
383  
384 $s->{t0_timer} = timer_new( \&t0_timer_run, $self, $sid );
385 $s->{t1_timer} = timer_new( \&t1_timer_run, $self, $sid );
386 $s->{t2_timer} = timer_new( \&t2_timer_run, $self, $sid );
387 $s->{t3_timer} = timer_new( \&t3_timer_run, $self, $sid );
388  
389 $s->{ci_timeout} =
390 ( $self->{ci_timeout} ) ? $self->{ci_timeout} : 5 * 60; # CI timeout, sec
391 $s->{sync_timeout} =
392 ( $self->{sync_timeout} )
393 ? $self->{sync_timeout}
394 : 60 * 60; # Sync timeout, sec
395 $s->{ci_timer} = timer_new( \&ci_timer_run, $self, $sid );
396 $s->{sync_timer} = timer_new( \&sync_timer_run, $self, $sid );
397  
398 $s->{time_diff} = 0; # diff in time between kp and control station
399  
400 $s->{t0_timer}->add( $s->{t0} ); # timeout of init connection
401 }
402  
403 # Invoked when the client's socket becomes readable
404 sub handle_client {
405 my $data;
406  
407 my $e = shift;
408 my $etype = shift;
409 my $self = shift;
410 my $sid = shift;
411 my $h = $e->fh;
412 my $s = \%{ $self->{sids}{$sid} };
413  
414 unless ( $h->connected ) {
415 &DEBUG( 9, "client disconnected" );
416 $self->disconnect($sid);
417 return;
418 }
419 if ( eof($h) ) {
420 &DEBUG( 1, "connection not readable" );
421 $self->disconnect($sid);
422 return;
423 }
424  
425 if ( defined( $self->{sids}{$sid}{r_buf} ) ) {
426 $data = $s->{r_buf};
427 $s->{r_buf} = undef;
428 }
429  
430 while (<$h>) {
431 $data .= $_;
432 }
433  
434 my ( $start, $length, $bits ) = unpack( "C3", $data );
435 while (1) {
436 if ( $start != 0x68 || length($data) < 3 ) {
437  
438 #error in Net::IEC104 packet
439 &DEBUG( 11, raw2hex($data) );
440 &DEBUG(
441 1,
442 "error in Net::IEC104 chunk: START: ",
443 $start,
444 "; LENGTH: ",
445 defined($length) ? $length : 0,
446 "; DATA SIZE: ",
447 length($data)
448 );
449 $self->disconnect($sid);
450 return;
451 }
452  
453 # retransmission (part of data will be received in next packet)
454 # put data in receive buffer
455 if ( $length > length($data) - 2 ) {
456 &DEBUG( 2,
457 "receive fragmented packet, save data in buffer and wait next chunk"
458 );
459 &DEBUG( 2, "LENGTH: ", length($data) - 2,
460 " of ", $length, " bytes" );
461 $s->{r_buf} = $data;
462 return;
463 }
464 my $curdata = substr( $data, 0, $length + 2 );
465 &DEBUG( 11, raw2hex($curdata) );
466  
467 # Receiving packet of any type restart a T3 timer
468 if ( $s->{t3_timer}->pending ) {
469 $s->{t3_timer}->remove;
470 }
471 $s->{t3_timer}->add( $s->{t3} );
472  
473 if ( ( $bits & 1 ) == 0 ) {
474  
475 # frame type I
476 $self->frame_i_recv( $sid, $curdata );
477 }
478 elsif ( ( $bits & 3 ) == 1 ) {
479  
480 # frame type S
481 $self->frame_s_recv( $sid, $curdata );
482 }
483 elsif ( ( $bits & 3 ) == 3 ) {
484  
485 # frame type U
486 $self->frame_u_recv( $sid, $curdata );
487 }
488 else {
489 &DEBUG( 0, "unknown frame type" );
490 }
491 $data = substr( $data, $length + 2 );
492 return unless ($data);
493 ( $start, $length, $bits ) = unpack( "C3", $data );
494 }
495 }
496  
497 # public method disconnect()
498 # close client or server connection
499 sub disconnect {
500 my $self = shift;
501 my ( $e, $h );
502 my $csid = undef;
503  
504 if ( $#_ != -1 && defined( $_[0] ) ) {
505 $csid = shift;
506 }
507  
508 foreach my $sid ( keys %{ $self->{sids} } ) {
509 next if ( defined($csid) && $csid ne $sid );
510 $e = $self->{sids}{$sid}{event};
511 $h = $e->fh;
512 &DEBUG( 1, "disconnected from ", &sid2hex($sid) );
513 close $h;
514 $e->remove;
515 $self->{sids}{$sid}{t0_timer}->remove;
516 $self->{sids}{$sid}{t1_timer}->remove;
517 $self->{sids}{$sid}{t2_timer}->remove;
518 $self->{sids}{$sid}{t3_timer}->remove;
519 $self->{sids}{$sid}{ci_timer}->remove;
520 $self->{sids}{$sid}{sync_timer}->remove;
521 delete $self->{sids}{$sid};
522  
523 if ( $self->{type} eq "master" && $self->{persist} != 0 ) {
524 &DEBUG( 11, "persist is true, reconnect..." );
525 $self->connect();
526 }
527 else {
528 &DEBUG( 11, "persist is not true, dont reconnect..." );
529 }
530 }
531 }
532  
533 sub reconnect {
534 my $e = shift;
535 my $etype = shift;
536 my $self = shift;
537 my $timer;
538  
539 $self->{retry_count}++;
540 &DEBUG(
541 1, "reconnect to ",
542 $self->{ip}, ":", $self->{port}, " after fail... Attempt: ",
543 $self->{retry_count}
544 );
545 $self->connect;
546 }
547  
548 # public method send()
549 # send spontaneous data to all client connections (only for SLAVE)
550 sub send {
551 my $self = shift;
552 my $ca = shift;
553 my %h = @_;
554 return if ( $self->{type} ne "slave" );
555 foreach my $sid ( keys %{ $self->{sids} } ) {
556 next
557 if ( !defined( $self->{sids}{$sid} )
558 || $self->{sids}{$sid}{ufunc} eq "STOPDT"
559 || $self->{sids}{$sid}{ca} != $ca );
560 if ( exists $h{"TI"} && $self->{sids}{$sid}{ti_fn} != 0 ) {
561 &{ $asdu_type{ $self->{sids}{$sid}{ti_fn} }{write_cb} }( $self,
562 $sid, 3, $self->{sids}{$sid}{ti_fn}, $h{"TI"} );
563 }
564 if ( exists $h{"TS"} && $self->{sids}{$sid}{ts_fn} != 0 ) {
565 &{ $asdu_type{ $self->{sids}{$sid}{ts_fn} }{write_cb} }( $self,
566 $sid, 3, $self->{sids}{$sid}{ts_fn}, $h{"TS"} );
567 }
568 if ( exists $h{"TII"} && $self->{sids}{$sid}{tii_fn} != 0 ) {
569 &{ $asdu_type{ $self->{sids}{$sid}{tii_fn} }{write_cb} }( $self,
570 $sid, 3, $self->{sids}{$sid}{tii_fn}, $h{"TII"} );
571 }
572 }
573 }
574  
575 sub t0_timer_run {
576 my $e = shift;
577 my $type = shift;
578 my $self = shift;
579 my $sid = shift;
580  
581 &DEBUG( 1, "sid: ", &sid2hex($sid), ". t0 timer run" );
582 $self->disconnect($sid);
583 }
584  
585 sub t1_timer_run {
586 my $e = shift;
587 my $type = shift;
588 my $self = shift;
589 my $sid = shift;
590 &DEBUG( 1, "sid: ", &sid2hex($sid), ". t1 timer run" );
591 $self->disconnect($sid);
592 }
593  
594 sub t2_timer_run {
595 my $e = shift;
596 my $type = shift;
597 my $self = shift;
598 my $sid = shift;
599 &DEBUG( 2, "t2 timer run" );
600 $self->frame_s_send($sid);
601 }
602  
603 sub t3_timer_run {
604 my $e = shift;
605 my $type = shift;
606 my $self = shift;
607 my $sid = shift;
608 my $s = \%{ $self->{sids}{$sid} };
609 &DEBUG( 1, "sid: ", &sid2hex($sid), ". t3 timer run" );
610 $self->frame_u_send( $sid, "TESTFRACT" );
611 unless ( $s->{t1_timer}->pending ) {
612 $s->{t1_timer}->add( $s->{t1} );
613 }
614 }
615  
616 sub ci_timer_run {
617 my $e = shift;
618 my $type = shift;
619 my $self = shift;
620 my $sid = shift;
621 &DEBUG( 1, "sid: ", &sid2hex($sid), ". ci timer run" );
622 $self->frame_i_send( $sid,
623 pack( "C2S3C2", 100, 1, 6, $self->{sids}{$sid}{ca}, 0, 0, 20 ) );
624 }
625  
626 sub sync_timer_run {
627 my $e = shift;
628 my $type = shift;
629 my $self = shift;
630 my $sid = shift;
631 &DEBUG( 1, "sid: ", &sid2hex($sid), ". sync timer run" );
632 $self->sync_time($sid);
633 }
634  
635 # send frame type U
636 sub frame_u_send {
637 my $self = shift;
638 my $sid = shift;
639 my $func = shift;
640 my $bits = 3;
641  
642 &DEBUG( 3, "send frame type U, function ", $func, ": " );
643 if ( $func eq "STARTDTACT" ) {
644 $bits |= 1 << 2;
645 }
646 elsif ( $func eq "STARTDTCON" ) {
647 $bits |= 1 << 3;
648 }
649 elsif ( $func eq "STOPDTACT" ) {
650 $bits |= 1 << 4;
651 }
652 elsif ( $func eq "STOPDTCON" ) {
653 $bits |= 1 << 5;
654 }
655 elsif ( $func eq "TESTFRACT" ) {
656 $bits |= 1 << 6;
657 }
658 elsif ( $func eq "TESTFRCON" ) {
659 $bits |= 1 << 7;
660 }
661  
662 return unless ( defined( $self->{sids}{$sid}{event} ) );
663 my $sock = $self->{sids}{$sid}{event}->fh;
664 my $data = pack( "C6", 0x68, 4, $bits, 0, 0, 0 );
665 &DEBUG( 3, raw2hex($data) );
666 print $sock $data;
667 }
668  
669 sub frame_u_recv {
670 my $self = shift;
671 my $sid = shift;
672 my $data = shift;
673  
674 my ($bits) = ( unpack( "C3", $data ) )[2];
675 &DEBUG( 3, "received frame type U, function " );
676  
677 if ( $bits & 1 << 2 ) {
678  
679 # STARTDT ACT
680 &DEBUG( 3, "STARTDTACT" );
681 if ( $self->{sids}{$sid}{type} ne "SLAVE" ) {
682 &DEBUG( 0, "master receive STARTDT ACT" );
683 return -1;
684 }
685  
686 # T0 timer removed after init
687 $self->{sids}{$sid}{t0_timer}->remove;
688 $self->{sids}{$sid}{ufunc} = "STARTDT";
689 $self->frame_u_send( $sid, "STARTDTCON" );
690 }
691 elsif ( $bits & 1 << 3 ) {
692  
693 # STARTDT CON
694 &DEBUG( 3, "STARTDTCON" );
695 if ( $self->{sids}{$sid}{type} ne "MASTER" ) {
696 return -1;
697 }
698  
699 # Slave answer on init -> remove T0 timer
700 $self->{sids}{$sid}{t0_timer}->remove;
701  
702 $self->{sids}{$sid}{ufunc} = "STARTDT";
703  
704 # Connection activated.
705 # Sync time
706 $self->sync_time($sid);
707  
708 # Start common interogation
709 $self->frame_i_send( $sid,
710 pack( "C2S3C2", 100, 1, 6, $self->{sids}{$sid}{ca}, 0, 0, 20 ) );
711  
712 }
713 elsif ( $bits & 1 << 4 ) {
714  
715 # STOPDT ACT
716 &DEBUG( 3, "STOPDTACT" );
717 if ( $self->{sids}{$sid}{type} ne "SLAVE" ) {
718 return -1;
719 }
720 $self->{sids}{$sid}{ufunc} = "STOPDT";
721 $self->frame_u_send( $sid, "STOPDTCON" );
722 }
723 elsif ( $bits & 1 << 5 ) {
724  
725 # STOPDT CON
726 &DEBUG( 3, "STOPDTCON" );
727 if ( $self->{sids}{$sid}{type} ne "MASTER" ) {
728 return -1;
729 }
730 $self->{sids}{$sid}{ufunc} = "STOPDT";
731 }
732 elsif ( $bits & 1 << 6 ) {
733  
734 # TESTFR ACT
735 &DEBUG( 3, "TESTFRACT" );
736 $self->frame_u_send( $sid, "TESTFRCON" );
737 }
738 elsif ( $bits & 1 << 7 ) {
739  
740 # TESTFR CON
741 &DEBUG( 3, "TESTFRCON" );
742 $self->{sids}{$sid}{t1_timer}->remove;
743 }
744 else {
745 &DEBUG( 3, "unknown" );
746 &DEBUG( 0, "Error in received U frame: unknown type" );
747 }
748 }
749  
750 # send frame type S
751 sub frame_s_send {
752 my $self = shift;
753 my $sid = shift;
754 if ( $self->{sids}{$sid}{as} == $self->{sids}{$sid}{vr} ) {
755 &DEBUG(
756 2,
757 "not sending frame type S, AS=VR (",
758 $self->{sids}{$sid}{as},
759 "=", $self->{sids}{$sid}{vr}, ")"
760 );
761 return;
762 }
763 &DEBUG( 3, "send frame type S(", $self->{sids}{$sid}{vr}, ")" );
764 my $sock = $self->{sids}{$sid}{event}->fh;
765 print $sock pack( "C4S", 0x68, 4, 1, 0, $self->{sids}{$sid}{vr} << 1 );
766 $self->{sids}{$sid}{as} = $self->{sids}{$sid}{vr};
767 }
768  
769 # receive frame type S
770 sub frame_s_recv {
771 my $self = shift;
772 my $sid = shift;
773 my $data = shift;
774  
775 my ($nr) = ( unpack( "C2S2", $data ) )[3];
776 $nr >>= 1;
777 if ( ( ( $self->{sids}{$sid}{vs} - $nr + 32768 ) % 32768 ) >
778 $self->{sids}{$sid}{k} )
779 {
780 &DEBUG(
781 0, "wrong N(R) number in S-ack received: ",
782 $nr,
783 ". Current N(S) = ",
784 $self->{sids}{$sid}{vs}
785 );
786 $self->disconnect($sid);
787 return;
788 }
789 &DEBUG( 3, "received frame type S(", $nr, ")" );
790 $self->{sids}{$sid}{ar} = $nr;
791 $self->{sids}{$sid}{t1_timer}->remove;
792  
793 $self->flush_send_queue($sid);
794 }
795  
796 sub flush_send_queue {
797 my $ret;
798 my $self = shift;
799 my $sid = shift;
800  
801 #return if ($#{$self->{sids}{$sid}{s_queue}} == -1);
802 #for my $i (0 .. $#{$self->{sids}{$sid}{s_queue}}) {
803 #$ret = $self->frame_i_send($sid,undef);
804 #last if ($ret != 0);
805 #}
806 while ( $#{ $self->{sids}{$sid}{s_queue} } != -1 ) {
807 last if ( $self->frame_i_send( $sid, undef ) );
808 }
809 }
810  
811 sub frame_i_send {
812 my $self = shift;
813 my $sid = shift;
814 my $asdu = shift;
815  
816 unless ( exists( $self->{sids}{$sid} ) ) {
817 &DEBUG( 0, "frame_i_send(): error, connection ",
818 &sid2hex($sid), " already dead\n" );
819 for my $j ( 0 .. 3 ) {
820 &DEBUG( 0, join( "->", ( caller($j) )[ 0, 1, 2, 3 ] ) );
821 }
822 return -1;
823 }
824 if ( $self->{sids}{$sid}{vs} ==
825 ( $self->{sids}{$sid}{ar} + $self->{sids}{$sid}{k} ) % 32768 )
826 {
827 &DEBUG( 2, "reached k, no frames will be sent" );
828 if ( $#{ $self->{sids}{$sid}{s_queue} } + 1 > $MAX_S_QUEUE ) {
829 &DEBUG( 0, $self->sidinfo($sid) );
830 &DEBUG( 0, "send queue overloaded, asdu dropped" );
831 $self->disconnect($sid);
832 return 2;
833 }
834 elsif ( defined($asdu) ) {
835 push @{ $self->{sids}{$sid}{s_queue} }, $asdu;
836 if ( $self->{sids}{$sid}{type} eq "SLAVE"
837 && $#{ $self->{sids}{$sid}{s_queue} } > $MAX_S_QUEUE * 0.9 )
838 {
839 &DEBUG(
840 0, &sid2hex($sid),
841 ", queue increased: ",
842 ( $#{ $self->{sids}{$sid}{s_queue} } + 1 )
843 );
844 }
845 &DEBUG(
846 2,
847 "asdu queued (No:",
848 $#{ $self->{sids}{$sid}{s_queue} } + 1, ")"
849 );
850 }
851 return 1;
852 }
853 unless ( defined($asdu) ) {
854 $asdu = shift( @{ $self->{sids}{$sid}{s_queue} } )
855 if ( $#{ $self->{sids}{$sid}{s_queue} } >= 0 );
856 unless ( defined($asdu) ) {
857 &DEBUG( 0, "Error: empty asdu" );
858 return 3;
859 }
860 else {
861 if ( $self->{sids}{$sid}{type} eq "SLAVE"
862 && $#{ $self->{sids}{$sid}{s_queue} } > $MAX_S_QUEUE * 0.9 )
863 {
864 &DEBUG(
865 0, &sid2hex($sid),
866 ", queue reduced: ",
867 ( $#{ $self->{sids}{$sid}{s_queue} } + 1 )
868 );
869 }
870 &DEBUG( 3, "send frame type I from queue: " );
871 }
872 }
873 else {
874 &DEBUG( 3, "send frame type I: " );
875 }
876  
877 $self->{sids}{$sid}{t1_timer}->remove;
878 $self->{sids}{$sid}{t1_timer}->add( $self->{sids}{$sid}{t1} );
879  
880 my $ns = $self->{sids}{$sid}{vs} << 1;
881 my $nr = $self->{sids}{$sid}{vr} << 1;
882 my $sock = $self->{sids}{$sid}{event}->fh;
883 my $data = pack( "C2S2", 0x68, 4 + length($asdu), $ns, $nr ) . $asdu;
884 DEBUG( 3, raw2hex($data) );
885 print $sock $data;
886  
887 $self->{sids}{$sid}{vs} = ( $self->{sids}{$sid}{vs} + 1 ) % 32768;
888 return 0;
889 }
890  
891 sub frame_i_recv {
892 my $self = shift;
893 my $sid = shift;
894 my $data = shift;
895 DEBUG( 3, "received frame type I " );
896 if ( $self->{sids}{$sid}{ufunc} ne "STARTDT" ) {
897 DEBUG( 0, "Error: no STARTDT in current connection" );
898 return -1;
899 }
900  
901 my ( $ns, $nr ) = ( unpack( "C2S2", $data ) )[ 2, 3 ];
902 $ns >>= 1;
903 $nr >>= 1;
904 DEBUG( 3, "NS=$ns,NR=$nr" );
905 if ( $ns != $self->{sids}{$sid}{vr} ) {
906 &DEBUG(
907 0,
908 "Error: Expect N(S)=",
909 $self->{sids}{$sid}{vr},
910 ", but receive: ",
911 $ns, ". Packet lost or reordered"
912 );
913 return -1;
914 }
915 if ( ( $nr != $self->{sids}{$sid}{ar} )
916 && ( ( $nr - $self->{sids}{$sid}{ar} + 32768 ) % 32768 ) <=
917 $self->{sids}{$sid}{k}
918 && ( ( $self->{sids}{$sid}{vs} - $nr + 32768 ) % 32768 ) <=
919 $self->{sids}{$sid}{k} )
920 {
921 $self->{sids}{$sid}{ar} = $nr;
922 $self->{sids}{$sid}{t1_timer}->remove;
923 }
924  
925 $self->{sids}{$sid}{t2_timer}->remove();
926 $self->{sids}{$sid}{t2_timer}->add( $self->{sids}{$sid}{t2} );
927  
928 $self->{sids}{$sid}{vr} = ( $ns + 1 ) % 32768;
929 if (
930 ( $self->{sids}{$sid}{vr} - $self->{sids}{$sid}{as} + 32768 ) % 32768 ==
931 $self->{sids}{$sid}{w} )
932 {
933 $self->frame_s_send($sid);
934 }
935  
936 $self->parse_asdu( $sid, substr( $data, 6 ) );
937 }
938  
939 sub parse_asdu {
940 my $self = shift;
941 my $sid = shift;
942 my $asdu = shift;
943  
944 my $i = \%{ $self->{sids}{$sid}{i} };
945 my $kps;
946  
947 &DEBUG( 12, "parse_asdu(): ", raw2hex($asdu) );
948 ( $i->{id}, $kps, $i->{cause}, $i->{ca} ) = unpack( "C2S2", $asdu );
949 $i->{sq} = ( $kps & 1 << 7 ) >> 7;
950 $i->{nobj} = $kps & 0x7F;
951 $i->{cause} &= 0xFF;
952 &DEBUG( 3, "ID: ", sprintf( "%02X", $i->{id} ), ", " );
953 &DEBUG( 3, "SQ: ", $i->{sq}, ", " );
954 &DEBUG( 3, "NObj: ", sprintf( "%02X", $i->{nobj} ), ", " );
955 &DEBUG( 3, "Cause: ", sprintf( "%02X", $i->{cause} ), ", " );
956 &DEBUG( 3, "C.Addr ASDU: ", sprintf( "%02X", $i->{ca} ) );
957  
958 unless ( exists $asdu_type{ $i->{id} } ) {
959 &DEBUG( -1, "not implemented type ", $i->{id} );
960 return;
961 }
962  
963 if ( $i->{sq} == 0 ) {
964  
965 # Numerous information objects
966 for my $j ( 1 .. $i->{nobj} ) {
967 my $k = ( $j - 1 ) * ( 3 + $asdu_type{ $i->{id} }{size} );
968 ( $i->{obj}{$j}{ioa}, $i->{obj}{$j}{ioa2} ) =
969 unpack( "SC", substr( $asdu, 6 + $k, 3 ) );
970 $i->{obj}{$j}{data} =
971 substr( $asdu, 6 + 3 + $k, $asdu_type{ $i->{id} }{size} );
972 }
973 }
974 else {
975  
976 # One object, numerous elements
977 # <{TODO}>
978 &DEBUG( -1, "not implemented code" );
979 }
980 &{ $asdu_type{ $i->{id} }{parse_cb} }( $self, $sid );
981 }
982  
983 sub default_read_cb {
984 DEBUG( 1, "default_read_cb()" );
985 }
986  
987 sub default_write_cb {
988 DEBUG( 1, "default_write_cb()" );
989 return ( "TS" => { "1" => [ "0", gettimeofday ] } );
990 }
991  
992 sub parse_asdu_type_100 {
993 my $self = shift;
994 my $sid = shift;
995 my $s = \%{ $self->{sids}{$sid} };
996 my $i = \%{ $s->{i} };
997 if ( $i->{cause} == 6 ) {
998 &DEBUG( 0, &sid2hex($sid), " [100] activation" );
999  
1000 # drop outgoing queue
1001 if ( $#{ $self->{sids}{$sid}{s_queue} } >= 0 ) {
1002 &DEBUG(
1003 0, &sid2hex($sid), " drop ",
1004 ( $#{ $self->{sids}{$sid}{s_queue} } + 1 ),
1005 " asdu from queue because of activation"
1006 );
1007 $self->{sids}{$sid}{s_queue} = [];
1008 }
1009  
1010 # send accept
1011 $s->{ca} = $i->{ca};
1012 my $data = pack( "C2S3C",
1013 100, 1, 7, $i->{ca},
1014 $i->{obj}{1}{ioa},
1015 $i->{obj}{1}{ioa2} )
1016 . $i->{obj}{1}{data};
1017 $self->frame_i_send( $sid, $data );
1018  
1019 # 1. Send whole database
1020 my %h = &{ $s->{wcb} }( $self, $s->{ca} );
1021  
1022 if ( exists $h{"TI"} && $s->{ti_fn} != 0 ) {
1023 &{ $asdu_type{ $s->{ti_fn} }{write_cb} }( $self, $sid, 3,
1024 $s->{ti_fn}, $h{"TI"} );
1025 }
1026 if ( exists $h{"TS"} && $s->{ts_fn} != 0 ) {
1027 &{ $asdu_type{ $s->{ts_fn} }{write_cb} }( $self, $sid, 3,
1028 $s->{ts_fn}, $h{"TS"} );
1029 }
1030 if ( exists $h{"TII"} && $s->{tii_fn} != 0 ) {
1031 &{ $asdu_type{ $s->{tii_fn} }{write_cb} }( $self, $sid, 3,
1032 $s->{tii_fn}, $h{"TII"} );
1033 }
1034 }
1035 elsif ( $i->{cause} == 8 ) {
1036 &DEBUG( 0, &sid2hex($sid), " [100] deactivation" );
1037  
1038 # <{TODO}>
1039 }
1040 elsif ( $i->{cause} == 7 ) {
1041 &DEBUG( 2, &sid2hex($sid), " [100] accept of activation" );
1042  
1043 $s->{t1_timer}->remove;
1044  
1045 # Start timer Common Interogation
1046 $s->{ci_timer}->remove;
1047 $s->{ci_timer}->add( $s->{ci_timeout} );
1048  
1049 # <{TODO}>
1050 }
1051 elsif ( $i->{cause} == 9 ) {
1052 &DEBUG( 2, "[100] accept of deactivation" );
1053  
1054 # <{TODO}>
1055 }
1056 elsif ( $i->{cause} == 10 ) {
1057 &DEBUG( 2, &sid2hex($sid), " [100] close activation" );
1058  
1059 # <{TODO}>
1060 }
1061 else {
1062 &DEBUG( 2, "[100] unknown cause: ", $i->{cause} );
1063 }
1064 }
1065  
1066 sub parse_asdu_type_103 {
1067 my $self = shift;
1068 my $sid = shift;
1069 my $s = \%{ $self->{sids}{$sid} };
1070 my $i = \%{ $s->{i} };
1071 if ( $i->{cause} == 6 ) {
1072 &DEBUG( 2, "[103] activation" );
1073  
1074 # send accept and current time
1075 $s->{ca} = $i->{ca};
1076 my $data = pack( "C2S3C",
1077 103, 1, 7, $i->{ca},
1078 $i->{obj}{1}{ioa},
1079 $i->{obj}{1}{ioa2} )
1080 . &time_2_cp56_2a(gettimeofday);
1081 $self->frame_i_send( $sid, $data );
1082 }
1083 elsif ( $i->{cause} == 3 ) {
1084 &DEBUG( 2, "[103] sporadic" );
1085  
1086 # Start timer of Sync
1087 $s->{sync_timer}->remove;
1088 $s->{sync_timer}->add( $s->{sync_timeout} );
1089 }
1090 elsif ( $i->{cause} == 7 ) {
1091 &DEBUG( 2, "[103] accept of activation" );
1092 my ( $tm, $ms ) = &cp56_2a_2_time( $i->{obj}{1}{data} );
1093 my $time_diff = tv_interval( [ $tm, $ms ] );
1094 &DEBUG( 1, "CA: ", $i->{ca}, "; KP unix time: ",
1095 $tm, ", Diff: ", $time_diff );
1096 $s->{time_diff} = $time_diff;
1097  
1098 # Start timer of Sync
1099 $s->{sync_timer}->remove;
1100 $s->{sync_timer}->add( $s->{sync_timeout} );
1101 }
1102 else {
1103 &DEBUG( 2, "[103] unknown cause: ", $i->{cause} );
1104 }
1105 }
1106  
1107 sub parse_asdu_type_0_44 {
1108 my ( $addr, $value, $tm, $ms );
1109 my $self = shift;
1110 my $sid = shift;
1111  
1112 my $s = \%{ $self->{sids}{$sid} };
1113 my $i = \%{ $s->{i} };
1114 my $type = $asdu_type{ $i->{id} }{type};
1115  
1116 my %result = ( $type => {} );
1117 for my $j ( 1 .. $i->{nobj} ) {
1118 if ( $i->{id} == 30 ) {
1119 $value = unpack( "C", $i->{obj}{$j}{data} );
1120 $value &= 1;
1121 ( $tm, $ms ) =
1122 cp56_2a_2_time( substr( $i->{obj}{$j}{data}, 1, 7 ) );
1123 }
1124 elsif ( $i->{id} == 35 ) {
1125 $value = unpack( "s", $i->{obj}{$j}{data} );
1126 ( $tm, $ms ) =
1127 cp56_2a_2_time( substr( $i->{obj}{$j}{data}, 3, 7 ) );
1128 }
1129 elsif ( $i->{id} == 36 ) {
1130 $value = unpack( "f", $i->{obj}{$j}{data} );
1131 ( $tm, $ms ) =
1132 cp56_2a_2_time( substr( $i->{obj}{$j}{data}, 5, 7 ) );
1133 }
1134 elsif ( $i->{id} == 37 ) {
1135 $value = unpack( "L", $i->{obj}{$j}{data} );
1136 ( $tm, $ms ) =
1137 cp56_2a_2_time( substr( $i->{obj}{$j}{data}, 5, 7 ) );
1138 }
1139 $tm += int( $s->{time_diff} );
1140 $ms += int( ( $s->{time_diff} - int( $s->{time_diff} ) ) * 1000000 );
1141 if ( $ms > 1000000 ) {
1142 $ms -= 1000000;
1143 $tm++;
1144 }
1145 elsif ( $ms < 0 ) {
1146 $ms += 1000000;
1147 $tm--;
1148 }
1149 $addr = $i->{obj}{$j}{ioa} + 65536 * $i->{obj}{$j}{ioa2};
1150  
1151 $result{$type}->{$addr} = [ $value, $tm, $ms ];
1152 &DEBUG( 8, "ioa: ", $addr, ", val: ", $value, " time: ",
1153 scalar localtime($tm), ";" );
1154 }
1155 &{ $s->{rcb} }( $self, %result );
1156 }
1157  
1158 sub send_asdu_type_0_44 {
1159 my ( $data, $cnt );
1160 my $self = shift;
1161 my $sid = shift;
1162 my $cause = shift;
1163 my $id = shift;
1164 my $d = shift;
1165 my $ca = $self->{sids}{$sid}{ca};
1166  
1167 &DEBUG( 3, "send_asdu_type_0_44(): send ", scalar( keys %{$d} ),
1168 " row(s)" );
1169 foreach my $key ( keys %{$d} ) {
1170 $cnt++;
1171 if ( $id == 30 ) {
1172 $data .= pack( "SC2",
1173 ( $key % 65536 ),
1174 int( $key / 65536 ),
1175 $d->{$key}->[0] & 1 )
1176 . &time_2_cp56_2a( $d->{$key}->[1], $d->{$key}->[2] );
1177 }
1178 elsif ( $id == 35 ) {
1179 $data .= pack( "SCSC",
1180 ( $key % 65536 ),
1181 int( $key / 65536 ),
1182 $d->{$key}->[0], 0 )
1183 . &time_2_cp56_2a( $d->{$key}->[1], $d->{$key}->[2] );
1184 }
1185 elsif ( $id == 36 ) {
1186 $data .= pack( "SCfC",
1187 ( $key % 65536 ),
1188 int( $key / 65536 ),
1189 $d->{$key}->[0], 0 )
1190 . &time_2_cp56_2a( $d->{$key}->[1], $d->{$key}->[2] );
1191 }
1192 elsif ( $id == 37 ) {
1193 $data .= pack( "SCLC",
1194 ( $key % 65536 ),
1195 int( $key / 65536 ),
1196 $d->{$key}->[0], 0 )
1197 . &time_2_cp56_2a( $d->{$key}->[1], $d->{$key}->[2] );
1198 }
1199 &DEBUG(
1200 5, "$cnt|--> IOA:",
1201 $key, ", VALUE:",
1202 $d->{$key}->[0], ", TIME:",
1203 $d->{$key}->[1], " size of pack: ",
1204 length($data)
1205 );
1206 if ( length($data) >= $MAX_ASDU_SIZE - 6 - 3 - $asdu_type{$id}{size} ) {
1207 $self->frame_i_send( $sid,
1208 pack( "C2S2", $id, $cnt, $cause, $ca ) . $data );
1209 $cnt = 0;
1210 $data = "";
1211 }
1212 }
1213 if ($data) {
1214 $self->frame_i_send( $sid,
1215 pack( "C2S2", $id, $cnt, $cause, $ca ) . $data );
1216 }
1217 }
1218  
1219 1;
1220  
1221 __END__
↑ Summary