#package Gateway::Dinstar;
package Dinstar;

use 5.032001;
use strict;
use warnings;
use POSIX;
use JSON;
use WWW::Curl::Easy;
use URI::Encode qw(uri_encode uri_decode);
use Switch;
use Data::Dumper;
use MIME::Base64;

use Exporter;
our @ISA = qw(Exporter);
our @EXPORT = qw(receiveSms sendSms querySmsResult gw_QueryPortInfo queryPortInfo getSlot convertSlot getSlotName changeToSlot enableSlot disableSlot calculateIMEI changeIMEI getPortInfo loginGateway dinstar_QueryDeliveryStatus dinstar_SendSms synway_GetIMEI querySmsResults gw_LoginGateway gw_QuerySmsResults gw_ChangeIMEI synway_EnableSlot gw_EnableSlot gw_SendSms gw_ReceiveSms );
our $VERSION = '0.01';
our $ABSTRACT = 'lib/Dinstar.pm';

use constant {
    DINSTAR => 0,
    SYNWAY => 2
};

# -------------
# sendSms
# -------------
sub sendSms {
	my $ip = $_[0];
	my $number = $_[1];
	my $text = $_[2];
	my $port = $_[3];
	my $auth = $_[4];
	my $id = $_[5];
	my $tipo_gw = $_[6];
	my $coding = $_[7];

	switch( $tipo_gw ) {
		case DINSTAR {
			return( dinstar_SendSms( $ip, $number, $text, $port, $auth, $id, $coding ) );
		}
		case SYNWAY {
			return( synway_SendSms( $ip, $number, $text, $port, $auth, $id, $coding ) );
		}	
	}		
	return "";
}

# -------------
# sendSms
# -------------
sub gw_SendSms {
	my $ip = $_[0];
	my $number = $_[1];
	my $text = $_[2];
	my $port = $_[3];
	my $auth = $_[4];
	my $id = $_[5];
	my $tipo_gw = $_[6];
	my $coding = $_[7];

	switch( $tipo_gw ) {
		case DINSTAR {
			return( dinstar_SendSms( $ip, $number, $text, $port, $auth, $id, $coding ) );
		}
		case SYNWAY {
			return( synway_SendSms( $ip, $number, $text, $port, $auth, $id, $coding ) );
		}	
	}		
	return "";
}


# -------------
# receiveSms
# -------------
sub receiveSms {
   my $ip = $_[0];
   my @ports = $_[1];
   my $flag = $_[2];
	my $auth = $_[3];
	my $tipo_gw = $_[4];

	switch( $tipo_gw ) {
 		case DINSTAR {
			return( dinstar_ReceiveSms( $ip, \@ports, $auth, $flag ) );
		}
		case SYNWAY {
			return( synway_ReceiveSms( $ip, \@ports, $auth, $flag ) );
		}	
	}		
	return "";
}

# -------------
# receiveSms
# -------------
sub gw_ReceiveSms {
   my $ip = $_[0];
   my @ports = $_[1];
   my $flag = $_[2];
	my $auth = $_[3];
	my $tipo_gw = $_[4];

	switch( $tipo_gw ) {
 		case DINSTAR {
			return( dinstar_ReceiveSms( $ip, \@ports, $auth, $flag ) );
		}
		case SYNWAY {
			return( synway_ReceiveSms( $ip, \@ports, $auth, $flag ) );
		}	
	}		
	return "";
}

# ------------------
# gw_QueryPortInfo
# ------------------

sub gw_QueryPortInfo {
	my $ip = $_[0];
   my $port = $_[1];
	my $auth = $_[2];
	my $content = "";
	my $tipo_gw = $_[3];
	my $sn = $_[4];

	switch( $tipo_gw ) {
 		case DINSTAR {
			return( queryPortInfo( $ip, $port, $auth ) );
		}
		case SYNWAY {
			return( synway_QueryPortInfo( $ip, $port, $auth, $sn ) ); 
		}	
	}		
	return "";
}

# -----------------
# gw_LoginGateway
# -----------------
sub gw_LoginGateway {
	my $ip = $_[0];
	my $name = $_[1];
	my $password = $_[2];
	my $tipo_gw = $_[3];

	switch( $tipo_gw ) {
 		case DINSTAR {
			return( loginGateway( $ip, $name, $password ) );
		}
		case SYNWAY {
			return "N/D";
		}	
	}		
	return "";
}	


# --------------------
# gw_QuerySmsResults
# --------------------
sub gw_QuerySmsResults {
	my $ip = $_[0];
	my @port = $_[1];
	my $auth = $_[2];
	my $id = $_[3];
	my $fecha= $_[4];
	my $recipient = $_[5];
	my $canales = $_[6];
	my $tipo_gw = $_[7];

	switch( $tipo_gw ) {

 		case DINSTAR {
			return( querySmsResults( $ip, \@port, $auth, $id, $fecha, $recipient ) );
		}
		case SYNWAY {
			return( synway_QuerySmsResults( $ip, $auth, $fecha, $canales ) );
		}	
	}		
	return "";
}	


# --------------------
# gw_ChangeIMEI
# --------------------
sub gw_ChangeIMEI {
	my $ip = $_[0];
	my $port = $_[1];
	my $auth = $_[2];
	my $imei = $_[3];
	my $tipo_gw = $_[4];

	switch( $tipo_gw ) {
 		case DINSTAR {
			return( changeIMEI( $ip, $port, $auth, $imei ) );
		}
		case SYNWAY {
			return( synway_ChangeIMEI( $ip, $port, $auth, $imei ) );
		}	
	}		
	return "";
}


# --------------------
# gw_EnableSlot
# --------------------
sub gw_EnableSlot {
	my $ip = $_[0];
	my $port = $_[1];
	my $slot = $_[2];
	my $auth = $_[3];
	my $jsessionid = $_[4];
	my $slot_num = "";
	my $sn = $_[5];
	my $tipo_gw = $_[6];

	switch( $tipo_gw ) {
 		case DINSTAR {
         return( enableSlot( $ip, $port, $slot, $auth, $jsessionid, $sn ) );
		}
		case SYNWAY {
			return( synway_EnableSlot( $ip, $port, $slot, $auth,  $jsessionid, $sn ) );
		}	
	}		
	return "";
}


# --------------------------------------------
# DINSTAR INTERFACE
# --------------------------------------------

