Доделки кода

This commit is contained in:
2026-04-03 13:43:58 +05:00
committed by Thiflict
parent e83a4f15cf
commit e7b9521a8a
3 changed files with 124 additions and 90 deletions

View File

@@ -1,7 +1,7 @@
package ru.thiflict package ru.thiflict
import kotlinx.coroutines.* import kotlinx.coroutines.*
import ru.thiflict.DebugMode.DEBUG import ru.thiflict.DebugMode.isDebug
import ru.thiflict.PinConfig.BUTTON import ru.thiflict.PinConfig.BUTTON
import java.io.BufferedReader import java.io.BufferedReader
import java.io.InputStreamReader import java.io.InputStreamReader
@@ -26,10 +26,6 @@ class ButtonListener(
clickListeners.add(listener) clickListeners.add(listener)
} }
fun removeClickListener(listener: ButtonClickListener) {
clickListeners.remove(listener)
}
private fun notifyClick() { private fun notifyClick() {
val event = ButtonClickEvent() val event = ButtonClickEvent()
clickListeners.forEach { it.invoke(event) } clickListeners.forEach { it.invoke(event) }
@@ -55,25 +51,25 @@ class ButtonListener(
var line: String? var line: String?
while (reader.readLine().also { line = it } != null) { while (reader.readLine().also { line = it } != null) {
println(if (DEBUG) "$line" else "") println(if (isDebug) "$line" else "")
when { when {
line?.contains("rising") == true -> { line?.contains("rising") == true -> {
currentButtonState.set(true) currentButtonState.set(true)
onStateChange?.invoke(true) onStateChange?.invoke(true)
println(if (DEBUG) "Кнопка нажата" else "") println(if (isDebug) "Кнопка нажата" else "")
// Генерируем событие клика при нажатии // Генерируем событие клика при нажатии
notifyClick() notifyClick()
} }
line?.contains("falling") == true -> { line?.contains("falling") == true -> {
currentButtonState.set(false) currentButtonState.set(false)
onStateChange?.invoke(false) onStateChange?.invoke(false)
println(if (DEBUG) "Кнопка разжата" else "") println(if (isDebug) "Кнопка разжата" else "")
// Убрана проверка на разжатие для генерации события // Убрана проверка на разжатие для генерации события
} }
} }
} }
val exitCode = process!!.waitFor() val exitCode = process!!.waitFor()
println("Процесс завершён ($exitCode)") println(if (isDebug) "Процесс завершён ($exitCode)" else "")
isListening.set(false) isListening.set(false)
} }
} catch (e: Exception) { } catch (e: Exception) {
@@ -82,10 +78,4 @@ class ButtonListener(
} }
return currentButtonState.get() return currentButtonState.get()
} }
fun stopListening() {
listenerJob?.cancel()
process?.destroy()
isListening.set(false)
}
} }

View File

@@ -1,16 +1,9 @@
package ru.thiflict package ru.thiflict
import kotlinx.coroutines.delay import ru.thiflict.DebugMode.isDebug
import ru.thiflict.PinConfig
import java.io.File
import kotlin.system.exitProcess
class GPIOController(private val pin: Int) { class GPIOController(private val pin: Int) {
fun setDirection(direction: String) {
// Для libgpiod направление задаётся автоматически
}
fun setValue(value: Int) { fun setValue(value: Int) {
try { try {
// Пробуем разные варианты синтаксиса gpioset // Пробуем разные варианты синтаксиса gpioset
@@ -27,7 +20,7 @@ class GPIOController(private val pin: Int) {
} }
} catch (e: Exception) { } catch (e: Exception) {
println("Ошибка установки GPIO $pin = $value: ${e.message}") println(if (isDebug) "Ошибка установки GPIO $pin = $value: ${e.message}" else "")
} }
} }
@@ -41,7 +34,7 @@ class GPIOController(private val pin: Int) {
process.waitFor() process.waitFor()
output.toIntOrNull() ?: 0 output.toIntOrNull() ?: 0
} catch (e: Exception) { } catch (e: Exception) {
println("Ошибка чтения GPIO $pin: ${e.message}") println(if (isDebug) "Ошибка чтения GPIO $pin: ${e.message}" else "")
0 0
} }
} }
@@ -52,4 +45,3 @@ class GPIOController(private val pin: Int) {
} }

