#1: Чуть-чуть поделал samba. Осталось совсем немного допилить.

This commit is contained in:
2026-04-15 15:34:20 +05:00
parent 34ddd60a0a
commit 2734c06fb1

View File

@@ -8,6 +8,7 @@ import java.io.InputStreamReader
import kotlin.system.exitProcess import kotlin.system.exitProcess
import java.util.* import java.util.*
import java.util.concurrent.* import java.util.concurrent.*
import kotlin.time.Duration.Companion.milliseconds
// Конфигурация GPIO (BCM номера) // Конфигурация GPIO (BCM номера)
object PinConfig { object PinConfig {
@@ -27,7 +28,7 @@ object DebugMode {
// Состояния системы // Состояния системы
enum class SystemState { enum class SystemState {
IDLE, SCANNING, CLEAN, INFECTED, ERROR, INIT IDLE, SCANNING, CLEAN, INFECTED, ERROR, INIT, SAMBA
} }
class USBVirusScanner { class USBVirusScanner {
@@ -120,45 +121,56 @@ class USBVirusScanner {
greenLed.setValue(1) greenLed.setValue(1)
yellowLed.setValue(1) yellowLed.setValue(1)
redLed.setValue(1) redLed.setValue(1)
delay(200) delay(200.milliseconds)
greenLed.setValue(0) greenLed.setValue(0)
yellowLed.setValue(0) yellowLed.setValue(0)
redLed.setValue(0) redLed.setValue(0)
delay(200) delay(200.milliseconds)
} }
SystemState.IDLE -> { SystemState.IDLE -> {
// Зелёный медленно мигает // Зелёный медленно мигает
blinkLed(greenLed, 1000) blinkLed(greenLed, 1000)
yellowLed.setValue(0) yellowLed.setValue(0)
redLed.setValue(0) redLed.setValue(0)
} }
SystemState.SCANNING -> { SystemState.SCANNING -> {
// Жёлтый быстро мигает // Жёлтый быстро мигает
greenLed.setValue(0) greenLed.setValue(0)
blinkLed(yellowLed, 150) blinkLed(yellowLed, 150)
redLed.setValue(0) redLed.setValue(0)
} }
SystemState.CLEAN -> { SystemState.CLEAN -> {
// Зелёный горит // Зелёный горит
greenLed.setValue(1) greenLed.setValue(1)
yellowLed.setValue(0) yellowLed.setValue(0)
redLed.setValue(0) redLed.setValue(0)
delay(100) delay(100.milliseconds)
} }
SystemState.INFECTED -> { SystemState.INFECTED -> {
// Красный горит // Красный горит
greenLed.setValue(0) greenLed.setValue(0)
yellowLed.setValue(0) yellowLed.setValue(0)
redLed.setValue(1) redLed.setValue(1)
delay(100) delay(100.milliseconds)
} }
SystemState.ERROR -> { SystemState.ERROR -> {
// Красный мигает // Красный мигает
greenLed.setValue(0) greenLed.setValue(0)
yellowLed.setValue(0) yellowLed.setValue(0)
blinkLed(redLed, 500) blinkLed(redLed, 500)
} }
SystemState.SAMBA -> {
blinkLed(greenLed, 1000)
blinkLed(yellowLed, 1000)
redLed.setValue(0)
}
} }
} }
} }
@@ -166,9 +178,9 @@ class USBVirusScanner {
private suspend fun blinkLed(led: GPIOController, intervalMs: Long) { private suspend fun blinkLed(led: GPIOController, intervalMs: Long) {
led.setValue(1) led.setValue(1)
delay(intervalMs / 2) delay((intervalMs / 2).milliseconds)
led.setValue(0) led.setValue(0)
delay(intervalMs / 2) delay((intervalMs / 2).milliseconds)
} }
fun startScan() { fun startScan() {
@@ -188,7 +200,7 @@ class USBVirusScanner {
if (usbDevices.isEmpty()) { if (usbDevices.isEmpty()) {
println(if (isDebug) "Устройства не найдены" else "") println(if (isDebug) "Устройства не найдены" else "")
currentState = SystemState.ERROR currentState = SystemState.ERROR
delay(5000) delay(5000.milliseconds)
currentState = SystemState.IDLE currentState = SystemState.IDLE
return@launch return@launch
} }
@@ -241,14 +253,22 @@ class USBVirusScanner {
println(if (isDebug) message else "") println(if (isDebug) message else "")
// Держим состояние 5 секунд // Держим состояние 5 секунд
delay(5000) delay(10000.milliseconds)
if (!hasVirus) {
currentState = SystemState.SAMBA
sambaStartSharing()
while (isUsbSharing()) {}
}
currentState = SystemState.IDLE currentState = SystemState.IDLE
} catch (e: Exception) { } catch (e: Exception) {
println(if (isDebug) "❌ Критическая ошибка: ${e.message}" else "") println(if (isDebug) "❌ Критическая ошибка: ${e.message}" else "")
e.printStackTrace() e.printStackTrace()
currentState = SystemState.ERROR currentState = SystemState.ERROR
delay(5000) delay(10000.milliseconds)
currentState = SystemState.IDLE currentState = SystemState.IDLE
} }
@@ -295,7 +315,8 @@ class USBVirusScanner {
if ((mountPoint.startsWith("/media")) && if ((mountPoint.startsWith("/media")) &&
File(mountPoint).exists() && File(mountPoint).exists() &&
devices.none { it.mountPoint == mountPoint }) { devices.none { it.mountPoint == mountPoint }
) {
devices.add(USBDevice("auto", mountPoint)) devices.add(USBDevice("auto", mountPoint))
} }
@@ -432,6 +453,62 @@ class USBVirusScanner {
} }
} }
fun isUsbSharing(isActive: Boolean): Boolean {
var defaultState: Boolean = false
defaultState = isActive
return defaultState
}
suspend fun sambaStartSharing() {
try {
currentState = SystemState.SAMBA
var process: Process? = null
val sambaStartServiceCmd = listOf("systemctl", "start", "smbd")
val processBuilder = ProcessBuilder(sambaStartServiceCmd)
.redirectErrorStream(true)
process = withContext(Dispatchers.IO) {
processBuilder.start()
}
} catch (e: Exception) {
e.printStackTrace()
currentState = SystemState.ERROR
delay(10000.milliseconds)
}
}
fun sambaShutdown() {
unmount()
try {
var process: Process? = null
val sambaStopServiceCmd = listOf("systemctl", "stop", "smbd")
val processBuilder = ProcessBuilder(sambaStopServiceCmd)
.redirectErrorStream(true)
process = processBuilder.start()
currentState = SystemState.IDLE
} catch (e: Exception) {}
}
fun unmount() {
for (i in 0..9) {
val path = if (i == 0) "/media/usb" else "/media/usb$i"
try {
val processBuilder = ProcessBuilder("umount", "-f", path)
.redirectErrorStream(true)
val process = processBuilder.start()
val exitCode = process.waitFor()
if (exitCode == 0) {
println(if (isDebug) "Успешно размонтировано: $path" else "")
}
} catch (e: Exception) {
println(if (isDebug) "Ошибка при размонтировании $path: ${e.message}" else "")
}
}
}
fun shutdown() { fun shutdown() {
println(if (isDebug) "\nЗавершение работы..." else "") println(if (isDebug) "\nЗавершение работы..." else "")
isRunning = false isRunning = false
@@ -527,7 +604,6 @@ fun main(args: Array<String>) {
println(if (isDebug) "Красный - ${PinConfig.RED_LED}" else "") println(if (isDebug) "Красный - ${PinConfig.RED_LED}" else "")
println(if (isDebug) "Кнопка - ${PinConfig.BUTTON}" else "") println(if (isDebug) "Кнопка - ${PinConfig.BUTTON}" else "")
val defaultButtonState = false
val scanner = USBVirusScanner() val scanner = USBVirusScanner()
Runtime.getRuntime().addShutdownHook(Thread { Runtime.getRuntime().addShutdownHook(Thread {
@@ -544,12 +620,13 @@ fun main(args: Array<String>) {
} }
buttonListener.addLongPressListener { event -> buttonListener.addLongPressListener { event ->
println("TODO: Сделать отключение samba и отмонтирование накопителя.") scanner.sambaShutdown()
} }
buttonListener.startListening() buttonListener.startListening()
println(if (isDebug) """ println(
if (isDebug) """
═══════════════════════════════════════ ═══════════════════════════════════════
USB Virus Scanner готов к работе USB Virus Scanner готов к работе
═══════════════════════════════════════ ═══════════════════════════════════════
@@ -559,7 +636,8 @@ fun main(args: Array<String>) {
📌 Зелёный LED горит - флешка чиста 📌 Зелёный LED горит - флешка чиста
📌 Красный LED горит - найдены вирусы 📌 Красный LED горит - найдены вирусы
📌 Для выхода нажмите Ctrl+C 📌 Для выхода нажмите Ctrl+C
""".trimIndent() else "") """.trimIndent() else ""
)
while (true) { while (true) {
Thread.sleep(1000) Thread.sleep(1000)