module VPCD_Adapter {

/* VPCD Adapter layer, sitting on top of VPCD_CodecPort.
 * test suites can 'inherit' in order to have a VPCD connection to the IUT which they're testing
 *
 * (C) 2018-2019 by 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.
 */

import from VPCD_Types all;
import from VPCD_CodecPort all;
import from VPCD_CodecPort_CtrlFunct all;
import from IPL4asp_Types all;
import from IPL4asp_PortType all;
import from Socket_API_Definitions all;

modulepar {
	integer mp_vpcd_port := 35963;
	charstring mp_vpcd_host := "127.0.0.1";
}

type component VPCD_Adapter_CT {
	port VPCD_CODEC_PT VPCD;
	var integer g_vpcd_conn_id;
};


private function f_set_tcp_segmentation() runs on VPCD_Adapter_CT {
	/* Set function for dissecting the binary stream into packets */
	var f_IPL4_getMsgLen vl_f := refers(f_IPL4_fixedMsgLen);
	/* Offset: 0, size of length: 2, delta: 0, multiplier: 1, big-endian: 0 */
	VPCD_CodecPort_CtrlFunct.f_IPL4_setGetMsgLen(VPCD, g_vpcd_conn_id, vl_f, {0, 2, 2, 1, 0});
}

function f_connect(charstring remote_host := mp_vpcd_host, integer remote_port := mp_vpcd_port)
runs on VPCD_Adapter_CT {
	var IPL4asp_Types.Result res;
	map(self:VPCD, system:VPCD);
	res := VPCD_CodecPort_CtrlFunct.f_IPL4_connect(VPCD, remote_host, remote_port, "", 0, 0,
							{ tcp := {} });
	if (not ispresent(res.connId)) {
		setverdict(fail, "Could not connect to VPCD at ", remote_host, ":", remote_port,
				", check your configuration");
		mtc.stop;
	}
	g_vpcd_conn_id := res.connId;
	f_set_tcp_segmentation();
}

function f_bind(charstring local_host, IPL4asp_Types.PortNumber local_port)
runs on VPCD_Adapter_CT {
	var IPL4asp_Types.Result res;
	map(self:VPCD, system:VPCD);
	res := VPCD_CodecPort_CtrlFunct.f_IPL4_listen(VPCD, local_host, local_port, { tcp:={} });
	g_vpcd_conn_id := res.connId;
	f_set_tcp_segmentation();
}

function f_vpcd_send(template (value) VPCD_PDU pdu) runs on VPCD_Adapter_CT {
	VPCD.send(ts_VPCD_Send(g_vpcd_conn_id, pdu));
}

function f_vpcd_exp(template VPCD_PDU exp) runs on VPCD_Adapter_CT return VPCD_PDU {
	var VPCD_RecvFrom rf;
	VPCD.receive(tr_VPCD_Recv(g_vpcd_conn_id, exp)) -> value rf;
	return rf.msg;
}


}