View File

@@ -1,9 +1,13 @@
package ru.thiflict package ru.thiflict
import kotlinx.coroutines.* import kotlinx.coroutines.*
import ru.thiflict.DebugMode.DEBUG import ru.thiflict.DebugMode.isDebug
import java.io.BufferedReader
import java.io.File import java.io.File
import java.io.InputStreamReader
import kotlin.system.exitProcess import kotlin.system.exitProcess
import java.util.*
import java.util.concurrent.*
// Конфигурация GPIO (BCM номера) // Конфигурация GPIO (BCM номера)
object PinConfig { object PinConfig {
@@ -14,7 +18,11 @@ object PinConfig {
} }
object DebugMode { object DebugMode {
const val DEBUG = true var isDebug = false
fun enableDebugging() {
isDebug = true
}
} }
// Состояния системы // Состояния системы
@@ -32,12 +40,11 @@ class USBVirusScanner {
private lateinit var greenLed: GPIOController private lateinit var greenLed: GPIOController
private lateinit var yellowLed: GPIOController private lateinit var yellowLed: GPIOController
private lateinit var redLed: GPIOController private lateinit var redLed: GPIOController
private lateinit var buttonReader: ButtonListener
private val scope = CoroutineScope(Dispatchers.IO + SupervisorJob()) private val scope = CoroutineScope(Dispatchers.IO + SupervisorJob())
fun initialize() { fun initialize() {
println(if (DEBUG) "Инициализация..." else "") println(if (isDebug) "Инициализация..." else "")
try { try {
// Проверяем доступность gpiod // Проверяем доступность gpiod
@@ -54,16 +61,18 @@ class USBVirusScanner {
// Запускаем индикацию состояния // Запускаем индикацию состояния
startStateIndication() startStateIndication()
currentState = SystemState.IDLE
antivirusDatabaseUpdater()
Thread.sleep(1000) Thread.sleep(1000)
println("Инициализация завершена.") println(if (isDebug) "Инициализация завершена." else "")
currentState = SystemState.IDLE currentState = SystemState.IDLE
} catch (e: Exception) { } catch (e: Exception) {
currentState = SystemState.ERROR currentState = SystemState.ERROR
println("❌ Ошибка инициализации: ${e.message}") println(if (isDebug) "❌ Ошибка инициализации: ${e.message}" else "")
e.printStackTrace() e.printStackTrace()
throw e throw e
} }
@@ -75,23 +84,23 @@ class USBVirusScanner {
val exitCode = process.waitFor() val exitCode = process.waitFor()
if (exitCode != 0) { if (exitCode != 0) {
throw Exception("gpiodetect не найден") throw Exception(if (isDebug) "gpiodetect не найден" else "")
} }
val output = process.inputStream.bufferedReader().readText() val output = process.inputStream.bufferedReader().readText()
println("✅ libgpiod найден") println(if (isDebug) "✅ libgpiod найден" else "")
if (output.isNotBlank()) { if (output.isNotBlank()) {
println("Доступные чипы: ${output.trim()}") println(if (isDebug) "Доступные чипы: ${output.trim()}" else "")
} }
} catch (e: Exception) { } catch (e: Exception) {
throw Exception("libgpiod Не установлен!") throw Exception(if (isDebug) "libgpiod Не установлен!" else "")
} }
} }
fun buttonPress(defaultButtonState: Boolean): Boolean { fun buttonPress(defaultButtonState: Boolean): Boolean {
var finalButtonState = defaultButtonState var finalButtonState = defaultButtonState
println(if (DEBUG) "Начало finalButtonState: $finalButtonState" else "") println(if (isDebug) "Начало finalButtonState: $finalButtonState" else "")
val buttonListener = ButtonListener() val buttonListener = ButtonListener()
val initialState = buttonListener.startListening { isPressed -> val initialState = buttonListener.startListening { isPressed ->
@@ -99,7 +108,7 @@ class USBVirusScanner {
finalButtonState = true finalButtonState = true
} }
} }
println(if (DEBUG) "finalButtonState: $finalButtonState" else "") println(if (isDebug) "finalButtonState: $finalButtonState" else "")
return finalButtonState return finalButtonState
} }
@@ -164,27 +173,27 @@ class USBVirusScanner {
fun startScan() { fun startScan() {
if (scanJob?.isActive == true) { if (scanJob?.isActive == true) {
println("Сканирование уже выполняется") println(if (isDebug) "Сканирование уже выполняется" else "")
return return
} }
scanJob = scope.launch { scanJob = scope.launch {
currentState = SystemState.SCANNING currentState = SystemState.SCANNING
println("=== Начало сканирования ===") println(if (isDebug) "=== Начало сканирования ===" else "")
try { try {
// Поиск USB-устройств // Поиск USB-устройств
val usbDevices = findUSBDevices() val usbDevices = findUSBDevices()
if (usbDevices.isEmpty()) { if (usbDevices.isEmpty()) {
println("Устройства не найдены") println(if (isDebug) "Устройства не найдены" else "")
currentState = SystemState.ERROR currentState = SystemState.ERROR
delay(5000) delay(5000)
currentState = SystemState.IDLE currentState = SystemState.IDLE
return@launch return@launch
} }
println("📀 Найдены USB-устройства:") println(if (isDebug) "📀 Найдены USB-устройства:" else "")
usbDevices.forEach { device -> usbDevices.forEach { device ->
println(" - ${device.mountPoint}") println(" - ${device.mountPoint}")
} }
@@ -194,23 +203,23 @@ class USBVirusScanner {
val scanResults = mutableListOf<ScanResult>() val scanResults = mutableListOf<ScanResult>()
for (device in usbDevices) { for (device in usbDevices) {
println("🔍 Сканирование: ${device.mountPoint}") println(if (isDebug) "🔍 Сканирование: ${device.mountPoint}" else "")
val result = scanWithClamAV(device.mountPoint) val result = scanWithClamAV(device.mountPoint)
scanResults.add(result) scanResults.add(result)
if (result.isInfected) { if (result.isInfected) {
hasVirus = true hasVirus = true
println("⚠️ ВНИМАНИЕ! Найдены угрозы!") println(if (isDebug) "⚠️ ВНИМАНИЕ! Найдены угрозы!" else "")
result.infectedFiles.take(10).forEach { file -> result.infectedFiles.take(10).forEach { file ->
println(" 🦠 ${file.take(100)}") println(" 🦠 ${file.take(100)}")
} }
if (result.infectedFiles.size > 10) { if (result.infectedFiles.size > 10) {
println(" ... и ещё ${result.infectedFiles.size - 10} файлов") println(if (isDebug) " ... и ещё ${result.infectedFiles.size - 10} файлов" else "")
} }
} else if (result.error != null) { } else if (result.error != null) {
println("❌ Ошибка сканирования: ${result.error}") println(if (isDebug) "❌ Ошибка сканирования: ${result.error}" else "")
} else { } else {
println("✅ Сканирование завершено: угроз не найдено") println(if (isDebug) "✅ Сканирование завершено: угроз не найдено" else "")
} }
println() println()
} }
@@ -225,25 +234,25 @@ class USBVirusScanner {
} }
val message = if (hasVirus) { val message = if (hasVirus) {
"🦠 Найдены вирусы! Красный LED горит" if (isDebug) "🦠 Найдены вирусы! Красный LED горит" else ""
} else { } else {
"✅ Флешка чиста! Зелёный LED горит" if (isDebug) "✅ Флешка чиста! Зелёный LED горит" else ""
} }
println(message) println(if (isDebug) message else "")
// Держим состояние 5 секунд // Держим состояние 5 секунд
delay(5000) delay(5000)
currentState = SystemState.IDLE currentState = SystemState.IDLE
} catch (e: Exception) { } catch (e: Exception) {
println("❌ Критическая ошибка: ${e.message}") println(if (isDebug) "❌ Критическая ошибка: ${e.message}" else "")
e.printStackTrace() e.printStackTrace()
currentState = SystemState.ERROR currentState = SystemState.ERROR
delay(5000) delay(5000)
currentState = SystemState.IDLE currentState = SystemState.IDLE
} }
println("=== Сканирование завершено ===\n") println(if (isDebug) "=== Сканирование завершено ===\n" else "")
} }
} }
@@ -295,7 +304,7 @@ class USBVirusScanner {
} }
} catch (e: Exception) { } catch (e: Exception) {
println("Ошибка при поиске USB-устройств: ${e.message}") println(if (isDebug) "Ошибка при поиске USB-устройств: ${e.message}" else "")
} }
return devices.distinctBy { it.mountPoint } return devices.distinctBy { it.mountPoint }
@@ -316,7 +325,7 @@ class USBVirusScanner {
infectedFiles = emptyList(), infectedFiles = emptyList(),
virusNames = emptyMap(), virusNames = emptyMap(),
exitCode = -1, exitCode = -1,
error = "ClamAV не установлен. Установите: sudo apt install clamav" error = if (isDebug) "ClamAV не установлен. Установите: sudo apt install clamav" else ""
) )
} }
@@ -328,11 +337,11 @@ class USBVirusScanner {
infectedFiles = emptyList(), infectedFiles = emptyList(),
virusNames = emptyMap(), virusNames = emptyMap(),
exitCode = -1, exitCode = -1,
error = "Путь не существует или не является директорией: $path" error = if (isDebug)"Путь не существует или не является директорией: $path" else ""
) )
} }
println(" Запуск clamscan (это может занять некоторое время)...") println(if (isDebug) " Запуск clamscan (это может занять некоторое время)..." else "")
// Запускаем ClamAV // Запускаем ClamAV
val processBuilder = ProcessBuilder( val processBuilder = ProcessBuilder(
@@ -340,8 +349,8 @@ class USBVirusScanner {
"-r", "-r",
"--stdout", "--stdout",
"--infected", "--infected",
"--max-filesize=70M", "--max-filesize=1M",
"--max-scansize=150M", "--max-scansize=10M",
path path
) )
@@ -364,30 +373,22 @@ class USBVirusScanner {
} }
} }
val syncProccessBuilder = ProcessBuilder("sync")
syncProccessBuilder.start()
process.waitFor()
val umountProcessBulder = ProcessBuilder("umount", "/dev/sda", "-f")
umountProcessBulder.start()
process.waitFor()
return ScanResult( return ScanResult(
isInfected = infectedFiles.isNotEmpty(), isInfected = infectedFiles.isNotEmpty(),
infectedFiles = infectedFiles, infectedFiles = infectedFiles,
virusNames = virusNames, virusNames = virusNames,
exitCode = exitCode, exitCode = exitCode,
error = if (exitCode != 0 && exitCode != 1) "ClamAV вернул код ошибки: $exitCode" else null error = if (isDebug) (if (exitCode != 0 && exitCode != 1) "ClamAV вернул код ошибки: $exitCode" else "") else ""
) )
} catch (e: Exception) { } catch (e: Exception) {
println(" Ошибка при выполнении clamscan: ${e.message}") println(if (isDebug) " Ошибка при выполнении clamscan: ${e.message}" else "")
return ScanResult( return ScanResult(
isInfected = false, isInfected = false,
infectedFiles = emptyList(), infectedFiles = emptyList(),
virusNames = emptyMap(), virusNames = emptyMap(),
exitCode = -1, exitCode = -1,
error = e.message error = if (isDebug) e.message else ""
) )
} }
} }
@@ -427,14 +428,14 @@ class USBVirusScanner {
} }
} }
println("📝 Лог сохранён: ${logFile.absolutePath}") println(if (isDebug) "📝 Лог сохранён: ${logFile.absolutePath}" else "")
} catch (e: Exception) { } catch (e: Exception) {
println("Ошибка сохранения лога: ${e.message}") println(if (isDebug) "Ошибка сохранения лога: ${e.message}" else "")
} }
} }
fun shutdown() { fun shutdown() {
println("\nЗавершение работы...") println(if (isDebug) "\nЗавершение работы..." else "")
isRunning = false isRunning = false
indicationJob?.cancel() indicationJob?.cancel()
@@ -453,7 +454,7 @@ class USBVirusScanner {
// Игнорируем ошибки при закрытии // Игнорируем ошибки при закрытии
} }
println("✅ Система остановлена") println(if (isDebug) "✅ Система остановлена" else "")
} }
} }
@@ -470,14 +471,63 @@ data class ScanResult(
val error: String? = null val error: String? = null
) )
fun scheduleUpdaterAt3AM() {
val scheduler = Executors.newSingleThreadScheduledExecutor()
val now = Calendar.getInstance()
val targetTime = Calendar.getInstance().apply {
set(Calendar.HOUR_OF_DAY, 3)
set(Calendar.MINUTE, 0)
set(Calendar.SECOND, 0)
set(Calendar.MILLISECOND, 0)
}
fun main() { var initialDelay = targetTime.timeInMillis - now.timeInMillis
println(if (DebugMode.DEBUG) "Зелёный - ${PinConfig.GREEN_LED}" else "") // Если время уже прошло сегодня, планируем на завтра
println(if (DebugMode.DEBUG) "Жёлтый - ${PinConfig.YELLOW_LED}" else "") if (initialDelay <= 0) {
println(if (DebugMode.DEBUG) "Красный - ${PinConfig.RED_LED}" else "") targetTime.add(Calendar.DAY_OF_MONTH, 1)
println(if (DebugMode.DEBUG) "Кнопка - ${PinConfig.BUTTON}" else "") initialDelay = targetTime.timeInMillis - now.timeInMillis
}
scheduler.scheduleAtFixedRate(
{ antivirusDatabaseUpdater() },
initialDelay,
TimeUnit.DAYS.toMillis(1),
TimeUnit.MILLISECONDS
)
println("Планировщик запущен. Первый запуск через ${initialDelay / 1000 / 60} минут")
}
fun antivirusDatabaseUpdater() {
println(if (isDebug) "Обновление базы данных антивируса" else "")
val processBuilder = ProcessBuilder("freshclam", "-vvv")
processBuilder.redirectErrorStream(true)
val process = processBuilder.start()
val reader = BufferedReader(InputStreamReader(process.inputStream))
if (isDebug) {
reader.useLines { lines ->
lines.forEach { println("Process output: $it") }
}
}
process.waitFor()
}
fun main(args: Array<String>) {
if (args.contains("--debug")) {
DebugMode.enableDebugging()
}
scheduleUpdaterAt3AM()
println(if (isDebug) "Зелёный - ${PinConfig.GREEN_LED}" else "")
println(if (isDebug) "Жёлтый - ${PinConfig.YELLOW_LED}" else "")
println(if (isDebug) "Красный - ${PinConfig.RED_LED}" else "")
println(if (isDebug) "Кнопка - ${PinConfig.BUTTON}" else "")
val defaultButtonState = false val defaultButtonState = false
val scanner = USBVirusScanner() val scanner = USBVirusScanner()
@@ -495,21 +545,23 @@ fun main() {
} }
buttonListener.startListening() buttonListener.startListening()
println("═══════════════════════════════════════") println(if (isDebug) """
println(" USB Virus Scanner готов к работе") ═══════════════════════════════════════
println("═══════════════════════════════════════") USB Virus Scanner готов к работе
println("📌 Вставьте флешку и нажмите кнопку") ═══════════════════════════════════════
println("📌 Зелёный LED мигает - режим ожидания") 📌 Вставьте флешку и нажмите кнопку
println("📌 Жёлтый LED мигает - идёт проверка") 📌 Зелёный LED мигает - режим ожидания
println("📌 Зелёный LED горит - флешка чиста") 📌 Жёлтый LED мигает - идёт проверка
println("📌 Красный LED горит - найдены вирусы") 📌 Зелёный LED горит - флешка чиста
println("📌 Для выхода нажмите Ctrl+C\n") 📌 Красный LED горит - найдены вирусы
📌 Для выхода нажмите Ctrl+C
""".trimIndent() else "")
while (true) { while (true) {
Thread.sleep(1000) Thread.sleep(1000)
} }
} catch (e: Exception) { } catch (e: Exception) {
println("❌ Критическая ошибка: ${e.message}") println(if (isDebug) "❌ Критическая ошибка: ${e.message}" else "")
e.printStackTrace() e.printStackTrace()
scanner.shutdown() scanner.shutdown()
exitProcess(1) exitProcess(1)