dev-v2.0 #3

Merged
Thiflict merged 11 commits from dev-v2.0 into master 2026-04-19 16:30:26 +00:00
2 changed files with 24 additions and 106 deletions
Showing only changes of commit 17e1925034 - Show all commits

View File

@@ -7,11 +7,11 @@ import java.io.BufferedReader
import java.io.InputStreamReader
import java.util.concurrent.atomic.AtomicBoolean
// Событие клика по кнопке
class ButtonClickEvent
class ButtonLongPressEvent
// Слушатель событий клика
typealias ButtonClickListener = (ButtonClickEvent) -> Unit
typealias ButtonLongPressListener = (ButtonLongPressEvent) -> Unit
class ButtonListener(
private var process: Process? = null,
@@ -19,128 +19,63 @@ class ButtonListener(
private var isListening: AtomicBoolean = AtomicBoolean(false),
private var listenerJob: Job? = null
) {
private val clickListeners = mutableListOf<ButtonClickListener>()
private val longPressListeners = mutableListOf<ButtonLongPressListener>()
var shortPressThresholdMs: Long = 100
var longPressThresholdMs: Long = 1000
private var pressStartTime: Long = 0
fun addClickListener(listener: ButtonClickListener) {
clickListeners.add(listener)
}
fun removeClickListener(listener: ButtonClickListener) {
clickListeners.remove(listener)
}
fun addLongPressListener(listener: ButtonLongPressListener) {
longPressListeners.add(listener)
}
fun removeLongPressListener(listener: ButtonLongPressListener) {
longPressListeners.remove(listener)
}
private fun notifyClick() {
println("=== [CLICK] Короткое нажатие ===")
val event = ButtonClickEvent()
clickListeners.forEach { it.invoke(event) }
}
private fun notifyLongPress() {
println("=== [LONG] Длинное нажатие ===")
val event = ButtonLongPressEvent()
longPressListeners.forEach { it.invoke(event) }
}
fun startListening(onStateChange: ((Boolean) -> Unit)? = null): Boolean {
if (isListening.get()) {
return currentButtonState.get()
}
startListeningInternal(onStateChange)
return currentButtonState.get()
}
private fun startListeningInternal(onStateChange: ((Boolean) -> Unit)? = null) {
try {
val cmd = listOf("gpiomon", "--chip=0", "$BUTTON")
val processBuilder = ProcessBuilder(cmd)
.redirectErrorStream(true)
// Сохраняем процесс в поле
process = processBuilder.start()
isListening.set(true)
listenerJob = CoroutineScope(Dispatchers.IO).launch {
// Используем process, который теперь не null
val reader = BufferedReader(InputStreamReader(process!!.inputStream))
var line: String?
try {
while (reader.readLine().also { line = it } != null) {
println(if (isDebug) "$line" else "")
when {
line?.contains("rising") == true -> {
currentButtonState.set(true)
onStateChange?.invoke(true)
pressStartTime = System.currentTimeMillis()
println(if (isDebug) "Кнопка нажата, время: $pressStartTime" else "")
}
line?.contains("falling") == true -> {
val pressDuration = System.currentTimeMillis() - pressStartTime
currentButtonState.set(false)
onStateChange?.invoke(false)
println(if (isDebug) "Кнопка отпущена, длительность: ${pressDuration}ms" else "")
// Определяем тип нажатия по длительности
when {
pressDuration >= longPressThresholdMs -> {
println(if (isDebug) "Длинное нажатие (${pressDuration}ms)" else "")
notifyLongPress()
}
pressDuration >= shortPressThresholdMs -> {
println(if (isDebug) "Короткое нажатие (${pressDuration}ms)" else "")
println(if (isDebug) "Кнопка нажата" else "")
// Генерируем событие клика при нажатии
notifyClick()
}
else -> {
println(if (isDebug) "Слишком короткое нажатие (${pressDuration}ms) - игнорируем" else "")
line?.contains("falling") == true -> {
currentButtonState.set(false)
onStateChange?.invoke(false)
println(if (isDebug) "Кнопка разжата" else "")
// Убрана проверка на разжатие для генерации события
}
}
}
}
}
} catch (e: Exception) {
println("Ошибка чтения процесса: ${e.message}")
}
val exitCode = process!!.waitFor()
println("Процесс завершён ($exitCode)")
println(if (isDebug) "Процесс завершён ($exitCode)" else "")
isListening.set(false)
// Автоматически перезапускаем прослушивание, если оно должно быть активно
if (isListening.get()) {
println("Перезапуск прослушивания...")
delay(100)
startListeningInternal(onStateChange)
}
}
} catch (e: Exception) {
e.printStackTrace()
isListening.set(false)
}
}
fun stopListening() {
isListening.set(false)
listenerJob?.cancel()
process?.destroy()
process = null
}
fun restartListening(onStateChange: ((Boolean) -> Unit)? = null) {
stopListening()
Thread.sleep(200)
startListening(onStateChange)
return currentButtonState.get()
}
}

View File

@@ -27,7 +27,7 @@ object DebugMode {
// Состояния системы
enum class SystemState {
IDLE, SCANNING, CLEAN, INFECTED, ERROR, INIT, SAMBA
IDLE, SCANNING, CLEAN, INFECTED, ERROR, INIT
}
class USBVirusScanner {
@@ -159,11 +159,6 @@ class USBVirusScanner {
yellowLed.setValue(0)
blinkLed(redLed, 500)
}
SystemState.SAMBA -> {
blinkLed(greenLed, 1000)
blinkLed(yellowLed, 1000)
redLed.setValue(0)
}
}
}
}
@@ -321,7 +316,7 @@ class USBVirusScanner {
try {
// Проверяем установлен ли ClamAV
val checkProcess = ProcessBuilder("which", "clamdscan").start()
val checkProcess = ProcessBuilder("which", "clamscan").start()
val checkExitCode = checkProcess.waitFor()
if (checkExitCode != 0) {
@@ -543,20 +538,9 @@ fun main(args: Array<String>) {
scanner.initialize()
val buttonListener = ButtonListener()
buttonListener.shortPressThresholdMs = 100
buttonListener.longPressThresholdMs = 1000
buttonListener.addClickListener { event ->
scanner.startScan()
}
buttonListener.addLongPressListener { event ->
println(if (isDebug) "ДЛИННОЕ НАЖАТИЕ МЯУ" else "")
println("TODO(\"Добавить отключение samba и размонтирование флешки\")")
}
buttonListener.startListening()
println(if (isDebug) """
@@ -580,5 +564,4 @@ fun main(args: Array<String>) {
scanner.shutdown()
exitProcess(1)
}
}