refactoring flash client

This commit is contained in:
MaximZaitsev
2016-07-20 16:44:54 +03:00
parent ed4671f5c7
commit 68a1e1cd40
6 changed files with 54 additions and 23 deletions
+46 -14
View File
@@ -1,13 +1,10 @@
import com.google.protobuf.ByteString import client.Client
import com.martiansoftware.jsap.FlaggedOption import com.martiansoftware.jsap.FlaggedOption
import com.martiansoftware.jsap.JSAP import com.martiansoftware.jsap.JSAP
import com.martiansoftware.jsap.JSAPResult import com.martiansoftware.jsap.JSAPResult
import io.netty.buffer.Unpooled import io.netty.buffer.Unpooled
import io.netty.handler.codec.http.* import io.netty.handler.codec.http.*
import java.io.File import java.io.*
import java.io.FileInputStream
import java.io.IOException
import java.io.PrintWriter
import java.util.* import java.util.*
/** /**
@@ -32,7 +29,10 @@ fun main(args: Array<String>) {
val flashFilePath = getActualValue("flash", clArgsConfig, fileConfig) val flashFilePath = getActualValue("flash", clArgsConfig, fileConfig)
val actualValues = mapOf<String, String>(Pair("host", host), Pair("port", port.toString()), Pair("mcuSystem", mcuSystem), Pair("flash", flashFilePath)) val actualValues = mapOf<String, String>(Pair("host", host), Pair("port", port.toString()), Pair("mcuSystem", mcuSystem), Pair("flash", flashFilePath))
saveFileConfig(actualValues)
if (!isCorrectArguments(actualValues)) {
return
}
var fileBytes: ByteArray = ByteArray(0); var fileBytes: ByteArray = ByteArray(0);
try { try {
FileInputStream(flashFilePath).use { fis -> FileInputStream(flashFilePath).use { fis ->
@@ -41,21 +41,53 @@ fun main(args: Array<String>) {
} }
} catch (e: IOException) { } catch (e: IOException) {
e.printStackTrace() e.printStackTrace()
println("error in read file $flashFilePath") println("error reading file $flashFilePath")
return; return;
} }
val bytesBinTest = Carkot.Upload.newBuilder().setData(ByteString.copyFrom(fileBytes)).setBase(mcuSystem).build().toByteArray() saveFileConfig(actualValues)
val request = DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, "/loadBin", Unpooled.copiedBuffer(bytesBinTest));
val uploadObject = Upload.BuilderUpload().setData(fileBytes).setBase(mcuSystem).build()
val uploadBytesStream = ByteArrayOutputStream()
uploadObject.writeTo(CodedOutputStream(uploadBytesStream))
val request = DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, "/loadBin", Unpooled.copiedBuffer(uploadBytesStream.toByteArray()));
request.headers().set(HttpHeaderNames.HOST, host) request.headers().set(HttpHeaderNames.HOST, host)
request.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.CLOSE) request.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.CLOSE)
request.headers().setInt(HttpHeaderNames.CONTENT_LENGTH, request.content().readableBytes()) request.headers().setInt(HttpHeaderNames.CONTENT_LENGTH, request.content().readableBytes())
request.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain; charset=UTF-8") request.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain; charset=UTF-8")
client.Client.sendRequest(request, host, port) val clientInstanse = Client(host, port)
println(client.ClientHandler.requestResult.code) clientInstanse.sendRequest(request)
println(client.ClientHandler.requestResult.stdErr) val requestResult = client.ClientHandler.requestResult
println(client.ClientHandler.requestResult.stdOut) var printString: String = ""
synchronized(requestResult, {
printString = "result code: ${requestResult.code}\n" +
"result error message: ${requestResult.stdErr}\n" +
"result out message: ${requestResult.stdOut}"
})
println(printString)
}
fun isCorrectArguments(actualValues: Map<String, String>): Boolean {
//host and flash file its required.
val host = actualValues.getOrElse("host", { "" })
val flashFilePath = actualValues.getOrElse("flash", { "" })
if (host.equals("") || flashFilePath.equals("")) {
println("incorrect args (host/flash file must be initialized)")
return false;
}
val file = File(flashFilePath)
if (!file.exists()) {
println("file ${file.absoluteFile} not exist")
return false
}
val ipRegex = Regex("^(?:[0-9]{1,3}.){3}[0-9]{1,3}$")//bad regex. skip ip with first zero (10.05.1.1) and with numbers more 255 (300.300.300.300). this ips is correct for this regex
if (!ipRegex.matches(host)) {
println("incorrect server address.")
return false
}
return true
} }
fun saveFileConfig(actualValues: Map<String, String>) { fun saveFileConfig(actualValues: Map<String, String>) {
@@ -65,7 +97,6 @@ fun saveFileConfig(actualValues: Map<String, String>) {
if (!file.exists()) { if (!file.exists()) {
try { try {
file.createNewFile() file.createNewFile()
} catch (e: IOException) { } catch (e: IOException) {
println("error creating config file. parameters don't saved") println("error creating config file. parameters don't saved")
e.printStackTrace() e.printStackTrace()
@@ -110,6 +141,7 @@ fun readFileConfig(): Map<String, String> {
fun setOptions(jsap: JSAP) { fun setOptions(jsap: JSAP) {
val opthost = FlaggedOption("host").setStringParser(JSAP.STRING_PARSER).setRequired(false).setShortFlag('h').setLongFlag("host") val opthost = FlaggedOption("host").setStringParser(JSAP.STRING_PARSER).setRequired(false).setShortFlag('h').setLongFlag("host")
opthost.setHelp("write here only ip address. domain name (e.g. vk.com is incorrect)")
val optPort = FlaggedOption("port").setStringParser(JSAP.INTEGER_PARSER).setRequired(false).setShortFlag('p').setLongFlag("port") val optPort = FlaggedOption("port").setStringParser(JSAP.INTEGER_PARSER).setRequired(false).setShortFlag('p').setLongFlag("port")
val optBinPath = FlaggedOption("flash").setStringParser(JSAP.STRING_PARSER).setRequired(false).setShortFlag('f').setLongFlag("flash") val optBinPath = FlaggedOption("flash").setStringParser(JSAP.STRING_PARSER).setRequired(false).setShortFlag('f').setLongFlag("flash")
val optmcuSystem = FlaggedOption("mcuSystem").setStringParser(JSAP.STRING_PARSER).setRequired(false).setShortFlag('s') val optmcuSystem = FlaggedOption("mcuSystem").setStringParser(JSAP.STRING_PARSER).setRequired(false).setShortFlag('s')
@@ -1,11 +1,9 @@
package client package client
import io.netty.bootstrap.Bootstrap import io.netty.bootstrap.Bootstrap
import io.netty.channel.ChannelFutureListener
import io.netty.channel.nio.NioEventLoopGroup import io.netty.channel.nio.NioEventLoopGroup
import io.netty.channel.socket.nio.NioSocketChannel import io.netty.channel.socket.nio.NioSocketChannel
import io.netty.handler.codec.http.HttpRequest import io.netty.handler.codec.http.HttpRequest
import io.netty.util.AttributeKey
import java.net.ConnectException import java.net.ConnectException
/** /**
@@ -32,10 +30,10 @@ class Client constructor(host: String, port: Int) {
channel.closeFuture().sync() channel.closeFuture().sync()
} catch (e: InterruptedException) { } catch (e: InterruptedException) {
ClientHandler.requestResult.code = 2 ClientHandler.requestResult.code = 2
// ClientHandler.requestResult.errorString = "command execution interrupted" ClientHandler.requestResult.stdErr = "command execution interrupted"
} catch (e: ConnectException) { } catch (e: ConnectException) {
ClientHandler.requestResult.code = 1 ClientHandler.requestResult.code = 1
// ClientHandler.requestResult.errorString = "don't can connect to server ($host:$port)" ClientHandler.requestResult.stdErr = "don't can connect to server ($host:$port)"
} finally { } finally {
group.shutdownGracefully() group.shutdownGracefully()
} }
@@ -1,11 +1,12 @@
package client package client
import CodedInputStream
import UploadResult
import com.google.protobuf.InvalidProtocolBufferException import com.google.protobuf.InvalidProtocolBufferException
import io.netty.channel.ChannelHandlerContext import io.netty.channel.ChannelHandlerContext
import io.netty.channel.SimpleChannelInboundHandler import io.netty.channel.SimpleChannelInboundHandler
import io.netty.handler.codec.http.HttpContent import io.netty.handler.codec.http.HttpContent
import java.io.ByteArrayInputStream import java.io.ByteArrayInputStream
import CodedInputStream
/** /**
* Created by user on 7/8/16. * Created by user on 7/8/16.
@@ -39,9 +40,9 @@ class ClientHandler : SimpleChannelInboundHandler<Any> {
resultStdOut = uploadResult.stdOut resultStdOut = uploadResult.stdOut
resultStdErr = uploadResult.stdErr resultStdErr = uploadResult.stdErr
} catch (e: InvalidProtocolBufferException) { } catch (e: InvalidProtocolBufferException) {
resultStdErr = "error in " resultStdErr = "protobuf parsing error. bytes from server is not message. stack trace:\n ${e.message}"
resultStdOut = "" resultStdOut = ""
resultCode = 2 resultCode = 1
} }
synchronized(requestResult, { synchronized(requestResult, {
requestResult.code = resultCode requestResult.code = resultCode
+2 -2
View File
@@ -6,11 +6,11 @@ option java_outer_classname = "Location";
message LocationResponse { message LocationResponse {
LocationResponse locationResponse = 1; LocationData locationResponseData = 1;
int32 code = 2; int32 code = 2;
string errorMsg = 3; string errorMsg = 3;
message LocationResponse { message LocationData {
double x = 1; double x = 1;
double y = 2; double y = 2;
double angle = 3; double angle = 3;