# ---------------------
# dinstar_ReceiveSms
# ---------------------
sub dinstar_SendSms {

	my $ip = $_[0];
	my $number = $_[1];
	my $text = $_[2];
	my $port = $_[3];
	my $auth = $_[4];
	my $id = $_[5];
	my $coding = $_[6];
	my $encoding = "gsm-7bit";

	if( $coding == 0 ) {
		$encoding = "gsm-7bit"; 
	}		
	else {
		$encoding = "unicode";
	}

   my $coded = uri_decode($text);
	my $url = sprintf( "%s/api/send_sms", $ip ); 
	my $postfields = { port => [int($port)],
							 text => $coded,
 							 encoding => $encoding,
				          request_status_report => 1,
				          param => [{number=>$number,user_id=>int($id)}]
						  };

#	my $field = sprintf( '{"param":[{"number":"%s","user_id":%d}],"text":"Tu clave es 98845","port":["23"],"request_status_report":1}', $number, int($user_id) ;
#'{"text":"ye","param":[{"number":"10086"}]}' -H "Content-Type:application/json" https://gateway_ip/api/send_sms
#{"param":[{"number":"541149483227","user_id":1228}],"text":"Tu clave es 98845","port":["23"],"request_status_report":1}

   my $jsonEncoded = encode_json( $postfields );
# 	printf( "%s\n", $jsonEncoded );
   my $curl = WWW::Curl::Easy->new;
   $curl->setopt( CURLOPT_HEADER,0);
   $curl->setopt( CURLOPT_URL, $url);
   $curl->setopt( CURLOPT_MAXREDIRS, 10 );                                                
   $curl->setopt( CURLOPT_POSTFIELDS, $jsonEncoded );
   $curl->setopt( CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
   $curl->setopt( CURLOPT_HTTPAUTH, CURLAUTH_ANY ) ;
   $curl->setopt( CURLOPT_USERPWD, $auth );
   $curl->setopt( CURLOPT_POST, 1);
   $curl->setopt( CURLOPT_TIMEOUT, 0);
   $curl->setopt( CURLOPT_FOLLOWLOCATION, 1);
   $curl->setopt( CURLOPT_USERPWD, $auth);
   
   my $response_body;
   $curl->setopt(CURLOPT_WRITEDATA,\$response_body);
   my $retcode = $curl->perform;
   my $error_text = "";
	
   if ($retcode == 0) {
	   my $response_code = $curl->getinfo(CURLINFO_HTTP_CODE);
     	if( $response_code == 200 ) {
        	my $resultSend = decode_json($response_body);
			return $resultSend;
     	}
   }
	return "";
}


# ----------------------------------
# querySmsResult
# ----------------------------------

sub querySmsResult {
	my $ip = $_[0];
	my $port = $_[1];
	my $auth = $_[2];
	my $id = $_[3];
	my $fecha= $_[4];
	my $recipient = $_[5];

	my $url = sprintf( "%s/api/query_sms_result", $ip ); 
	my $postfields = { 
					       number => [$recipient],
							 port => [int($port)],
							 user_id => [int($id)],
							 time_after => $fecha
						  };

   my $jsonEncoded = encode_json( $postfields );
#	printf( "%s\n", $jsonEncoded );
   my $curl = WWW::Curl::Easy->new;
   $curl->setopt( CURLOPT_HEADER,0);
   $curl->setopt( CURLOPT_URL, $url);
   $curl->setopt( CURLOPT_MAXREDIRS, 10 );                                                
   $curl->setopt( CURLOPT_POSTFIELDS, $jsonEncoded );
   $curl->setopt( CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
   $curl->setopt( CURLOPT_HTTPAUTH, CURLAUTH_ANY ) ;
   $curl->setopt( CURLOPT_USERPWD, $auth );
   $curl->setopt( CURLOPT_POST, 1);
   $curl->setopt( CURLOPT_TIMEOUT, 0);
   $curl->setopt( CURLOPT_FOLLOWLOCATION, 1);
   $curl->setopt( CURLOPT_USERPWD, $auth);
   
   my $response_body;
   $curl->setopt(CURLOPT_WRITEDATA,\$response_body);
   my $retcode = $curl->perform;
   my $error_text = "";
	
   if ($retcode == 0) {
	   my $response_code = $curl->getinfo(CURLINFO_HTTP_CODE);
     	if( $response_code == 200 ) {
#        	my $resultSend = decode_json($response_body);
#			return $resultSend;
			return $response_body;
     	}
   }
	return "";
}

# ----------------------------------
# querySmsResults
# ----------------------------------

sub querySmsResults {
	my $ip = $_[0];
	my @port = $_[1];
	my $auth = $_[2];
	my $id = $_[3];
	my $fecha= $_[4];
	my $recipient = $_[5];

	my $url = sprintf( "%s/api/query_sms_result", $ip ); 
	my $postfields = { 
							 port => \@port,
							 time_after => $fecha
						  };

   my $jsonEncoded = encode_json( $postfields );
   my $curl = WWW::Curl::Easy->new;
   $curl->setopt( CURLOPT_HEADER,0);
   $curl->setopt( CURLOPT_URL, $url);
   $curl->setopt( CURLOPT_MAXREDIRS, 10 );                                                
   $curl->setopt( CURLOPT_POSTFIELDS, $jsonEncoded );
   $curl->setopt( CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
   $curl->setopt( CURLOPT_HTTPAUTH, CURLAUTH_ANY ) ;
   $curl->setopt( CURLOPT_USERPWD, $auth );
   $curl->setopt( CURLOPT_POST, 1);
   $curl->setopt( CURLOPT_TIMEOUT, 0);
   $curl->setopt( CURLOPT_FOLLOWLOCATION, 1);
   $curl->setopt( CURLOPT_USERPWD, $auth);
   
   my $response_body;
   $curl->setopt(CURLOPT_WRITEDATA,\$response_body);
   my $retcode = $curl->perform;
   my $error_text = "";
	
   if ($retcode == 0) {
	   my $response_code = $curl->getinfo(CURLINFO_HTTP_CODE);
     	if( $response_code == 200 ) {
#        	my $resultSend = decode_json($response_body);
#			return $resultSend;
			return $response_body;
     	}
   }
	return "";
}

# ----------------------------------
# dinstar_QueryDeliveryStatus
# ----------------------------------

sub dinstar_QueryDeliveryStatus {
	my $ip = $_[0];
	my $port = $_[1];
	my $auth = $_[2];
	my $id = $_[3];
	my $fecha= $_[4];
	my $recipient = $_[5];

	my $url = sprintf( "%s/api/query_sms_deliver_status", $ip ); 
	my $postfields = { 
					       number => [$recipient],
							 port => [int($port)],
							 user_id => [int($id)],
							 time_after => $fecha
						  };

   my $jsonEncoded = encode_json( $postfields );
   my $curl = WWW::Curl::Easy->new;
   $curl->setopt( CURLOPT_HEADER,0);
   $curl->setopt( CURLOPT_URL, $url);
   $curl->setopt( CURLOPT_MAXREDIRS, 10 );                                                
   $curl->setopt( CURLOPT_POSTFIELDS, $jsonEncoded );
   $curl->setopt( CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
   $curl->setopt( CURLOPT_HTTPAUTH, CURLAUTH_ANY ) ;
   $curl->setopt( CURLOPT_USERPWD, $auth );
   $curl->setopt( CURLOPT_POST, 1);
   $curl->setopt( CURLOPT_TIMEOUT, 0);
   $curl->setopt( CURLOPT_FOLLOWLOCATION, 1);
   $curl->setopt( CURLOPT_USERPWD, $auth);
   
   my $response_body;
   $curl->setopt(CURLOPT_WRITEDATA,\$response_body);
   my $retcode = $curl->perform;
   my $error_text = "";
	
   if ($retcode == 0) {
	   my $response_code = $curl->getinfo(CURLINFO_HTTP_CODE);
     	if( $response_code == 200 ) {
			return $response_body;
     	}
   }
	return "";
}

# --------------------
# receiveSms
# --------------------
sub dinstar_ReceiveSms {

   my $ip = $_[0];
   my @port = @{$_[1]};
   my $flag = $_[2];
   my $auth = $_[3];

#	print( Dumper( @port ) );
   my $url = sprintf( "%s/api/query_incoming_sms", $ip ); 
   my $postfields = { port => @port,
                      flag => $flag };
   my $jsonEncoded = encode_json( $postfields );

   my $curl = WWW::Curl::Easy->new;
   $curl->setopt( CURLOPT_HEADER,0);
   $curl->setopt( CURLOPT_URL, $url);
   $curl->setopt( CURLOPT_MAXREDIRS, 10 );                                                
   $curl->setopt( CURLOPT_POSTFIELDS, $jsonEncoded );
   $curl->setopt( CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
   $curl->setopt( CURLOPT_HTTPAUTH, CURLAUTH_ANY ) ;
   $curl->setopt( CURLOPT_USERPWD, $auth );
   $curl->setopt( CURLOPT_POST, 1);
   $curl->setopt( CURLOPT_TIMEOUT, 0);
   $curl->setopt( CURLOPT_FOLLOWLOCATION, 1);
   $curl->setopt( CURLOPT_USERPWD, $auth);
   
   my $response_body;
   $curl->setopt(CURLOPT_WRITEDATA,\$response_body);
   my $retcode = $curl->perform;
   my $error_text = "";

   if ($retcode == 0) {
		my $response_code = $curl->getinfo(CURLINFO_HTTP_CODE);
     	if( $response_code == 200 ) {
        	my $resultSend = decode_json($response_body);
			return $resultSend;
     	}
   }
   return "";
}


# ------------------
# queryPortStatus
# ------------------

sub queryPortInfo {
   my $ip = $_[0];
   my $port = $_[1];
   my $auth_basic = $_[2];
	my $content = "";

   my $url = sprintf( "%s/api/get_port_info", $ip ); 
   if( $port == -1 ) {
	   $content = "info_type=type,imei,imsi,iccid,number,reg,slot,callstate,signal";
	}
   else {
		$content = "port=$port&info_type=type,imei,imsi,iccid,number,reg,slot,callstate,signal"; 
	}		

   my $curl = WWW::Curl::Easy->new;
   $curl->setopt( CURLOPT_HEADER,0);
   $curl->setopt( CURLOPT_URL, $url);
   $curl->setopt( CURLOPT_MAXREDIRS, 10 );                                                
   $curl->setopt( CURLOPT_POSTFIELDS, $content );
#   $curl->setopt( CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
   $curl->setopt( CURLOPT_HTTPAUTH, CURLAUTH_ANY ) ;
   $curl->setopt( CURLOPT_USERPWD, $auth_basic );
   $curl->setopt( CURLOPT_POST, 1);
   $curl->setopt( CURLOPT_TIMEOUT, 0);
   $curl->setopt( CURLOPT_FOLLOWLOCATION, 1);
   $curl->setopt( CURLINFO_HEADER_OUT, 1 );

   my $response_body;
   $curl->setopt(CURLOPT_WRITEDATA,\$response_body);
   my $retcode = $curl->perform;
   my $error_text = "";

   if ($retcode == 0) {
		my $response_code = $curl->getinfo(CURLINFO_HTTP_CODE);
     	if( $response_code == 200 ) {
#       	my $resultSend = decode_json($response_body);
#			return $resultSend;
			return $response_body;
     	}
   }
   return "";
}


sub getSlot {
   my $port = $_[0];
   my $val = $_[1];

   my $data = "";
   my $sl = "A";
   switch( int($val) ) {
      case 0  { $sl = "A" }
      case 1  { $sl = "B" }
      case 2  { $sl = "C" }
      case 3  { $sl = "D" }
   }
   $data = sprintf( "%2d%s", intval( $port ), $sl );
   return $data;
}


sub convertSlot {
   my $val = $_[0];
   my $sl = "";

	if( $val ne "" ) {
	   switch( int($val) ) {
   	   case 0  { $sl = "A" }
      	case 1  { $sl = "B" }
	      case 2  { $sl = "C" }
   	   case 3  { $sl = "D" }
	   }
	}
	else {
	 	$sl = "X";
	}
   my $data = sprintf( "%s", $sl );
   return $data;
}

sub getSlotName {
   my $val = $_[0];
	my $sl;

	if( $val ne "" ) {
   	switch( int($val) ) {
      	case 0  { $sl = "A" }
	      case 1  { $sl = "B" }
   	   case 2  { $sl = "C" }
      	case 3  { $sl = "D" }
			else { $sl = "X"; }
   	}
	}
	else {
	 	$sl = "X";
	}
   return $sl;
}

# -----------------------------------
# changeToSlot
# -----------------------------------

sub changeToSlot {
	my $ip = $_[0];
	my $port = $_[1];
	my $slot = $_[2];
	my $auth = $_[3];
	my $slot_num = "";

   switch( $slot ) {
      case ( "A" || "a" )
         { $slot_num = 0 }

      case ( "B" || "b" )
         { $slot_num = 1 }

      case ( "C" || "c" )
         { $slot_num = 2 }

      case ( "D" || "d" )
         { $slot_num = 3 }
   }

   my $url = sprintf( "%s/api/set_port_info", $ip ); 
   my $content = "port=" . $port . "&action=slot" . "&param=" . $slot_num;

   my $curl = WWW::Curl::Easy->new;
   $curl->setopt( CURLOPT_HEADER,0);
   $curl->setopt( CURLOPT_URL, $url);
   $curl->setopt( CURLOPT_MAXREDIRS, 10 );                                                
   $curl->setopt( CURLOPT_POSTFIELDS, $content );
#  $curl->setopt( CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
   $curl->setopt( CURLOPT_HTTPAUTH, CURLAUTH_ANY ) ;
   $curl->setopt( CURLOPT_USERPWD, $auth );
   $curl->setopt( CURLOPT_POST, 1);
   $curl->setopt( CURLOPT_TIMEOUT, 0);
   $curl->setopt( CURLOPT_FOLLOWLOCATION, 1);
   $curl->setopt( CURLINFO_HEADER_OUT, 1 );

   my $response_body;
   $curl->setopt(CURLOPT_WRITEDATA,\$response_body);
   my $retcode = $curl->perform;
   my $error_text = "";

   if ($retcode == 0) {
		my $response_code = $curl->getinfo(CURLINFO_HTTP_CODE);
     	if( $response_code == 200 ) {
        	my $resultSend = decode_json($response_body);
			return "Ok";
     	}
   }
   return "Error";
}


# --------------
# enableSlot
# --------------

sub enableSlot {
	my $ip = $_[0];
	my $port = $_[1];
	my $slot = $_[2];
	my $auth = $_[3];
	my $jsessionid = $_[4];
	my $slot_num = "";
	my $sn = $_[5];

   my $url = "$ip/goform/EiaHBSIM";
   my $content = "SubText=E_" . $port . $slot;
	my $device = sprintf( "devckie=%s", $sn ); 

   my $curl = WWW::Curl::Easy->new;
   $curl->setopt( CURLOPT_HEADER,0);
   $curl->setopt( CURLOPT_URL, $url);
   $curl->setopt( CURLOPT_MAXREDIRS, 10 );                                                
   $curl->setopt( CURLOPT_POSTFIELDS, $content );
#  $curl->setopt( CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
   $curl->setopt( CURLOPT_HTTPAUTH, CURLAUTH_ANY ) ;
   $curl->setopt( CURLOPT_USERPWD, $auth );
   $curl->setopt( CURLOPT_POST, 1);
   $curl->setopt( CURLOPT_TIMEOUT, 0);
   $curl->setopt( CURLOPT_FOLLOWLOCATION, 1);
   $curl->setopt( CURLINFO_HEADER_OUT, 1 );
#  $curl->setopt( CURLOPT_COOKIE, 'devckie=db49-c230-9183-0071');
   $curl->setopt( CURLOPT_COOKIE, $device );
   my $session = sprintf( "JSESSIONID=%s", $jsessionid );
   $curl->setopt( CURLOPT_COOKIE, $session );

   my $response_body;
   $curl->setopt(CURLOPT_WRITEDATA,\$response_body);
   my $retcode = $curl->perform;
   my $error_text = "";

   if ($retcode == 0) {
		my $response_code = $curl->getinfo(CURLINFO_HTTP_CODE);
     	if( $response_code == 200 ) {
			return $response_code;
     	}
   }
   return $retcode;
}

# --------------
# disableSlot
# --------------

sub disableSlot {
	my $ip = $_[0];
	my $port = $_[1];
	my $slot = $_[2];
	my $auth = $_[3];
	my $jsessionid = $_[4];
	my $sn = $_[5];
	my $slot_num = "";

#   my ($package, $filename, $line, $subroutine) = caller(0);
#   print "disableSlot Caller: $filename, linea: $line, en el sub: $subroutine\n";

   my $url = "$ip/goform/EiaHBSIM";
   my $content = "SubText=D_" . $port . $slot;
	my $device = sprintf( "devckie=%s", $sn ); 

   my $curl = WWW::Curl::Easy->new;
   $curl->setopt( CURLOPT_HEADER,0);
   $curl->setopt( CURLOPT_URL, $url);
   $curl->setopt( CURLOPT_MAXREDIRS, 10 );                                                
   $curl->setopt( CURLOPT_POSTFIELDS, $content );
#  $curl->setopt( CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
   $curl->setopt( CURLOPT_HTTPAUTH, CURLAUTH_ANY ) ;
   $curl->setopt( CURLOPT_USERPWD, $auth );
   $curl->setopt( CURLOPT_POST, 1);
   $curl->setopt( CURLOPT_TIMEOUT, 0);
   $curl->setopt( CURLOPT_FOLLOWLOCATION, 1);
   $curl->setopt( CURLINFO_HEADER_OUT, 1 );
   $curl->setopt( CURLOPT_COOKIE, $device );
   my $session = sprintf( "JSESSIONID=%s", $jsessionid );
   $curl->setopt( CURLOPT_COOKIE, $session );

   my $response_body;
   $curl->setopt(CURLOPT_WRITEDATA,\$response_body);
   my $retcode = $curl->perform;
   my $error_text = "";

   if ($retcode == 0) {
		my $response_code = $curl->getinfo(CURLINFO_HTTP_CODE);
     	if( $response_code == 200 ) {
			return $response_code;
     	}
   }
   return 0;
}

# --------------------------------
# calculateIMEI
# --------------------------------

sub calculateIMEI {

	my $imei = $_[0];
	my $sum;
	my $odd;
	my $even;
	my $chk;
   my @change =  (  0, 2, 4, 6, 8, 1, 3, 5, 7, 9 );

# ------------------------------------------------------
#     1. Compute the sum of all digits on odd places.
#     2. Replace the digits on even places by the formula:
#
#        0=>0, 1=>2, 2=>4, 3=>6, 4=>8, 5=>1, 6=>3, 7=>5, 
#        8=>7, 9=>9 and summarize them.
#
#     3. Summarize the two results.
#     4. In case the sum of digits ends in 0, 0 is the 
#        check digit. Otherwise, the checksum is equal to 
#        the number that needs to be added to the result 
#        to get the next highest "round" number.
# ------------------------------------------------------ 

	my @newImei = split (//, $imei); 

   $odd = int( $newImei[0] ) + int( $newImei[2] ) + int( $newImei[4] ) + int( $newImei[6] ) +
    	    int( $newImei[8] ) + int( $newImei[10] ) + int( $newImei[12] );

   $even = $change[int( $newImei[1] )] + $change[int( $newImei[3] )] + $change[int( $newImei[5] )] +
    	     $change[int( $newImei[7] )] + $change[int( $newImei[9] )] + $change[int( $newImei[11] )] + $change[int( $newImei[13] )];

   $sum = int($odd) + int($even);
   $sum = $sum % 10;
   $chk = 10 - $sum;
   my $newData = substr($imei,0,14) . $chk;
   return $newData;
}


# ------------
# changeIMEI
# ------------
sub changeIMEI {
	my $ip = $_[0];
	my $port = $_[1];
	my $auth = $_[2];
	my $imei = $_[3];

   my $url = "$ip/api/set_port_info";
   my $calculated = $imei;
   my $content = "action=imei&param=" . $imei . "&port=" . $port;

#10.0.66.104/api/set_port_info?action=reset&param=350448243301774&port=22&imei=350448243301774

   my $curl = WWW::Curl::Easy->new;
   $curl->setopt( CURLOPT_HEADER,0);
   $curl->setopt( CURLOPT_URL, $url);
   $curl->setopt( CURLOPT_MAXREDIRS, 10 );                                                
   $curl->setopt( CURLOPT_POSTFIELDS, $content );
#  $curl->setopt( CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
   $curl->setopt( CURLOPT_HTTPAUTH, CURLAUTH_ANY ) ;
   $curl->setopt( CURLOPT_USERPWD, $auth );
   $curl->setopt( CURLOPT_POST, 1);
   $curl->setopt( CURLOPT_TIMEOUT, 0);
   $curl->setopt( CURLOPT_FOLLOWLOCATION, 1);
   $curl->setopt( CURLINFO_HEADER_OUT, 1 );

   my $response_body;
   $curl->setopt(CURLOPT_WRITEDATA,\$response_body);
   my $retcode = $curl->perform;
   my $error_text = "";

   if ($retcode == 0) {
		my $response_code = $curl->getinfo(CURLINFO_HTTP_CODE);
     	if( $response_code == 200 ) {
#	     	print "IMEI change succesful\n";
			return $calculated;
     	}
   }
   return "";
}

# ------------
# getPortInfo
# ------------

sub getPortInfo {
	my $ip = $_[0];
	my $port = $_[1];
	my $auth = $_[2];

   my $url = "$ip/api/get_port_info";
   my $content = "port=$port&info_type=type,imei,number,reg,slot,callstate,signal";

   my $curl = WWW::Curl::Easy->new;
   $curl->setopt( CURLOPT_HEADER,0);
   $curl->setopt( CURLOPT_URL, $url);
   $curl->setopt( CURLOPT_MAXREDIRS, 10 );                                                
   $curl->setopt( CURLOPT_POSTFIELDS, $content );
#  $curl->setopt( CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
   $curl->setopt( CURLOPT_HTTPAUTH, CURLAUTH_ANY ) ;
   $curl->setopt( CURLOPT_USERPWD, $auth );
   $curl->setopt( CURLOPT_POST, 1);
   $curl->setopt( CURLOPT_TIMEOUT, 0);
   $curl->setopt( CURLOPT_FOLLOWLOCATION, 1);
   $curl->setopt( CURLINFO_HEADER_OUT, 1 );

   my $response_body;
   $curl->setopt(CURLOPT_WRITEDATA,\$response_body);
   my $retcode = $curl->perform;
   my $error_text = "";

   if ($retcode == 0) {
		my $response_code = $curl->getinfo(CURLINFO_HTTP_CODE);
     	if( $response_code == 200 ) {
		   my $data = json_decode($response_body);
			return $data;
     	}
   }
   return "";
}

   # -----------------------------------
   # loginDinstar
   # -----------------------------------

   sub loginGateway {
		my $ip = $_[0];
		my $name = $_[1];
		my $password = $_[2];
      my $jsessionid = "";
     	my $app_folder = getcwd;

      my $url = "$ip/goform/IADIdentityAuth";
      my $content = "username=$name&password=$password";
		my $cookiefile = $app_folder . "/cookies.txt";

      my $curl = WWW::Curl::Easy->new;
      $curl->setopt( CURLOPT_HEADER,0);
      $curl->setopt( CURLOPT_URL, $url);
      $curl->setopt( CURLOPT_MAXREDIRS, 10 );                                                
      $curl->setopt( CURLOPT_POSTFIELDS, $content );
      $curl->setopt( CURLOPT_HTTPAUTH, CURLAUTH_ANY ) ;
      $curl->setopt( CURLOPT_POST, 1);
      $curl->setopt( CURLOPT_TIMEOUT, 0);
      $curl->setopt( CURLOPT_FOLLOWLOCATION, 1);
      $curl->setopt( CURLINFO_HEADER_OUT, 1 );
      $curl->setopt( CURLOPT_COOKIEJAR, $cookiefile );

      my $response_body;
      $curl->setopt(CURLOPT_WRITEDATA,\$response_body);
      my $retcode = $curl->perform;
      my $error_text = "";

#      /JSESSIONID([^;]+)
      if ($retcode == 0) {
	   	my $response_code = $curl->getinfo(CURLINFO_HTTP_CODE);
     	   if( $response_code == 200 ) {

            my $string;
            my $index;

            open(my $fh, '<', $cookiefile);
            while (my $line = <$fh>) {  # Read one line at a time
                chomp $line;  # Remove trailing newline
                if(  ( $index = index( $line, 'JSESSIONID') ) > 0 ) {
                  $string =  substr($line,$index);
                  $string =~ s/\s+//g;
                  $jsessionid =  substr( $string, 10 );
                  last;
               }
            }
            close $fh;
            return $jsessionid;
        	}
      }
      return "";
   }

# -----------------------------------------------------------------------
# Synway Interface
# -----------------------------------------------------------------------

# -------------
# sendSms
# -------------

sub synway_SendSms {

	my $ip = $_[0];
	my $number = $_[1];
	my $text = $_[2];
	my $port = $_[3];
	my $auth = $_[4];
	my $id = $_[5];
	my $coding = $_[6];
	my $encoding = 0;

	if( $coding == 0 ) {
		$encoding = 0;
	}
	else {
		$encoding = 8;
	}			

   my $coded = uri_decode($text);
	my $url = sprintf( "%s/API/SendSMS", $ip ); 
	my $postfields = { port => int($port),
							 smsinfo => $coded,
							 event => 'txtsms',
							 num => $number,
							 userid => $id,
							 encoding => 0							# 0 7bit   8 UCS-2
						  };

   my $jsonEncoded = encode_json( $postfields );
# 	printf( "%s\n", $jsonEncoded );
   my $curl = WWW::Curl::Easy->new;
   $curl->setopt( CURLOPT_HEADER,0);
   $curl->setopt( CURLOPT_URL, $url);
   $curl->setopt( CURLOPT_MAXREDIRS, 10 );                                                
   $curl->setopt( CURLOPT_POSTFIELDS, $jsonEncoded );
   $curl->setopt( CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
   $curl->setopt( CURLOPT_HTTPAUTH, CURLAUTH_ANY ) ;
   $curl->setopt( CURLOPT_USERPWD, $auth );
   $curl->setopt( CURLOPT_POST, 1);
   $curl->setopt( CURLOPT_TIMEOUT, 0);
   $curl->setopt( CURLOPT_FOLLOWLOCATION, 1);
   $curl->setopt( CURLOPT_USERPWD, $auth);
   
   my $response_body;
   $curl->setopt(CURLOPT_WRITEDATA,\$response_body);
   my $retcode = $curl->perform;
   my $error_text = "";
	
   if ($retcode == 0) {
	   my $response_code = $curl->getinfo(CURLINFO_HTTP_CODE);
     	if( $response_code == 200 ) {
        	my $resultSend = decode_json($response_body);
			my $errCode = $resultSend->{result};
			my $content = $resultSend->{content};
			if( $errCode eq "ok" ) {
				my $index = index ($content, 'taskid:');
				my $taskid = "";
				if( $index >= 0 ) {
	 				$taskid = substr($content, $index + 7); 
				}
				my $result = '{"error_code":202, "sn":"","sms_in_queue":1,"task_id":$taskid}';
	  			return $result;
			}
			else {
				my $result = '{"error_code":500, "sn":"","sms_in_queue":0,"task_id":$content}';
	  			return $result;
			}
=begin
sms encoding format does not support 		SMS encoding format unsupported
txsms fifo is full 								SMS sending queue is full
sms data too long 								SMS content too long
no available port 								No ports available
no phonenumber 									No sending number
no quantity available 							Available SMS on the port used up
=cut

			return $resultSend;
     	}
   }
	return "";
}

# ----------------------------------
# querySmsResult
# ----------------------------------

sub synway_QuerySmsResult {
	return "";
}


# ----------------------------------
# querySmsResults
# ----------------------------------

sub synway_QuerySmsResults {
	my $ip = $_[0];
	my $auth = $_[1];
	my $fecha= $_[2];
	my $canales = $_[3];
   my $json = "";
	my $text = "";
	my $i;

   my $url = sprintf( "%s/API/QueryInfo", $ip ); 
	my $postfields = { 
	   					 event => 'querytxallsms'
						  };
   my $jsonEncoded = encode_json( $postfields );
   my $curl = WWW::Curl::Easy->new;
   $curl->setopt( CURLOPT_HEADER,0);
   $curl->setopt( CURLOPT_URL, $url);
   $curl->setopt( CURLOPT_MAXREDIRS, 10 );                                                
   $curl->setopt( CURLOPT_POSTFIELDS, $jsonEncoded );
   $curl->setopt( CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
   $curl->setopt( CURLOPT_HTTPAUTH, CURLAUTH_ANY ) ;
   $curl->setopt( CURLOPT_USERPWD, $auth );
   $curl->setopt( CURLOPT_POST, 1);
   $curl->setopt( CURLOPT_TIMEOUT, 0);
   $curl->setopt( CURLOPT_FOLLOWLOCATION, 1);
   $curl->setopt( CURLOPT_USERPWD, $auth);
   
   my $response_body;
   $curl->setopt(CURLOPT_WRITEDATA,\$response_body);
   my $retcode = $curl->perform;
   my $error_text = "";

   if ($retcode == 0) {
	   my $response_code = $curl->getinfo(CURLINFO_HTTP_CODE);

     	if( $response_code == 200 ) {

         my $data = decode_json($response_body);
         if( $data->{result} eq "ok" ) {

            my $sn = "0002";
				my $error_code = 200;
				my $smstotal = $data->{smstotal};
            if( $smstotal > 0 ) {

               $json = sprintf( '{"error_code":200,"sn":"%s","result":[', $sn );
               $json .= "\n";
               for( $i = 0; $i < $smstotal; $i++ ) {
                  my $sms = sprintf( "SMS%d", $i );
                  my @info = split /:/, $data->{$sms};
                  my $taskid = $info[0];
                  my $time = $info[1];
                  my $port = $info[2];
                  my $recipient = $info[3];
                  my $status = $info[4];

                  my $datetime = substr( $time, 0, 4 ) . "-" . substr( $time, 4, 2 ) . "-" . substr( $time, 6, 2 ) . " " . substr( $time, 8, 2 ) . ":" . substr( $time, 10, 2 ) . ":" . substr( $time, 12, 2 );
                  my $status_report = "";

                  switch( $status ) {

                     case 0 {
                        $status_report = "NONE";
                     }

                     case 3 {
                        $status_report = "DELIVERED";
                     }

                     case 2 {
                        $status_report = "SENDING";
                     }

                     case 4 {
                        $status_report = "FAILED";
                     }

                     case 5 {
                        $status_report = "TIMEOUT";
                     }
                  }
                  $json .= sprintf( '{"port":%d, "number":"%s","time":"%s","ref_id":%d,"status_code":"%s","imsi":""}', $port, $recipient, $datetime, $taskid, $status_report );
                  if( $i < $smstotal-1 ) {
                     $json .= ",\n";
                  } 

#               Dinstar: {"error_code":200,"sn":"xxxx-xxxx-xxxx-xxxx","result":[{"port":0, "number":"12341234","time":"2014-12-21 12:06:01","ref_id":12,"status_code":0,"imsi":"460004642148063"}]}
#               0:20250427175207:1:1144255139:3
#               taskid=0 : 
#               datetime=20250427175207 :
#               port=1   :
#               recipient=1144255139 :
#               send_status=3
#               0-None, 1-Wait, 2-Sending, 3-Successful, 4-Failed 5-Timeout
               }
               $json .= "]}";
					synway_DeleteSms( $ip, $auth, $fecha );
            }
            else {
               $json = sprintf( '{"error_code":200,"sn":"%s","result":[]}', $sn );
            }
         }
			return $json;
     	}
   }
	return "";
}


# ----------------------------------
# synway_DeleteSms
# ----------------------------------

sub synway_DeleteSms {
	my $ip = $_[0];
	my $auth = $_[1];
	my $fecha= $_[2];
   my $json = "";
	my $text = "";
   my @content;

   my $datetime = substr( $fecha,0,4) . substr( $fecha,5,2) . substr( $fecha,8,2) . substr( $fecha,11,2) . substr( $fecha,14,2) . substr( $fecha,17,2);
   my $url = sprintf( "%s/API/DeleteSMS", $ip ); 
	my $postfields = { 
	   					 event => 'deletesms',
#     					 begintime => $datetime,
	   					 endtime => $datetime,
	   					 smsbox => 's',
	   					 clear => '1'
						  };

   my $jsonEncoded = encode_json( $postfields );
   printf( "%s\n", $jsonEncoded );

   my $curl = WWW::Curl::Easy->new;
   $curl->setopt( CURLOPT_HEADER,0);
   $curl->setopt( CURLOPT_URL, $url);
   $curl->setopt( CURLOPT_MAXREDIRS, 10 );                                                
   $curl->setopt( CURLOPT_POSTFIELDS, $jsonEncoded );
   $curl->setopt( CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
   $curl->setopt( CURLOPT_HTTPAUTH, CURLAUTH_ANY ) ;
   $curl->setopt( CURLOPT_USERPWD, $auth );
   $curl->setopt( CURLOPT_POST, 1);
   $curl->setopt( CURLOPT_TIMEOUT, 0);
   $curl->setopt( CURLOPT_FOLLOWLOCATION, 1);
   $curl->setopt( CURLOPT_USERPWD, $auth);
   
   my $response_body;
   $curl->setopt(CURLOPT_WRITEDATA,\$response_body);
   my $retcode = $curl->perform;
   my $error_text = "";

   if ($retcode == 0) {
	   my $response_code = $curl->getinfo(CURLINFO_HTTP_CODE);

     	if( $response_code == 200 ) {

         my $data = decode_json($response_body);
         if( $data->{result} eq "ok" ) {

#           {“result”:“ok”,“content”:“}
				@content = split /:/, $data->{content};  

#            printf( "%s\n", $data->{content} );
#            printf( "%s\n", $content[0] );      # total
            printf( "%s\n", $content[1] );      # num
         }
			return $content[1];
     	}
   }
	return "0";
}

# --------------------
# receiveSms
# --------------------
sub synway_ReceiveSms {

   my $ip = $_[0];
   my $port = $_[1];
   my $flag = $_[2];
   my $auth = $_[3];

   my $url = sprintf( "%s/api/query_incoming_sms", $ip ); 
   my $postfields = { port => $port,
                      flag => $flag };
   my $jsonEncoded = encode_json( $postfields );
   my $curl = WWW::Curl::Easy->new;
   $curl->setopt( CURLOPT_HEADER,0);
   $curl->setopt( CURLOPT_URL, $url);
   $curl->setopt( CURLOPT_MAXREDIRS, 10 );                                                
   $curl->setopt( CURLOPT_POSTFIELDS, $jsonEncoded );
   $curl->setopt( CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
   $curl->setopt( CURLOPT_HTTPAUTH, CURLAUTH_ANY ) ;
   $curl->setopt( CURLOPT_USERPWD, $auth );
   $curl->setopt( CURLOPT_POST, 1);
   $curl->setopt( CURLOPT_TIMEOUT, 0);
   $curl->setopt( CURLOPT_FOLLOWLOCATION, 1);
   $curl->setopt( CURLOPT_USERPWD, $auth);
   
   my $response_body;
   $curl->setopt(CURLOPT_WRITEDATA,\$response_body);
   my $retcode = $curl->perform;
   my $error_text = "";

   if ($retcode == 0) {
		my $response_code = $curl->getinfo(CURLINFO_HTTP_CODE);
     	if( $response_code == 200 ) {
        	my $resultSend = decode_json($response_body);
			return $resultSend;
     	}
   }
   return "";
}

# ------------------
# queryPortStatus
# ------------------

sub synway_QueryPortInfo {
   my $ip = $_[0];
   my $port = $_[1];
   my $auth_name = $_[2];
   my $sn = $_[3];
   my @states = ("UNREGISTER","REGISTER_OK","SEARCHING_NETWORK","NO_SIM","UNKNOWN", "ROAMING", "NO_SIM");
   my @callstates = ("Idle","Off-hook","Ringing","Talking","Dialing","Dialing","Dialing","Pending","","Ringback","Interior","Unavailable");
   my @reg;
   my @imei;
   my @imsi;
   my @iccid;
   my @porttype;
   my $totales = 0;
   my @slots;
   my @tPort;
   my @tPortState;
   my @tPortOp;
   my @tPortType;
   my @tPortSig;
   my $data;

#POWER_OFF, NO_SIM, PIN_REQUIRE,
#PUK_REQUIRE, UNREGISTER,
#SEARCHING_NETWORK, REGISTER_OK or
#UNKNOWN.

   my $auth_basic = encode_base64($auth_name);
   my $url = $ip . "/API/QueryPortConnectState";

   if( $port == -1 ) {
   	$data = { event => "getportconnectstate" };
	}
	else {
   	$data = { event => "getportconnectstate" };
	}	

   my $content = encode_json( $data );
   my $curl = WWW::Curl::Easy->new;
   $curl->setopt( CURLOPT_URL, $url);
   $curl->setopt( CURLOPT_HTTPAUTH, CURLAUTH_ANY ) ;
   $curl->setopt( CURLOPT_HEADER,0);
   $curl->setopt( CURLOPT_USERPWD, $auth_name );
   $curl->setopt( CURLOPT_POST, 1);
   $curl->setopt( CURLOPT_MAXREDIRS, 10 );                                                
   $curl->setopt( CURLOPT_POSTFIELDS, $content );
   $curl->setopt( CURLOPT_HTTPHEADER, ["Content-type:application/json;charset='utf-8'","Accept:application/json"]);
   $curl->setopt( CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1 );
   $curl->setopt( CURLOPT_TIMEOUT, 0);
   $curl->setopt( CURLOPT_FOLLOWLOCATION, 1);
   $curl->setopt( CURLINFO_HEADER_OUT, 1 );
   $curl->setopt( CURLOPT_SSL_VERIFYPEER, 0);
   $curl->setopt( CURLOPT_SSL_VERIFYHOST, 0);

   my $response_body;
   $curl->setopt(CURLOPT_WRITEDATA,\$response_body);
   my $retcode = $curl->perform;
   my $error_text = "";


   if ($retcode == 0) {
		my $response_code = $curl->getinfo(CURLINFO_HTTP_CODE);
     	if( $response_code == 200 ) {

         $data = decode_json($response_body);
         if( $data->{result} eq "ok" ) {

            my @info = split /;/, $data->{content};
            my @portsConnect = split /:/, $info[1];
           	my @ports = split /,/, $portsConnect[1];
            my $state = "";
            my @total = split /:/, $info[0];
            $totales = $total[1];

            for( my $i = 0; $i < $total[1]; $i++ ) {
               $reg[$i] = $states[$ports[$i]];
            }
         }
     	}
   }


	# -----------------
	# Available Slots
	# -----------------
   $auth_basic = encode_base64($auth_name);
   $url = $ip . "/API/QueryPortInfo";
 	$data = { event => "getportinfoex" };

   $content = encode_json( $data );
   $curl = WWW::Curl::Easy->new;
   $curl->setopt( CURLOPT_URL, $url);
   $curl->setopt( CURLOPT_HTTPAUTH, CURLAUTH_ANY ) ;
   $curl->setopt( CURLOPT_HEADER,0);
   $curl->setopt( CURLOPT_USERPWD, $auth_name );
   $curl->setopt( CURLOPT_POST, 1);
   $curl->setopt( CURLOPT_MAXREDIRS, 10 );                                                
   $curl->setopt( CURLOPT_POSTFIELDS, $content );
   $curl->setopt( CURLOPT_HTTPHEADER, ["Content-type:application/json;charset='utf-8'","Accept:application/json"]);
   $curl->setopt( CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1 );
   $curl->setopt( CURLOPT_TIMEOUT, 0);
   $curl->setopt( CURLOPT_FOLLOWLOCATION, 1);
   $curl->setopt( CURLINFO_HEADER_OUT, 1 );
   $curl->setopt( CURLOPT_SSL_VERIFYPEER, 0);
   $curl->setopt( CURLOPT_SSL_VERIFYHOST, 0);

   $response_body = "";
   $curl->setopt(CURLOPT_WRITEDATA,\$response_body);
   $retcode = $curl->perform;
   $error_text = "";

   if ($retcode == 0) {
		my $response_code = $curl->getinfo(CURLINFO_HTTP_CODE);
     	if( $response_code == 200 ) {

         $data = decode_json($response_body);
         if( $data->{result} eq "ok" ) {

            my @info = split /;/, $data->{content};
            
#           info[0] = total:32
#           info[1] = portstate:17,17,17,17:16,17,17,17:16,17,17,17:17,17,17,17:17,17,17,17:17,17,17,17:17,17,17,17:17,17,17,17:17,17,17,17:17,17,17,17:17,17,17,17:17,17,17,17:17,17,17,17:17,17,17,17:1 

            my $status = substr( $info[1],10 );
            my @ports = split /:/, $status;

            my @total = split /:/, $info[0];
            my $state = "";
            $totales = $total[1];

				# ----------------------------------------
				# 0 In Use, 16 Available  17 Unavailable
				# ----------------------------------------
            for( my $i = 0; $i < $total[1]; $i++ ) {
            
               $slots[$i] = "";
               my @portSlots = split /,/, $ports[$i];
               for( my $s = 0; $s < 4; $s++ ) {
                  if( $portSlots[$s] == 0 ) {
                     $slots[$i] = $s;
                  }
               }
#              printf( "Port: %d/%d\n", $i, $slots[$i] );  
            }
         }
     	}
   }


   # ------
   # IMEI  
   # ------     
   $url = $ip . "/API/QueryWireLessInfo";
   $data = { event => "getwirelessinfo", type => "IMEI" };

   $content = encode_json( $data );
   $curl = WWW::Curl::Easy->new;
   $curl->setopt( CURLOPT_URL, $url);
   $curl->setopt( CURLOPT_HTTPAUTH, CURLAUTH_ANY ) ;
   $curl->setopt( CURLOPT_HEADER,0);
   $curl->setopt( CURLOPT_USERPWD, $auth_name );
   $curl->setopt( CURLOPT_POST, 1);
   $curl->setopt( CURLOPT_MAXREDIRS, 10 );                                                
   $curl->setopt( CURLOPT_POSTFIELDS, $content );
   $curl->setopt( CURLOPT_HTTPHEADER, ["Content-type:application/json;charset='utf-8'","Accept:application/json"]);
   $curl->setopt( CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1 );
   $curl->setopt( CURLOPT_TIMEOUT, 0);
   $curl->setopt( CURLOPT_FOLLOWLOCATION, 1);
   $curl->setopt( CURLINFO_HEADER_OUT, 1 );
   $curl->setopt( CURLOPT_SSL_VERIFYPEER, 0);
   $curl->setopt( CURLOPT_SSL_VERIFYHOST, 0);

   $response_body = "";
   $curl->setopt(CURLOPT_WRITEDATA,\$response_body);
   $retcode = $curl->perform;
   $error_text = "";

   if ($retcode == 0) {
		my $response_code = $curl->getinfo(CURLINFO_HTTP_CODE);
     	if( $response_code == 200 ) {

         $data = decode_json($response_body);
         if( $data->{result} eq "ok" ) {

            my @info = split /;/, $data->{content};
            my @ports = split /,/, $info[0];

            my @imeis = split /\./, $ports[0];

            for( my $i = 0; $i < $totales; $i++ ) {

               my @imei_data = split /:/, $imeis[$i];
               my $index = $imei_data[0]; 
               $imei[$index-1] = $imei_data[1];
            }
         }
      }
   }

   # ------
   # IMSI
   # ------     
   $url = $ip . "/API/QueryWireLessInfo";
   $data = { event => "getwirelessinfo", type => "IMSI" };

   $content = encode_json( $data );
   $curl = WWW::Curl::Easy->new;
   $curl->setopt( CURLOPT_URL, $url);
   $curl->setopt( CURLOPT_HTTPAUTH, CURLAUTH_ANY ) ;
   $curl->setopt( CURLOPT_HEADER,0);
   $curl->setopt( CURLOPT_USERPWD, $auth_name );
   $curl->setopt( CURLOPT_POST, 1);
   $curl->setopt( CURLOPT_MAXREDIRS, 10 );                                                
   $curl->setopt( CURLOPT_POSTFIELDS, $content );
   $curl->setopt( CURLOPT_HTTPHEADER, ["Content-type:application/json;charset='utf-8'","Accept:application/json"]);
   $curl->setopt( CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1 );
   $curl->setopt( CURLOPT_TIMEOUT, 0);
   $curl->setopt( CURLOPT_FOLLOWLOCATION, 1);
   $curl->setopt( CURLINFO_HEADER_OUT, 1 );
   $curl->setopt( CURLOPT_SSL_VERIFYPEER, 0);
   $curl->setopt( CURLOPT_SSL_VERIFYHOST, 0);

   $response_body = "";
   $curl->setopt(CURLOPT_WRITEDATA,\$response_body);
   $retcode = $curl->perform;
   $error_text = "";

   if ($retcode == 0) {
		my $response_code = $curl->getinfo(CURLINFO_HTTP_CODE);
     	if( $response_code == 200 ) {

         $data = decode_json($response_body);
         if( $data->{result} eq "ok" ) {

            my @info = split /;/, $data->{content};
            my @ports = split /,/, $info[0];

            my @imsis = split /\./, $ports[0];
            for( my $i = 0; $i < $totales; $i++ ) {

               my @imsi_data = split /:/, $imsis[$i];
               my $index = $imsi_data[0]; 

               if( $imsi_data[1] eq "----" ) {
                  $imsi[$index-1] = "";
               }
               else {
                  $imsi[$index-1] = $imsi_data[1];
               }
            }
         }
      }
   }

   # ------
   # ICCID
   # ------     
   $url = $ip . "/API/QueryWireLessInfo";
   $data = { event => "getwirelessinfo", type => "ICCID" };

   $content = encode_json( $data );
   $curl = WWW::Curl::Easy->new;
   $curl->setopt( CURLOPT_URL, $url);
   $curl->setopt( CURLOPT_HTTPAUTH, CURLAUTH_ANY ) ;
   $curl->setopt( CURLOPT_HEADER,0);
   $curl->setopt( CURLOPT_USERPWD, $auth_name );
   $curl->setopt( CURLOPT_POST, 1);
   $curl->setopt( CURLOPT_MAXREDIRS, 10 );                                                
   $curl->setopt( CURLOPT_POSTFIELDS, $content );
   $curl->setopt( CURLOPT_HTTPHEADER, ["Content-type:application/json;charset='utf-8'","Accept:application/json"]);
   $curl->setopt( CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1 );
   $curl->setopt( CURLOPT_TIMEOUT, 0);
   $curl->setopt( CURLOPT_FOLLOWLOCATION, 1);
   $curl->setopt( CURLINFO_HEADER_OUT, 1 );
   $curl->setopt( CURLOPT_SSL_VERIFYPEER, 0);
   $curl->setopt( CURLOPT_SSL_VERIFYHOST, 0);


   $response_body = "";
   $curl->setopt(CURLOPT_WRITEDATA,\$response_body);
   $retcode = $curl->perform;
   $error_text = "";

   if ($retcode == 0) {
		my $response_code = $curl->getinfo(CURLINFO_HTTP_CODE);
     	if( $response_code == 200 ) {

         $data = decode_json($response_body);
         if( $data->{result} eq "ok" ) {

            my @info = split /;/, $data->{content};
            my @ports = split /,/, $info[0];
            my @iccids = split /\./, $ports[0];

            for( my $i = 0; $i < $totales; $i++ ) {

               my @iccid_data = split /:/, $iccids[$i];
               my $index = $iccid_data[0]; 

               if( $iccid_data[1] eq "----" ) {
                  $iccid[$index-1] = "";
               }
               else {
                  $iccid[$index-1] = $iccid_data[1];
               }
#               printf( "%s\n", $iccid[$i]);
            }

         }
      }
   }

   # ------
   # Portype
   # ------     
   $url = $ip . "/API/QueryWireLessInfo";
   $data = { event => "getwirelessinfo", type => "porttype" };

   $content = encode_json( $data );
   $curl = WWW::Curl::Easy->new;
   $curl->setopt( CURLOPT_URL, $url);
   $curl->setopt( CURLOPT_HTTPAUTH, CURLAUTH_ANY ) ;
   $curl->setopt( CURLOPT_HEADER,0);
   $curl->setopt( CURLOPT_USERPWD, $auth_name );
   $curl->setopt( CURLOPT_POST, 1);
   $curl->setopt( CURLOPT_MAXREDIRS, 10 );                                                
   $curl->setopt( CURLOPT_POSTFIELDS, $content );
   $curl->setopt( CURLOPT_HTTPHEADER, ["Content-type:application/json;charset='utf-8'","Accept:application/json"]);
   $curl->setopt( CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1 );
   $curl->setopt( CURLOPT_TIMEOUT, 0);
   $curl->setopt( CURLOPT_FOLLOWLOCATION, 1);
   $curl->setopt( CURLINFO_HEADER_OUT, 1 );
   $curl->setopt( CURLOPT_SSL_VERIFYPEER, 0);
   $curl->setopt( CURLOPT_SSL_VERIFYHOST, 0);

   $response_body = "";
   $curl->setopt(CURLOPT_WRITEDATA,\$response_body);
   $retcode = $curl->perform;
   $error_text = "";

   if ($retcode == 0) {
		my $response_code = $curl->getinfo(CURLINFO_HTTP_CODE);
     	if( $response_code == 200 ) {

         $data = decode_json($response_body);
         if( $data->{result} eq "ok" ) {

            my @info = split /;/, $data->{content};
            my @ports = split /,/, $info[0];

            my @porttypes = split /\./, $ports[0];
            my @porttype_data = split /:/, $porttypes[0];
            for( my $i = 0; $i < $totales; $i++ ) {

               $porttype[$i] = $porttype_data[1]; 
            }
         }
      }
   }


   # ----------
   # Detail
   # ----------
   $url = $ip . "/API/QueryInfo";
   $data = { event => "getDetailPortInfo" };

   $content = encode_json( $data );
   $curl = WWW::Curl::Easy->new;
   $curl->setopt( CURLOPT_URL, $url);
   $curl->setopt( CURLOPT_HTTPAUTH, CURLAUTH_ANY ) ;
   $curl->setopt( CURLOPT_HEADER,0);
   $curl->setopt( CURLOPT_USERPWD, $auth_name );
   $curl->setopt( CURLOPT_POST, 1);
   $curl->setopt( CURLOPT_MAXREDIRS, 10 );                                                
   $curl->setopt( CURLOPT_POSTFIELDS, $content );
   $curl->setopt( CURLOPT_HTTPHEADER, ["Content-type:application/json;charset='utf-8'","Accept:application/json"]);
   $curl->setopt( CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1 );
   $curl->setopt( CURLOPT_TIMEOUT, 0);
   $curl->setopt( CURLOPT_FOLLOWLOCATION, 1);
   $curl->setopt( CURLINFO_HEADER_OUT, 1 );
   $curl->setopt( CURLOPT_SSL_VERIFYPEER, 0);
   $curl->setopt( CURLOPT_SSL_VERIFYHOST, 0);

   $response_body = "";
   $curl->setopt(CURLOPT_WRITEDATA,\$response_body);
   $retcode = $curl->perform;
   $error_text = "";

   if ($retcode == 0) {
		my $response_code = $curl->getinfo(CURLINFO_HTTP_CODE);
     	if( $response_code == 200 ) {

         $data = decode_json($response_body);
         if( $data->{result} eq "ok" ) {
            my $totalport = $data->{totalPort};
            my $portState = $data->{portState};
            my $portOp = $data->{portOp};
            my $portType = $data->{portType};
            my $portSig = $data->{portSig};

            @tPort = split /,/, $totalport;
            @tPortState = split /,/, $portState;
            @tPortOp = split /,/, $portOp;
            @tPortType = split /,/, $portType;
            @tPortSig = split /,/, $portSig;
         }
      }
   }


   my $json = sprintf( '{"error_code":200,"sn":"%s","info":[', $sn );
#  printf( "%s\n", $json );
   for( my $i = 0; $i < 32; $i++ ) {
      my $state = sprintf( '{"port":%d,"type":"%s","imei":"%s","imsi":"%s","iccid":"%s","number":"","reg":"%s","slot":"%s","callstate":"%s","signal":%s}', $i, $tPortType[0], $imei[$i], $imsi[$i], $iccid[$i], $reg[$i], $slots[$i], $callstates[$tPortState[$i]], $tPortSig[$i] );
      if( $i < 31 ) {
         $state .= ",";
      }
		$json .= $state;
   }
   $json .= "]}\n";
   return $json;
}


# -------------------
# synway_ChangeIMEI
# -------------------
sub synway_ChangeIMEI {
	my $ip = $_[0];
	my $port = $_[1];
	my $auth = $_[2];
	my $imei = $_[3];

   my $headers = 
      "'Host: ' . $ip,
      'Connection: keep-alive',
      'Authorization: Basic YWRtaW46cGVwaXRvMjA=',
      'Upgrade-Insecure-Requests: 1',
      'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36',
      'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
      'Referer: http://10.0.66.106/en/5-4-1IMEIset.php',
      'Accept-Encoding: gzip, deflate',
      'Accept-Language: es-AR,es;q=0.9,en-US;q=0.8,en;q=0.7,es-419;q=0.6',
      'Content-Type: application/x-www-form-urlencoded'";
#      'Referer: http://' . $ip . '/en/5-4IMEI.php',


   my $url = sprintf( "%s/en/5-4-1IMEIset.php", $ip ); 
   my $content = sprintf( "IMEI%d=%s&save=Save", $port-1, $imei);
   my $curl = WWW::Curl::Easy->new;
   $curl->setopt( CURLOPT_HEADER,0);
   $curl->setopt( CURLOPT_URL, $url);
   $curl->setopt( CURLOPT_MAXREDIRS, 10 );                                                
   $curl->setopt( CURLOPT_HTTPHEADER, [$headers] ); 
   $curl->setopt( CURLOPT_HTTPAUTH, CURLAUTH_ANY ) ;
   $curl->setopt( CURLOPT_USERPWD, $auth );
   $curl->setopt( CURLOPT_POST, 0);
   $curl->setopt( CURLOPT_POSTFIELDS, $content);
   $curl->setopt( CURLOPT_TIMEOUT, 0);
   $curl->setopt( CURLOPT_FOLLOWLOCATION, 1);
   $curl->setopt( CURLINFO_HEADER_OUT, 1 );
   
   my $response_body;
   $curl->setopt(CURLOPT_WRITEDATA,\$response_body);
   my $retcode = $curl->perform;
   my $error_text = "";

   if ($retcode == 0) {
   	my $response_code = $curl->getinfo(CURLINFO_HTTP_CODE);
     	if( $response_code == 200 ) {

#            open(FH, '>', "./setImei.txt") or die $!;   
#            print FH $response_body;
#            close(FH);
      }
   }
   return( 0 );
}

# -------------------
# synway_GetIMEI
# -------------------
sub synway_GetIMEI {
   my $ip = $_[0];
   my $port = $_[1];
   my $auth_name = $_[2];
   my $sn = $_[3];

   # ------
   # IMEI  
   # ------     
   my $url = $ip . "/API/QueryWireLessInfo";
   my $data = { event => "getwirelessinfo", type => "IMEI", port => $port };

   my $content = encode_json( $data );
   my $curl = WWW::Curl::Easy->new;
   $curl->setopt( CURLOPT_URL, $url);
   $curl->setopt( CURLOPT_HTTPAUTH, CURLAUTH_ANY ) ;
   $curl->setopt( CURLOPT_HEADER,0);
   $curl->setopt( CURLOPT_USERPWD, $auth_name );
   $curl->setopt( CURLOPT_POST, 1);
   $curl->setopt( CURLOPT_MAXREDIRS, 10 );                                                
   $curl->setopt( CURLOPT_POSTFIELDS, $content );
   $curl->setopt( CURLOPT_HTTPHEADER, ["Content-type:application/json;charset='utf-8'","Accept:application/json"]);
   $curl->setopt( CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1 );
   $curl->setopt( CURLOPT_TIMEOUT, 0);
   $curl->setopt( CURLOPT_FOLLOWLOCATION, 1);
   $curl->setopt( CURLINFO_HEADER_OUT, 1 );
   $curl->setopt( CURLOPT_SSL_VERIFYPEER, 0);
   $curl->setopt( CURLOPT_SSL_VERIFYHOST, 0);

   my $response_body = "";
   $curl->setopt(CURLOPT_WRITEDATA,\$response_body);
   my $retcode = $curl->perform;
   my $error_text = "";

   if ($retcode == 0) {
		my $response_code = $curl->getinfo(CURLINFO_HTTP_CODE);
     	if( $response_code == 200 ) {

         my $data = decode_json($response_body);
         if( $data->{result} eq "ok" ) {
#           printf( "%s\n", $data->{content} );
            my @info = split /:/, $data->{content};
#           printf( "%s\n", $info[0] );
#           printf( "%s\n", $info[1] );
            return substr($info[1],0,15);
         }
      }
   }
   return "";
}


# --------------
# enableSlot
# --------------

sub synway_EnableSlot {
	my $ip = $_[0];
	my $port = $_[1];
	my $slot = $_[2];
	my $auth = $_[3];
	my $jsessionid = $_[4];
	my $slot_num = "";
	my $sn = $_[5];

   my $url = "$ip/API/SwitchCard";
   my $content = "event=switchcard,port=$port.$slot";
	my $device = sprintf( "devckie=%s", $sn ); 

   my $curl = WWW::Curl::Easy->new;
   $curl->setopt( CURLOPT_HEADER,0);
   $curl->setopt( CURLOPT_URL, $url);
   $curl->setopt( CURLOPT_MAXREDIRS, 10 );                                                
   $curl->setopt( CURLOPT_POSTFIELDS, $content );
   $curl->setopt( CURLOPT_HTTPAUTH, CURLAUTH_ANY ) ;
   $curl->setopt( CURLOPT_USERPWD, $auth );
   $curl->setopt( CURLOPT_POST, 1);
   $curl->setopt( CURLOPT_TIMEOUT, 0);
   $curl->setopt( CURLOPT_FOLLOWLOCATION, 1);
   $curl->setopt( CURLINFO_HEADER_OUT, 1 );

   my $response_body;
   $curl->setopt(CURLOPT_WRITEDATA,\$response_body);
   my $retcode = $curl->perform;
   my $error_text = "";

   if ($retcode == 0) {
		my $response_code = $curl->getinfo(CURLINFO_HTTP_CODE);
     	if( $response_code == 200 ) {
			return $response_code;
     	}
   }
   return 0;
}

# --------------
# disableSlot
# --------------

sub synway_DisableSlot {
   return 0;
}

# -----------------------------------
# loginDinstar
# -----------------------------------

sub synway_LoginGateway {
   return "";
}



=begin
# -----------------------------------
# changeToSlot
# -----------------------------------

sub synway_ChangeToSlot {
	my $ip = $_[0];
	my $port = $_[1];
	my $slot = $_[2];
	my $auth = $_[3];
	my $slot_num = "";

   switch( $slot ) {
      case ( "A" || "a" )
         { $slot_num = 0 }

      case ( "B" || "b" )
         { $slot_num = 1 }

      case ( "C" || "c" )
         { $slot_num = 2 }

      case ( "D" || "d" )
         { $slot_num = 3 }
   }

   my $url = sprintf( "%s/api/set_port_info", $ip ); 
   my $content = "port=" . $port . "&action=slot" . "&param=" . $slot_num;

   my $curl = WWW::Curl::Easy->new;
   $curl->setopt( CURLOPT_HEADER,0);
   $curl->setopt( CURLOPT_URL, $url);
   $curl->setopt( CURLOPT_MAXREDIRS, 10 );                                                
   $curl->setopt( CURLOPT_POSTFIELDS, $content );
#  $curl->setopt( CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
   $curl->setopt( CURLOPT_HTTPAUTH, CURLAUTH_ANY ) ;
   $curl->setopt( CURLOPT_USERPWD, $auth );
   $curl->setopt( CURLOPT_POST, 1);
   $curl->setopt( CURLOPT_TIMEOUT, 0);
   $curl->setopt( CURLOPT_FOLLOWLOCATION, 1);
   $curl->setopt( CURLINFO_HEADER_OUT, 1 );

   my $response_body;
   $curl->setopt(CURLOPT_WRITEDATA,\$response_body);
   my $retcode = $curl->perform;
   my $error_text = "";

   if ($retcode == 0) {
		my $response_code = $curl->getinfo(CURLINFO_HTTP_CODE);
     	if( $response_code == 200 ) {
        	my $resultSend = decode_json($response_body);
			return "Ok";
     	}
   }
   return "Error";
}

# -------------------------------------
# getIMEI
# -------------------------------------

sub synway_GetIMEI {
	my $ip = $_[0];
	my $auth = $_[1];
	my $port = $_[2];
	my $channels = $_[3];
	my $public_url = $_[4];

   my @IMEI;
    my @new_imei;

   my $headers = 
      "'Host: $ip', 'Connection: keep-alive', 'Authorization: Basic YWRtaW46cGVwaXRvMjA=', 'Upgrade-Insecure-Requests: 1', 'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36',
      'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9', 'Referer: http://$ip/en/navigation_imei.php',
      'Accept-Encoding: gzip, deflate', 'Accept-Language: es-AR,es;q=0.9,en-US;q=0.8,en;q=0.7,es-419;q=0.6'";

   my $url = sprintf( "%s/en/5-4-1IMEIset.php", $public_url ); 
	my $curl = WWW::Curl::Easy->new;
   $curl->setopt( CURLOPT_HEADER,0);
   $curl->setopt( CURLOPT_URL, $url);
   $curl->setopt( CURLOPT_MAXREDIRS, 10 );                                                
   $curl->setopt( CURLOPT_HTTPHEADER, [$headers] ); 
   $curl->setopt( CURLOPT_HTTPAUTH, CURLAUTH_ANY ) ;
   $curl->setopt( CURLOPT_USERPWD, $auth );
   $curl->setopt( CURLOPT_POST, 0);
   $curl->setopt( CURLOPT_TIMEOUT, 0);
   $curl->setopt( CURLOPT_FOLLOWLOCATION, 1);
   $curl->setopt( CURLINFO_HEADER_OUT, 1 );

   my $response_body;
   $curl->setopt(CURLOPT_WRITEDATA,\$response_body);
   my $retcode = $curl->perform;
   my $error_text = "";

   if ($retcode == 0) {
		my $response_code = $curl->getinfo(CURLINFO_HTTP_CODE);
     	if( $response_code == 200 ) {

#		   printf( "%s\n", $response_body );

         my $startstr = index($response_body,"function LoadPreData()");
	      my $str = substr( $response_body, $startstr );
      	my $endstr = index($str, "}");
			$str = substr( $str, 0, $endstr );

      	# -----------------------------------
      	# Buscar valores de IMEI en $str
         # -----------------------------------
         for( my $i = 0; $i < $channels; ++$i ) {
		   
				my $offset = 0;
            my $search = sprintf( "IMEI%d", $i );
            my $strIMEI = index( $str, $search );
            if( $i >= 10 ) {
					$offset = 18;
				}
            else {
					$offset = 17;
				}

            $IMEI[$i] = substr( $str, $strIMEI + $offset, 15 );
#           printf( "%s\n", $IMEI[$i] );
#           $new_imei[$i] = changeIMEI( $IMEI[$i] );
#      		printf( "Port %2d: %s -> %s\n", $i + 1, $IMEI[$i], $new_imei[$i] );
#          	printf( "Port %2d: %s\n", $i + 1, $IMEI[$i] );
        }
#        setIMEI( $ip, $public_url, $auth, 0, $new_imei[0] );
#        return( $new_imei[$port] );
#        printf( "%s\n", $IMEI[$port] );
         return( $IMEI[$port] );
     	}
   }
	return "";
}

   // -------------------------------------
   // setIMEI
   // -------------------------------------

   function setIMEI( $ip, $public_url, $auth, $port, $imei ) {
      $IMEI = array();

      $headers = array(
         'Host: ' . $ip,
         'Connection: keep-alive',
         'Authorization: Basic YWRtaW46cGVwaXRvMjA=',
         'Upgrade-Insecure-Requests: 1',
         'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36',
         'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
         'Referer: http://10.0.66.106/en/5-4-1IMEIset.php',
         'Accept-Encoding: gzip, deflate',
         'Accept-Language: es-AR,es;q=0.9,en-US;q=0.8,en;q=0.7,es-419;q=0.6',
         'Content-Type: application/x-www-form-urlencoded'
//         'Referer: http://' . $ip . '/en/5-4IMEI.php',
      );


      $url = sprintf( "%s/en/5-4-1IMEIset.php", $public_url ); 
      $content = sprintf( "IMEI%d=%s&save=Save", $port, $imei);
      $curl = curl_init($url);
      curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_ANY ) ;
      curl_setopt($curl, CURLOPT_HEADER, true );
      curl_setopt($curl, CURLINFO_HEADER_OUT, true);
      curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
      curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
      curl_setopt($curl, CURLOPT_USERPWD, $auth ); 
      curl_setopt($curl, CURLOPT_POST, false);
      curl_setopt($curl, CURLOPT_POSTFIELDS, $content);
      curl_setopt($curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
      curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
      curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
      curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
      $json_response = curl_exec($curl);
      $status_code = curl_getinfo($curl, CURLINFO_HTTP_CODE);

      if( $status_code == 200 ) {
         if( ( $file = fopen( "./setImei.txt", "w"  ) ) )  {
            fwrite( $file, $json_response );
            fclose( $file );
         }
//         printf( "%s\n", $json_response );
      }
      curl_close($curl);
      return( 0 );
   }

   $portStatus = array("Idle","Off-hook", "Ringing","Talking","Dialing","Dialing","Dialing","Pending","Ringback","Interior","Unavailable","","","","","","Available","Unavailable");
   $connectState = array("Unconnected","Connected", "Connecting", "Rejected","Unknown","Roaming" );

   // --------------------------------------------------------
   //  queryPortInfo
   // --------------------------------------------------------

   function synway_QueryWirelessInfo($ip,$auth_name,$logged,$logfile,$type,$port) {

      $auth_basic = base64_encode($auth_name);
      $url = $url . "/QueryWireLessInfo";

		my $url = sprintf( "%s/API/SendSMS", $ip ); 


		# ------------
		# Query IMEI  
		# ------------  		
      $postfields1 = array
      (
         'event' => 'getwirelessinfo',
         'type' => "IMEI",
         'port' => $port
      );  

		# ------------
		# Query IMSI  
		# ------------  		
      $postfields2 = array
      (
         'event' => 'getwirelessinfo',
         'type' => "IMSI",
         'port' => $port
      );  


      $content = json_encode($postfields1);
      $curl = curl_init($url);
      curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_ANY ) ;
      curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
      curl_setopt($curl, CURLOPT_HTTPHEADER, array("Content-type: application/json;charset='utf-8'","Accept:application/json") );
      curl_setopt($curl, CURLOPT_USERPWD, $auth_name ); 
      curl_setopt($curl, CURLOPT_POST, true);
      curl_setopt($curl, CURLOPT_POSTFIELDS, $content);
      curl_setopt($curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1 );
      curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
      curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
      curl_setopt($curl, CURLINFO_HEADER_OUT, true);
      $json_response = curl_exec($curl);
      $status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
      curl_close($curl);

      if( $logged == true ) {
         writeToLog( $logfile, "", 1 ); 
         writeToLog( $logfile, $content, 0 ); 
         writeToLog( $logfile, "", 1 ); 
      }

      if( $status == 200 ) {
           return( $json_response );
      }
      else {
         printf( "Error %d\n", $status );
      }
      return "";
   }


   // --------------------------------------------------------
   //  queryPortInfo
   // --------------------------------------------------------

   function queryPortConnectState($url,$auth_name,$logged,$logfile) {

      $auth_basic = base64_encode($auth_name);
      $url = $url . "/QueryPortConnectState";

      $postfields1 = array
      (
         'event' => 'getportconnectstate' 
      );  
   
      $content = json_encode($postfields1);

      $curl = curl_init($url);
      curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_ANY ) ;
      curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
      curl_setopt($curl, CURLOPT_HTTPHEADER, array("Content-type: application/json;charset='utf-8'","Accept:application/json") );
      curl_setopt($curl, CURLOPT_USERPWD, $auth_name ); 
      curl_setopt($curl, CURLOPT_POST, true);
      curl_setopt($curl, CURLOPT_POSTFIELDS, $content);
      curl_setopt($curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1 );
      curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
      curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
      curl_setopt($curl, CURLINFO_HEADER_OUT, true);
      $json_response = curl_exec($curl);
      $status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
      curl_close($curl);

      if( $logged == true ) {
         writeToLog( $logfile, "", 1 ); 
         writeToLog( $logfile, $content, 0 ); 
         writeToLog( $logfile, "", 1 ); 
      }

      if( $status == 200 ) {
           return( $json_response );
      }
      else {
         printf( "Error %d\n", $status );
      }
      return "";
   }
=cut

BEGIN { 
#print "This is BEGIN Block\n" 
}

END { 
#print "In the end block\n"; 
}
1;
	

