From 8f7512c759961768a73d2b3c29c6bc69bea44d60 Mon Sep 17 00:00:00 2001 From: MaximZaitsev Date: Tue, 16 Aug 2016 14:22:46 +0300 Subject: [PATCH] mc transport subsystem --- car_srv/kotlinSrv/src/McTransport.kt | 73 ++++++++++++++++++++++++++++ 1 file changed, 73 insertions(+) create mode 100644 car_srv/kotlinSrv/src/McTransport.kt diff --git a/car_srv/kotlinSrv/src/McTransport.kt b/car_srv/kotlinSrv/src/McTransport.kt new file mode 100644 index 00000000000..63d49a3dc90 --- /dev/null +++ b/car_srv/kotlinSrv/src/McTransport.kt @@ -0,0 +1,73 @@ +/** + * Created by user on 8/16/16. + */ + +class McTransport() { + + private var writeStream: dynamic = null + private var readStream: dynamic = null + private val resultBytes = arrayListOf() + private var callback: (bytes: ByteArray) -> Unit = {} + + fun writeToFile(bytes: ByteArray) { + val bytesT = bytes + writeStream.write(js("new Buffer(bytesT)")); + writeStream.end(); + } + + fun writeToFile(byte: Byte) { + writeToFile(ByteArray(1, { idx -> byte })) + } + + fun initStreams(pathToFile: String) { + writeStream = fs.createWriteStream(pathToFile); + readStream = fs.createReadStream(pathToFile) + readStream.on("readable", { + val data = readStream.read() + if (data != null) { + var messageLength = getBodyLength(resultBytes) + for (i in 0..data.length - 1) { + resultBytes.add(data[i]) + if (messageLength != -1 && messageLength + protoHeaderLength == resultBytes.size) { + + callback.invoke(resultBytes.toByteArray()) + resultBytes.clear() + } else if (messageLength == -1) { + messageLength = getBodyLength(resultBytes) + } + } + } + }) + } + + fun setCallBack(cb: (bytes: ByteArray) -> Unit) { + this.callback = cb + } + + fun closeStreams() { + writeStream = null + readStream = null + } + + private fun getBodyLength(resultBytes: List): Int { + if (resultBytes.size < protoHeaderLength) { + //need first ${protoHeaderLength} bytes - header + return -1 + } + var res = 0 + for (i in 0..protoHeaderLength - 1) { + val curByte = resultBytes.get(i) + val curBytePositive: Int = if (curByte < 0) { + 256 + curByte + } else { + curByte.toInt() + } + res += curBytePositive * Math.pow(2.0, 24.0 - i * 8).toInt() + } + return res + } + +} + +val protoHeaderLength: Int = 4 +val mcTransport = McTransport() \ No newline at end of file