Skip to content

Commit

Permalink
Use logger instead of prints
Browse files Browse the repository at this point in the history
  • Loading branch information
loucass003 committed Jun 25, 2024
1 parent e27a3fd commit 348dc47
Show file tree
Hide file tree
Showing 4 changed files with 40 additions and 41 deletions.
2 changes: 2 additions & 0 deletions build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@ repositories {

dependencies {
implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.6.0")
implementation("org.slf4j:slf4j-api:1.7.36")
implementation("ch.qos.logback:logback-classic:1.2.11")

testImplementation("org.jetbrains.kotlin:kotlin-test-junit5")
testImplementation("org.junit.jupiter:junit-jupiter-engine:5.9.3")
Expand Down
57 changes: 27 additions & 30 deletions src/main/kotlin/Flasher.kt
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
package dev.llelievr.espflashkotlin

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import dev.llelievr.espflashkotlin.targets.ESP32Target
import dev.llelievr.espflashkotlin.targets.Esp32c3Target
import dev.llelievr.espflashkotlin.targets.Esp8266Target
import java.security.MessageDigest
import java.security.NoSuchAlgorithmException
import java.util.*
import java.util.logging.*
import kotlin.collections.ArrayList
import kotlin.collections.HashMap
import kotlin.math.floor
import kotlin.math.max

Expand Down Expand Up @@ -82,9 +82,10 @@ interface FlashingProgressListener {
@OptIn(ExperimentalStdlibApi::class)
class Flasher(
private val serialInterface: FlasherSerialInterface,
private val enableTrace: Boolean = false
) {
private val slipParser = SLIPParser(serialInterface, enableTrace);
private var logger: Logger? = LoggerFactory.getLogger(Flasher::class.java)

private val slipParser = SLIPParser(serialInterface);

private var currentTarget: FlasherTarget? = null
private var currentTimeout: Long? = null;
Expand Down Expand Up @@ -175,7 +176,7 @@ class Flasher(
val blockCount = (size + writeSize - 1) / writeSize
val eraseSize = flasherTarget.getEraseSize(offset, size)

println("Write bin, erase = $eraseSize write = $size ")
logger?.debug("Write bin, erase = $eraseSize write = $size ")
writeWait(
FlashBegin(
eraseSize,
Expand All @@ -191,7 +192,7 @@ class Flasher(
val writeSize = ESP_RAM_BLOCK;
val blockCount = (size + writeSize - 1) / writeSize

println("Write mem, write = $size ")
logger?.debug("Write mem, write = $size ")
writeWait(
MemBegin(
size,
Expand All @@ -207,7 +208,7 @@ class Flasher(
memBegin(stub.text.size, stub.text_start)
val textChunks = stub.text.asSequence().chunked(ESP_RAM_BLOCK)
textChunks.forEachIndexed { index, chunk ->
println("Progress ${(index.toFloat() / textChunks.count()) * 100}")
logger?.debug("Progress ${(index.toFloat() / textChunks.count()) * 100}")
writeWait(
MemData(
chunk.size,
Expand All @@ -220,7 +221,7 @@ class Flasher(
memBegin(stub.data.size, stub.data_start)
val dataChunks = stub.data.asSequence().chunked(ESP_RAM_BLOCK)
dataChunks.forEachIndexed { index, chunk ->
println("Progress ${(index.toFloat() / dataChunks.count()) * 100}")
logger?.debug("Progress ${(index.toFloat() / dataChunks.count()) * 100}")
writeWait(
MemData(
chunk.size,
Expand All @@ -235,22 +236,22 @@ class Flasher(
)


println("Waiting for OHAI response");
logger?.debug("Waiting for OHAI response");
setReadTimeout(DEFAULT_TIMEOUT);
val reader = slipParser.getSlipReader() ?: error("no SLIP reader")
val packetData = reader.next()

if (!packetData.contentEquals(byteArrayOf(0x4F, 0x48, 0x41, 0x49)))
println("Failed to start stub, unexpected response: ${packetData.toHexString()}")
println("Stub running...")
logger?.debug("Failed to start stub, unexpected response: ${packetData.toHexString()}")
logger?.debug("Stub running...")
}

private fun changeBaud(baud: Int): Boolean {
val flasherTarget = currentTarget ?: error("target not set")

val command = ChangeBaudrate(baud, if (flasherTarget.stub() != null) ESP_ROM_BAUD else 0);
if (!command.isPacketSupported(flasherTarget)) {
println("Cannot change the baudrate, packet not supported on this target")
logger?.debug("Cannot change the baudrate, packet not supported on this target")
return false;
}

Expand Down Expand Up @@ -339,7 +340,7 @@ class Flasher(

resetToFlash();

println("Trying to sync")
logger?.debug("Trying to sync")
for (i in 10 downTo 0) {
try {
slipParser.flushInput();
Expand All @@ -364,12 +365,12 @@ class Flasher(
val stub = target.stub();

if (stub != null) {
println("Uploading STUB")
logger?.debug("Uploading STUB")
loadStub(stub);

val newBaud = target.getUploadBaudrate();
if (changeBaud(newBaud))
println("Baudrate changed to $newBaud")
logger?.debug("Baudrate changed to $newBaud")
}
}

Expand Down Expand Up @@ -423,18 +424,16 @@ class Flasher(
val commandBuf = CommandPacket.createCommand(command)
val encoded = slipParser.encodeSLIP(commandBuf)

if (enableTrace) {
println(
"""
---------------------
Command $command
packetPayload=${encoded.toHexString()}
size=${encoded.size}
data=${commandBuf.toHexString()}
---------------------
""".trimIndent()
)
}
logger?.trace(
"""
---------------------
Command $command
packetPayload=${encoded.toHexString()}
size=${encoded.size}
data=${commandBuf.toHexString()}
---------------------
""".trimIndent()
)
serialInterface.write(encoded);
}

Expand All @@ -456,9 +455,7 @@ class Flasher(
res = ResponsePacket.decodeResponse(packetData);

if (res.command == command.command) {
if (enableTrace) {
println(res.toString())
}
logger?.trace(res.toString())
return res;
}
}
Expand Down
8 changes: 4 additions & 4 deletions src/main/kotlin/SLIPParser.kt
Original file line number Diff line number Diff line change
@@ -1,13 +1,15 @@
package dev.llelievr.espflashkotlin


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.ByteArrayOutputStream

@OptIn(ExperimentalStdlibApi::class)
class SLIPParser(
val serialInterface: FlasherSerialInterface,
val enableTrace: Boolean,
) {
private var logger: Logger? = LoggerFactory.getLogger(SLIPParser::class.java)
private var slipReader: Iterator<ByteArray>? = null;

fun flushInput() {
Expand All @@ -28,9 +30,7 @@ class SLIPParser(
val toRead = if (available == 0) 1 else available;
val readBytes = serialInterface.read(toRead);

if (enableTrace) {
println("Read ${readBytes.size} bytes: ${readBytes.toHexString()}")
}
logger?.trace("Read ${readBytes.size} bytes: ${readBytes.toHexString()}")
if (!packetStarted && readBytes[0] == 0.toByte()) {
error("No serial data received.")
}
Expand Down
14 changes: 7 additions & 7 deletions src/test/kotlin/Main.kt
Original file line number Diff line number Diff line change
Expand Up @@ -18,14 +18,14 @@ class LibraryTest: FlasherSerialInterface, FlashingProgressListener {
val ports = SerialPort.getCommPorts()
val firstPort = ports.first() ?: error("unable to find port")

Flasher(this, true)
Flasher(this)
.addProgressListener(this)
// ESP32
// .addBin(File("C:\\Users\\llelievr\\Downloads\\firmware\\firmware-part-0.bin").readBytes(), 4096)
// .addBin(File("C:\\Users\\llelievr\\Downloads\\firmware\\firmware-part-1.bin").readBytes(), 32768)
// .addBin(File("C:\\Users\\llelievr\\Downloads\\firmware\\firmware-part-2.bin").readBytes(), 57344)
// .addBin(File("C:\\Users\\llelievr\\Downloads\\firmware\\firmware-part-3.bin").readBytes(), 65536)
.addBin(File("C:\\Users\\llelievr\\Downloads\\firmware (1)\\firmware-part-0.bin").readBytes(), 0)
.addBin(File("C:\\Users\\llelievr\\Downloads\\firmware\\firmware-part-0.bin").readBytes(), 4096)
.addBin(File("C:\\Users\\llelievr\\Downloads\\firmware\\firmware-part-1.bin").readBytes(), 32768)
.addBin(File("C:\\Users\\llelievr\\Downloads\\firmware\\firmware-part-2.bin").readBytes(), 57344)
.addBin(File("C:\\Users\\llelievr\\Downloads\\firmware\\firmware-part-3.bin").readBytes(), 65536)
// .addBin(File("C:\\Users\\llelievr\\Downloads\\firmware (1)\\firmware-part-0.bin").readBytes(), 0)
.flash(firstPort)
}

Expand Down Expand Up @@ -115,7 +115,7 @@ class LibraryTest: FlasherSerialInterface, FlashingProgressListener {
}

override fun progress(progress: Float) {
println("Progress ${progress * 100}")
// println("Progress ${progress * 100}")
}
}

Expand Down

0 comments on commit 348dc47

Please sign in to comment.