﻿#ver 0.04 (C)Cyr
use strict;
use warnings;
use diagnostics;
use IO::Socket;
use Convert::ASN1;
#use Data::Dumper;
use Carp;
use POSIX;
#------------------настройки-----------------------------------------------------------------
my $host = '192.168.0.101';                  # IP АТС
my $ICDnumber='601';                         # ICD номер, на который поступают внешние звонки
my $defaultNumber = 191;                     # номер оператора. если 0, то разрыв соединения  
my @devices = (111,112,123,124);    	     # внутренние номера отслеживания
my $datafilename = 'callout.data' ;          # файл данных, нужно создать вручную
my $asnfilename  = 'kxtde.asn'    ;          # файл грамматики http://thinclient.narod.ru/files/kxtde.asn
#--------------------------------------------------------------------------------------------
my $CSTAapdu;
my $socket;
my %calls; # хеш для данных
sub decode_msg_header {
	my $bin = shift;
	my $len = unpack('n', $bin);
	return $len;
}
sub encode_msg_header {
	my $len = shift;
	die "Message larger than allowed!" unless ($len <= 240);
	my $bin = pack('n', $len);
	return $bin;
}
sub convert_to_hex {
	my $pdu = $_[0];
	my $hexdata = unpack('H*', $pdu);
	$hexdata =~ tr/a-z/A-Z/;
	$hexdata =~ s/(..)/$1 /g;
	$hexdata =~ s/ $//g;
	return $hexdata;
}
sub send_pdu {
	my $pdu = $_[0];
	my $header = encode_msg_header(length($pdu));
	$socket->write($header); 
	$socket->write($pdu);
#	my $hexdata = convert_to_hex($pdu);
#	print("SENT:    [$hexdata]\n"); 
} 
sub csta_connect {
	my %args = %{$_[0]}; 
	open_csta_socket($args{host}, $args{port});
	# A-ASSOCIATE Request
	my $pdu = "602380020780A10706052B0C00815ABE14281206072B0C00821D8148A007A0050303000800";
	$pdu = pack('H*', $pdu);
	send_pdu($pdu);
	# A-ASSOCIATE Result 
	$pdu = receive_stuff();
	my $hexdata = convert_to_hex($pdu);
	if ($hexdata =~/A2 03 02 01 01/){
		print "rejected-permanent\n";
		exit 0
	}
	#SystemStatus Request
	$pdu = receive_stuff();
	my $out = $CSTAapdu->decode($pdu);
	my $invokeID  = $out->{svcRequest}{invokeID};
	SystemStatusResult($invokeID);
}
sub open_csta_socket {
	my $host = shift;
	my $port = shift;
	$socket = new IO::Socket::INET(
        PeerAddr => $host,
        PeerPort => $port,
		Timeout  => 20,
		Blocking => 1,
		Proto => 'tcp') || die "Error creating socket: $!\n";
	$socket->autoflush(1);
	print("opened a connection to $host on port $port\n");
}	
sub receive_stuff {
	my $header = '';
	my $pdu = '';
	my $nbytes = $socket->sysread($header, 2);
	if ($nbytes==1) { # фрагмент пакета
		my $header2;
		my $nbytes2= $socket->sysread($header2, 1);
		$header = $header.$header2;
		$nbytes = 2;
	} 
	croak "Didn't receive the specified amount of data (2 bytes)!\n".chr(7) unless ($nbytes == 2);
	my $len = decode_msg_header($header);
	$nbytes = $socket->sysread($pdu, $len);
	if ($nbytes<$len) { # фрагмент пакета
		my $pdu2;
		my $nbytes2= $socket->sysread($pdu2, $len-$nbytes);
		$pdu = $pdu.$pdu2;
		$nbytes = $nbytes + $nbytes2;
	} 
	croak "Didn't receive the specified amount of data ($len bytes)!\n".chr(7) unless ($nbytes == $len);
#	my $hexdata = convert_to_hex($pdu);
#	print("RECEIVED:[$hexdata]\n");
	return $pdu;
}
sub SystemStatusResult{
	my $invokeID = shift;
	my $pdu = $CSTAapdu->encode({svcResult=>{invokeID=>$invokeID,result=>{serviceID=>211,serviceResult=>{noData=>1}}}});
	send_pdu($pdu); # send SystemStatus Result
}
sub	AnswerCall{
	my $connectionID = shift;
	#берём трубку
	if (defined $connectionID) {
		my $pdu = $CSTAapdu->encode({svcRequest=>{
									invokeID=>10,
									serviceID=>2,
									serviceArgs=>{
										callToBeAnswered=>$connectionID
												}
											}
								});	
		send_pdu($pdu);
	}
}
sub	ClearConnection{
	my $connectionID = shift;
	#бросаем трубку
	if (defined $connectionID) {
		my $pdu = $CSTAapdu->encode({svcRequest=>{
									invokeID=>10,
									serviceID=>5,
									serviceArgs=>{
										connectionToBeCleared=>$connectionID
												}
											}
								});	
		send_pdu($pdu);
	}
}
sub DeflectCall{
	my $connectionID = shift;
	my $ext = shift;
	my $pdu = $CSTAapdu->encode({svcRequest=>{
									invokeID=>11,
									serviceID=>218,
									serviceArgs=>{
										callToBeDiverted=>$connectionID,
										newDestination =>{
													deviceIdentifier=>{
															dialingNumber=>$ext
												                      }
														 }										
												 }
											 }
								});	
	send_pdu($pdu);	
}
sub MonitorStart{
	my $Number = shift;
	my $pdu = $CSTAapdu->encode({svcRequest=>{
                                invokeID=>9,
								serviceID=>71,
                                serviceArgs=>{
										monitorObject=>{
											deviceObject=>{
												deviceIdentifier=>{
													dialingNumber=>$Number
																}
															}
														},
										requestedMonitorFilter=>{}
											}
										}
                        });
	send_pdu($pdu);
}
sub readdata{
    open DATA, $datafilename || die "Can't open file for read: $!";
    while (my $line = <DATA>) { # читаем в хещ
        chomp $line;
        my @line = split (/ /, $line);
        $calls{$line[0]} = $line[1];
    }
    close DATA || die "Can't close file: $!";
}
sub writedata{
    my $Called=shift;
    my $Calling=shift;
    if (defined $calls{$Called}) { # проверяем наличие вызваемого номера в данных
        if ($calls{$Called} != $Calling) { # сравниваем ext
            $calls{$Called} = $Calling;	
		} else {return;} #всё уже есть - ничего не делаем
    } else { # номера нет - добавляем в хеш
        $calls{$Called} = $Calling;
    }
    open DATA,">$datafilename" || die "Can't open file for write: $!";
    foreach my $k (keys %calls) { # пишем хеш в файл
        print DATA "$k $calls{$k}\n";
    }
    close DATA || die "Can't close file: $!";
}		
# parse ASN.1 desciptions
my $asn = Convert::ASN1->new;
$asn->prepare_file($asnfilename) or die "prepare: ", $asn->error;
my %serviceArgs = ( 2 => 'AnswerCallArgument',
					5 => 'ClearConnectionArgument',
					21=> 'CSTAEventReportArgument',
					51=> 'EscapeArgument',
					71=> 'MonitorStartArgument',
					211=> 'SystemStatusArg',
					218=> 'DeflectCallArgument');
