module MGCP_Adapter {

/* MGCP Adapter for bsc-nat tests in TTCN-3
 * (C) 2017 Harald Welte <laforge@gnumonks.org>
 * All rights reserved.
 *
 * Released under the terms of GNU General Public License, Version 2 or
 * (at your option) any later version.
 *
 * SPDX-License-Identifier: GPL-2.0-or-later
 */

import from IPL4asp_Types all;

import from MGCP_Types all;
import from MGCP_CodecPort all;
import from MGCP_CodecPort_CtrlFunct all;

import from IPA_Emulation all;


type component MGCP_Adapter_CT {
	/* MGCP Codec Port for MGCP-over-UDP */ 
	port MGCP_CODEC_PT MGCP_UDP;
	port IPA_MGCP_PT MGCP;
	var integer g_mgcp_conn_id := -1;
}

modulepar {
	charstring mp_callagent_ip := "127.0.0.1";
	PortNumber mp_callagent_udp_port := 2727;
	charstring mp_mgw_ip := "127.0.0.1";
	PortNumber mp_mgw_udp_port := 2427;
}

/* build a receive template for receiving a MGCP message. You
 * pass the MGCP response template in, and it will generate an
 * MGCP_RecvFrom template that can match the primitives arriving on the
 * MGCP_CodecPort */
function tr_MGCP_RecvFrom_R(template MgcpResponse resp)
runs on MGCP_Adapter_CT return template MGCP_RecvFrom {
	var template MGCP_RecvFrom mrf := {
		connId := g_mgcp_conn_id,
		remName := mp_mgw_ip,
		remPort := mp_mgw_udp_port,
		locName := mp_callagent_ip,
		locPort := mp_callagent_udp_port,
		msg := { response := resp }
	}
	return mrf;
}


function main() runs on MGCP_Adapter_CT {
	var Result res;
	map(self:MGCP_UDP, system:MGCP_CODEC_PT);
	res := MGCP_CodecPort_CtrlFunct.f_IPL4_connect(MGCP_UDP, mp_mgw_ip, mp_mgw_udp_port,
						mp_callagent_ip, mp_callagent_udp_port,
						0, { udp:={} });
	if (not ispresent(res.connId)) {
		setverdict(fail, "Could not connect MGCP, check your configuration");
		self.stop;
	}
	g_mgcp_conn_id := res.connId;

	while (true) {
		var MgcpCommand mgcp_cmd;
		var MGCP_RecvFrom mrf;

		alt {
		/* From BSC/MGW via UDP up to MSC / Call Agent */
		[] MGCP_UDP.receive(tr_MGCP_RecvFrom_R(?)) -> value mrf {
			MGCP.send(mrf.msg.response);
			}

		/* From MSC / Call Agent down to BSC/MGW */
		[] MGCP.receive(MgcpCommand:?) -> value mgcp_cmd {
			var MgcpMessage msg := { command := mgcp_cmd };
			MGCP_UDP.send(t_MGCP_Send(g_mgcp_conn_id, msg));
			}

		}
	}
}

}
