const { SerialPort } = require('serialport');
const { ReadlineParser } = require('@serialport/parser-readline');

( async( ) => {
	console.log( await SerialPort.list() );


	let port = new SerialPort( { path: '/dev/ttyS11', baudRate: 9600 } );

	/*port.on('data', function (data) {
		console.log('Data:', data.toString())

	})*/

	port.close()

	let callbacks = {};

	function request()
	{
		return new Promise((resolve, reject) => {
			let id = makeid(8);
			console.log(id);

			let req = {
				id: id,
				type: "REQUEST",
				data: "1,2"
			}

			callbacks[req.id] = resolve;

			let done = false;

			setTimeout( () => {
				if( !done )
					reject("Request with id " + id + " timed out");
			}, 15000 );

			port.write(JSON.stringify(req) + "\r", "utf-8");
		});

	}

	const parser = port.pipe(new ReadlineParser({ delimiter: '\r' }))

	parser.on('data', (data) => {
		/*let req = {
			id: id,
			type: "ACK",
			data: "1,2"
		}*/

		data = data.toString().trim();
		let json = JSON.parse(data);

		console.log("GOT: " + data );
		callbacks[json.id]();

	});

	try {
		await request();
		console.log("FUNCTION RESOLVED YAY!");
	} catch( e )
	{
		console.error(e);
	}
} )();

function makeid(length) {
	var result           = '';
	var characters       = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
	var charactersLength = characters.length;
	for ( var i = 0; i < length; i++ ) {
		result += characters.charAt(Math.floor(Math.random() * charactersLength));
	}
	return result;
}