foreach (keys %serviceArgs) {
	$asn->registertype('serviceArgs',$_,$asn->find($serviceArgs{$_}));
}
my %serviceResults = (  51=> 'EscapeResult',
						71=> 'MonitorStartResult',
						211=> 'SystemStatusRes');
 foreach (keys %serviceResults) {
	$asn->registertype('serviceResult',$_,$asn->find($serviceResults{$_}));
} 
$CSTAapdu = $asn->find('CSTAapdu');
csta_connect({'host'=>$host, 'port'=>33333});
#EscapeArgument.privateData.private.kmeSystemData.setSystemData
my $pdu = $CSTAapdu->encode({svcRequest=>{
                                invokeID=>9,
								serviceID=>51,
                                serviceArgs=>{
									privateData=>{
										private =>{
											kmeSystemData=>{
												setSystemData=>{
													acdQueue =>{
														device =>{
															deviceIdentifier=>{
																dialingNumber=>$ICDnumber
																			  }
																  },
															attribute=>{
																acdMode =>1
																		}
																}
																}
															}
													}		
												  }
											 }
										  }
                            });
send_pdu($pdu);
#EscapeArgument.privateData.private.kmeSystemData.setSystemData
$pdu = $CSTAapdu->encode({svcRequest=>{
                                invokeID=>9,
								serviceID=>51,
                                serviceArgs=>{
									privateData=>{
										private =>{
											kmeSystemData=>{
												setSystemData=>{
													acdQueue =>{
														device =>{
															deviceIdentifier=>{
																dialingNumber=>$ICDnumber
																			  }
																  },
															attribute=>{
																ctiWaitTime =>20
																		}
																}
																}
															}
													}		
												  }
											 }
										  }
                        });
