simple refactoring

This commit is contained in:
MaximZaitsev
2016-08-17 15:47:58 +03:00
parent 222edce137
commit e267258520
3 changed files with 48 additions and 29 deletions
+12 -11
View File
@@ -23,19 +23,20 @@ class McTransport() {
fun initStreams(pathToFile: String) {
writeStream = fs.createWriteStream(pathToFile);
readStream = fs.createReadStream(pathToFile)
readStream.on("readable", {
readStream.on("readable", fun() {
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) {
if (data == null) {
return
}
var messageLength = getBodyLength(resultBytes)
callback.invoke(resultBytes.toByteArray())
resultBytes.clear()
} else if (messageLength == -1) {
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)
}
}
})
+1 -1
View File
@@ -79,7 +79,7 @@ class MicroController private constructor() {
throw RcControlException()
}
val sid = (Math.random() * 100000).toInt()
this.rcSid = sid;
this.rcSid = sid
rcHeartBeat(sid)
return sid
}
@@ -4,27 +4,45 @@ import RouteRequest
import mcTransport
import CodedOutputStream
/**
* Created by user on 8/17/16.
*/
fun encode(i: Int): ByteArray {
val result = ByteArray(4)
result[0] = i.shr(24).toByte()
result[1] = i.shr(16).toByte()
result[2] = i.shr(8).toByte()
result[3] = i.toByte()
return result
}
fun decode(bytes: ByteArray): Int {
var result = 0
result += bytes[3]
result += bytes[2].toInt().shl(8)
result += bytes[1].toInt().shl(16)
result += bytes[0].toInt().shl(24)
return result
}
fun encodeRouteRequest(route: RouteRequest): ByteArray {
val protoSize = route.getSizeNoTag()
val routeBytes = ByteArray(protoSize)
route.writeTo(CodedOutputStream(routeBytes))
return routeBytes
}
class RouteExecutorToUsb : RouteExecutor {
override fun executeRoute(route: RouteRequest) {
println("Execute Route:")
val size = encode(route.getSizeNoTag())
val routeBytes = encodeRouteRequest(route)
val protoSize = route.getSizeNoTag()
val routeBytes = ByteArray(protoSize)
route.writeTo(CodedOutputStream(routeBytes))
val fullBytes = ByteArray(route.getSizeNoTag() + 4)
for (i in 0..routeBytes.size - 1) {
fullBytes[i + 4] = routeBytes[i]
mcTransport.setCallBack { bytes ->
println("Read $bytes; decoded: ${decode(bytes)}")
}
fullBytes[0] = protoSize.shr(24).toByte()
fullBytes[1] = protoSize.shr(16).toByte()
fullBytes[2] = protoSize.shr(8).toByte()
fullBytes[3] = protoSize.toByte()
mcTransport.writeToFile(fullBytes)
mcTransport.writeToFile(size)
mcTransport.writeToFile(routeBytes)
}
}
}