send_pdu($pdu);
MonitorStart($ICDnumber);
foreach my $number (@devices) {
   MonitorStart($number);
}
readdata();
while (1) {
	$pdu = receive_stuff();
	#Convert::ASN1::asn_dump($pdu);
	my $out = $CSTAapdu->decode($pdu);
	# $Data::Dumper::Indent=1;
	# $Data::Dumper::Pair=' ';
	# $Data::Dumper::Quotekeys=0;
	# $Data::Dumper::Varname='CSTAapdu';
	#print Dumper($out);
	if  (defined  $out->{svcRequest})   {
			my $serviceID = $out->{svcRequest}{serviceID};
			my $invokeID  = $out->{svcRequest}{invokeID};
			my $serviceArgs=$out->{svcRequest}{serviceArgs};
			if ($serviceID==21) {
				if (defined $serviceArgs->{eventSpecificInfo}{callControlEvents}{delivered}) {
					my $connectionID = $serviceArgs->{eventSpecificInfo}{callControlEvents}{delivered}{connection};
					my $callingDevice;
					my $calledDevice;
					my $associatedCalledDevice="  ";
					$callingDevice = $serviceArgs->{eventSpecificInfo}{callControlEvents}{delivered}{callingDevice}{deviceIdentifier}{deviceIdentifier}{dialingNumber};
					$calledDevice = $serviceArgs->{eventSpecificInfo}{callControlEvents}{delivered}{calledDevice}{deviceIdentifier}{deviceIdentifier}{dialingNumber};
					if (defined $serviceArgs->{eventSpecificInfo}{callControlEvents}{delivered}{associatedCalledDevice}{deviceIdentifier}{deviceIdentifier}{deviceNumber}) {
						$associatedCalledDevice = $serviceArgs->{eventSpecificInfo}{callControlEvents}{delivered}{associatedCalledDevice}{deviceIdentifier}{deviceIdentifier}{deviceNumber} & 0x0000FFFF;
					}	
					my $localConnectionInfo = $serviceArgs->{eventSpecificInfo}{callControlEvents}{delivered}{localConnectionInfo};
					my $cause = $serviceArgs->{eventSpecificInfo}{callControlEvents}{delivered}{cause};
					print "delivered\n";
					print $callingDevice," ", $calledDevice, " ", $associatedCalledDevice," ", $localConnectionInfo," ", $cause,"\n";
					if (($localConnectionInfo==3) & ($cause==46)) {#connected
						#запись в файл 
						print "writedata\n";
						writedata($calledDevice,$callingDevice);
					} elsif (($calledDevice == $ICDnumber) & ($localConnectionInfo==2) & ($cause==42)) {#allerting 
						#ответить на звонок
						print "answer\n";
						AnswerCall($connectionID);
					}
				} elsif ($serviceArgs->{eventSpecificInfo}{callControlEvents}{queued}) {			
					my $connectionID = $serviceArgs->{eventSpecificInfo}{callControlEvents}{queued}{queuedConnection};
					if ($serviceArgs->{eventSpecificInfo}{callControlEvents}{queued}{queue}{deviceIdentifier}{deviceIdentifier}{dialingNumber} == $ICDnumber) {
						my $callingDevice = $serviceArgs->{eventSpecificInfo}{callControlEvents}{queued}{callingDevice}{deviceIdentifier}{deviceIdentifier}{dialingNumber};
						print "queued\n";
						print $callingDevice,"-";
						#найти ext по $callingDevice
						if (defined $calls{$callingDevice}) { #найден, соединение
							print "DeflectCall\n";
							my $ext=int $calls{$callingDevice};
							print $ext, "\n";
							DeflectCall($connectionID, $ext);
						} elsif ($defaultNumber) { #соединение по дефолтному номеру
								print "DeflectCall to defaultNumber\n";
								DeflectCall($connectionID, $defaultNumber);	
						} else { #бросить трубку
								print "ClearConnection\n";
								ClearConnection($connectionID);
						}
					}
				} 
			} elsif ($serviceID==211) { # if SystemStatus Request
				SystemStatusResult($invokeID);
			}
	}
}