Compare commits
63 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f23d8e35bb | ||
|
|
587d46578e | ||
|
|
7342dddd0b | ||
|
|
e32d6967aa | ||
|
|
99a867df6f | ||
|
|
29734e6203 | ||
|
|
af9bb48f7e | ||
|
|
c8daa276fc | ||
|
|
1bfac034cd | ||
|
|
7b8e897e8a | ||
|
|
c279982778 | ||
|
|
3b2a31e133 | ||
|
|
f5f51bce0c | ||
|
|
fbded33b67 | ||
|
|
6cee5999b8 | ||
|
|
2d85b0587b | ||
|
|
43890117b2 | ||
|
|
e5f964dff7 | ||
|
|
05ba30e0c6 | ||
|
|
e53186ea52 | ||
|
|
b0bf837a92 | ||
|
|
88739f17a9 | ||
|
|
b63ef121f9 | ||
|
|
b45f871544 | ||
|
|
516fb7b932 | ||
|
|
3de296b5d2 | ||
|
|
37ecd0fa6e | ||
|
|
467dabe509 | ||
|
|
0f827f7a9c | ||
|
|
78ac8648a6 | ||
|
|
ac10ffc7fa | ||
|
|
f5cb74ba25 | ||
|
|
4102140fa0 | ||
|
|
985cd9eb1a | ||
|
|
7564c8d092 | ||
|
|
fac3c7d692 | ||
|
|
884678d36d | ||
|
|
9d7b659231 | ||
|
|
ee61d3ef6f | ||
|
|
3109c52bbd | ||
|
|
eeffc14f1a | ||
|
|
9838daea2f | ||
|
|
531ec51fb6 | ||
|
|
e523bf756b | ||
|
|
ef72a2dc7f | ||
|
|
ef4fa24ba5 | ||
|
|
a1b2bdaa1c | ||
|
|
0b51e63262 | ||
|
|
268c9d76af | ||
|
|
11446a92a5 | ||
|
|
b988e7cea0 | ||
|
|
f4996bef8e | ||
|
|
27169e9d0f | ||
|
|
a083660e03 | ||
|
|
3de3d7e893 | ||
|
|
efcec098bd | ||
|
|
d0c055fec9 | ||
|
|
9790f9d69c | ||
|
|
ea36319fe3 | ||
|
|
fc224e3e09 | ||
|
|
583ec62e39 | ||
|
|
bff0d29ee8 | ||
|
|
abb6f254bc |
@@ -11,8 +11,8 @@ android {
|
|||||||
applicationId = "ru.ua1zbe.svxremote"
|
applicationId = "ru.ua1zbe.svxremote"
|
||||||
minSdk = 26
|
minSdk = 26
|
||||||
targetSdk = 34
|
targetSdk = 34
|
||||||
versionCode = 4
|
versionCode = 14
|
||||||
versionName = "1.0.2"
|
versionName = "1.0.12"
|
||||||
}
|
}
|
||||||
|
|
||||||
buildTypes {
|
buildTypes {
|
||||||
@@ -21,6 +21,10 @@ android {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
buildFeatures {
|
||||||
|
buildConfig = true
|
||||||
|
}
|
||||||
|
|
||||||
lint {
|
lint {
|
||||||
checkReleaseBuilds = false
|
checkReleaseBuilds = false
|
||||||
abortOnError = false
|
abortOnError = false
|
||||||
|
|||||||
@@ -25,9 +25,16 @@
|
|||||||
android:exported="false"
|
android:exported="false"
|
||||||
android:label="@string/settings_title" />
|
android:label="@string/settings_title" />
|
||||||
|
|
||||||
|
<activity
|
||||||
|
android:name=".AudioSettingsActivity"
|
||||||
|
android:exported="false"
|
||||||
|
android:label="@string/audio_settings_title"
|
||||||
|
android:screenOrientation="portrait" />
|
||||||
|
|
||||||
<activity
|
<activity
|
||||||
android:name=".SplashActivity"
|
android:name=".SplashActivity"
|
||||||
android:exported="true"
|
android:exported="true"
|
||||||
|
android:launchMode="singleTop"
|
||||||
android:screenOrientation="portrait"
|
android:screenOrientation="portrait"
|
||||||
android:theme="@style/Theme.SvxRemote">
|
android:theme="@style/Theme.SvxRemote">
|
||||||
<intent-filter>
|
<intent-filter>
|
||||||
@@ -39,6 +46,7 @@
|
|||||||
<activity
|
<activity
|
||||||
android:name=".MainActivity"
|
android:name=".MainActivity"
|
||||||
android:exported="false"
|
android:exported="false"
|
||||||
|
android:launchMode="singleTask"
|
||||||
android:screenOrientation="portrait"
|
android:screenOrientation="portrait"
|
||||||
android:configChanges="orientation|screenSize|keyboardHidden" />
|
android:configChanges="orientation|screenSize|keyboardHidden" />
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,95 @@
|
|||||||
|
package ru.ua1zbe.svxremote
|
||||||
|
|
||||||
|
import android.app.Activity
|
||||||
|
import android.os.Bundle
|
||||||
|
import android.widget.ArrayAdapter
|
||||||
|
import android.widget.Button
|
||||||
|
import android.widget.CheckBox
|
||||||
|
import android.widget.SeekBar
|
||||||
|
import android.widget.Spinner
|
||||||
|
import android.widget.TextView
|
||||||
|
import android.widget.Toast
|
||||||
|
import ru.ua1zbe.svxremote.prefs.Prefs
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Скрытые настройки звука (тройной тап по названию программы на главном
|
||||||
|
* экране): усиление микрофона, буфер воспроизведения (джиттер), накопление
|
||||||
|
* перед стартом. Применяются при следующем подключении/передаче.
|
||||||
|
*/
|
||||||
|
class AudioSettingsActivity : Activity() {
|
||||||
|
|
||||||
|
override fun onCreate(savedInstanceState: Bundle?) {
|
||||||
|
super.onCreate(savedInstanceState)
|
||||||
|
setContentView(R.layout.activity_audio_settings)
|
||||||
|
|
||||||
|
val seekMicGain = findViewById<SeekBar>(R.id.seek_mic_gain)
|
||||||
|
val lblMicGain = findViewById<TextView>(R.id.lbl_mic_gain_value)
|
||||||
|
val seekRxBuffer = findViewById<SeekBar>(R.id.seek_rx_buffer)
|
||||||
|
val lblRxBuffer = findViewById<TextView>(R.id.lbl_rx_buffer_value)
|
||||||
|
val seekJitter = findViewById<SeekBar>(R.id.seek_jitter)
|
||||||
|
val lblJitter = findViewById<TextView>(R.id.lbl_jitter_value)
|
||||||
|
val spinBitrate = findViewById<Spinner>(R.id.spin_tx_bitrate)
|
||||||
|
|
||||||
|
// Скорость передачи Opus: Авто + фиксированные 6..32 кбит/с.
|
||||||
|
// SvxLink: Opus 8 кГц, кадр 20 мс; декодер принимает любой битрейт,
|
||||||
|
// поэтому выбор — на стороне клиента. Авто = адаптация под интернет.
|
||||||
|
val bitrates = intArrayOf(0, 6, 8, 10, 12, 16, 20, 24, 32)
|
||||||
|
val bitrateLabels = bitrates.map {
|
||||||
|
if (it == 0) getString(R.string.audio_tx_bitrate_auto)
|
||||||
|
else getString(R.string.audio_tx_bitrate_fmt, it)
|
||||||
|
}
|
||||||
|
spinBitrate.adapter = ArrayAdapter(
|
||||||
|
this, android.R.layout.simple_spinner_item, bitrateLabels
|
||||||
|
).apply {
|
||||||
|
setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
|
||||||
|
}
|
||||||
|
val savedBitrate = Prefs.txBitrateKbps(this)
|
||||||
|
spinBitrate.setSelection(bitrates.indexOfFirst { it == savedBitrate }.coerceAtLeast(0))
|
||||||
|
|
||||||
|
fun updateMicGainLabel() {
|
||||||
|
lblMicGain.text = "${100 + seekMicGain.progress * 10}%"
|
||||||
|
}
|
||||||
|
|
||||||
|
fun updateRxBufferLabel() {
|
||||||
|
lblRxBuffer.text = "${100 + seekRxBuffer.progress * 20} мс"
|
||||||
|
}
|
||||||
|
|
||||||
|
fun updateJitterLabel() {
|
||||||
|
lblJitter.text = "${seekJitter.progress * 20} мс"
|
||||||
|
}
|
||||||
|
|
||||||
|
seekMicGain.progress = ((Prefs.micGain(this) - 1.0f) * 10).toInt().coerceIn(0, 40)
|
||||||
|
seekRxBuffer.progress = ((Prefs.rxBufferMs(this) - 100) / 20).coerceIn(0, 25)
|
||||||
|
seekJitter.progress = (Prefs.rxJitterMs(this) / 20).coerceIn(0, 20)
|
||||||
|
updateMicGainLabel()
|
||||||
|
updateRxBufferLabel()
|
||||||
|
updateJitterLabel()
|
||||||
|
|
||||||
|
val listener = object : SeekBar.OnSeekBarChangeListener {
|
||||||
|
override fun onProgressChanged(seekBar: SeekBar, progress: Int, fromUser: Boolean) {
|
||||||
|
updateMicGainLabel()
|
||||||
|
updateRxBufferLabel()
|
||||||
|
updateJitterLabel()
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onStartTrackingTouch(seekBar: SeekBar) {}
|
||||||
|
override fun onStopTrackingTouch(seekBar: SeekBar) {}
|
||||||
|
}
|
||||||
|
seekMicGain.setOnSeekBarChangeListener(listener)
|
||||||
|
seekRxBuffer.setOnSeekBarChangeListener(listener)
|
||||||
|
seekJitter.setOnSeekBarChangeListener(listener)
|
||||||
|
|
||||||
|
val chkRxStats = findViewById<CheckBox>(R.id.chk_rx_stats)
|
||||||
|
chkRxStats.isChecked = Prefs.rxStatsEnabled(this)
|
||||||
|
|
||||||
|
findViewById<Button>(R.id.btn_audio_save).setOnClickListener {
|
||||||
|
Prefs.setMicGain(this, 1.0f + seekMicGain.progress * 0.1f)
|
||||||
|
Prefs.setRxBufferMs(this, 100 + seekRxBuffer.progress * 20)
|
||||||
|
Prefs.setRxJitterMs(this, seekJitter.progress * 20)
|
||||||
|
Prefs.setTxBitrateKbps(this, bitrates[spinBitrate.selectedItemPosition])
|
||||||
|
Prefs.setRxStatsEnabled(this, chkRxStats.isChecked)
|
||||||
|
Toast.makeText(this, getString(R.string.saved), Toast.LENGTH_SHORT).show()
|
||||||
|
finish()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -8,7 +8,14 @@ import android.content.Context
|
|||||||
import android.content.Intent
|
import android.content.Intent
|
||||||
import android.content.ServiceConnection
|
import android.content.ServiceConnection
|
||||||
import android.content.pm.PackageManager
|
import android.content.pm.PackageManager
|
||||||
|
import android.media.MediaPlayer
|
||||||
import android.net.Uri
|
import android.net.Uri
|
||||||
|
import android.view.ViewGroup
|
||||||
|
import android.widget.ArrayAdapter
|
||||||
|
import android.widget.ListView
|
||||||
|
import android.content.res.ColorStateList
|
||||||
|
import android.graphics.Color
|
||||||
|
import android.graphics.PixelFormat
|
||||||
import android.os.Build
|
import android.os.Build
|
||||||
import android.os.Bundle
|
import android.os.Bundle
|
||||||
import android.os.Handler
|
import android.os.Handler
|
||||||
@@ -16,6 +23,8 @@ import android.os.IBinder
|
|||||||
import android.os.Looper
|
import android.os.Looper
|
||||||
import android.provider.Settings
|
import android.provider.Settings
|
||||||
import android.util.Log
|
import android.util.Log
|
||||||
|
import android.view.Gravity
|
||||||
|
import android.view.MotionEvent
|
||||||
import android.view.View
|
import android.view.View
|
||||||
import android.view.WindowManager
|
import android.view.WindowManager
|
||||||
import android.widget.ImageButton
|
import android.widget.ImageButton
|
||||||
@@ -24,11 +33,14 @@ import android.widget.ProgressBar
|
|||||||
import android.widget.TextView
|
import android.widget.TextView
|
||||||
import android.widget.Toast
|
import android.widget.Toast
|
||||||
import java.io.File
|
import java.io.File
|
||||||
|
import ru.ua1zbe.svxremote.aprs.AprsMeteo
|
||||||
import ru.ua1zbe.svxremote.prefs.ConnectionSettings
|
import ru.ua1zbe.svxremote.prefs.ConnectionSettings
|
||||||
import ru.ua1zbe.svxremote.prefs.Prefs
|
import ru.ua1zbe.svxremote.prefs.Prefs
|
||||||
import ru.ua1zbe.svxremote.proto.MsgParser
|
import ru.ua1zbe.svxremote.proto.MsgParser
|
||||||
import ru.ua1zbe.svxremote.proto.ReflectorClient
|
import ru.ua1zbe.svxremote.proto.ReflectorClient
|
||||||
import ru.ua1zbe.svxremote.ui.PttButton
|
import ru.ua1zbe.svxremote.ui.PttButton
|
||||||
|
import ru.ua1zbe.svxremote.ui.SMeterView
|
||||||
|
import ru.ua1zbe.svxremote.ui.SoundMeterPreviewView
|
||||||
|
|
||||||
private const val REQ_MIC = 1001
|
private const val REQ_MIC = 1001
|
||||||
private const val REQ_NOTIF = 1002
|
private const val REQ_NOTIF = 1002
|
||||||
@@ -37,35 +49,64 @@ class MainActivity : Activity(), SvxService.Listener {
|
|||||||
|
|
||||||
companion object {
|
companion object {
|
||||||
private const val TAG = "SVXRemote"
|
private const val TAG = "SVXRemote"
|
||||||
|
private const val TALK_LOG_MAX = 15
|
||||||
}
|
}
|
||||||
|
|
||||||
private lateinit var statusChip: TextView
|
private lateinit var statusChip: TextView
|
||||||
|
private lateinit var lblAppTitle: TextView
|
||||||
private lateinit var lblSubtitle: TextView
|
private lateinit var lblSubtitle: TextView
|
||||||
private lateinit var lblCallsign: TextView
|
private lateinit var lblCallsign: TextView
|
||||||
private lateinit var lblTg: TextView
|
private lateinit var lblTg: TextView
|
||||||
private lateinit var lblTalkerTitle: TextView
|
|
||||||
private lateinit var lblTalker: TextView
|
private lateinit var lblTalker: TextView
|
||||||
private lateinit var lblPttHint: TextView
|
private lateinit var lblDuplex: TextView
|
||||||
|
private var lastTalkerCs = ""
|
||||||
|
private var lastTalkerTg = -1L
|
||||||
private lateinit var lblTxState: TextView
|
private lateinit var lblTxState: TextView
|
||||||
private lateinit var lblConnectHint: TextView
|
private lateinit var lblConnectHint: TextView
|
||||||
private lateinit var connectZone: View
|
private lateinit var connectZone: View
|
||||||
private lateinit var rxBarFill: View
|
private lateinit var rxMeter: SMeterView
|
||||||
private lateinit var rxDb: TextView
|
private lateinit var micMeter: SMeterView
|
||||||
private lateinit var micBarFill: View
|
private lateinit var lblRxStats: TextView
|
||||||
private lateinit var micDb: TextView
|
|
||||||
private lateinit var pttButton: PttButton
|
private lateinit var pttButton: PttButton
|
||||||
private lateinit var btnSettings: ImageButton
|
private lateinit var btnSettings: ImageButton
|
||||||
|
private lateinit var btnMonitor: ImageButton
|
||||||
|
private lateinit var btnRecord: ImageButton
|
||||||
|
// Список записей: воспроизведение/удаление
|
||||||
|
private var recPlayer: MediaPlayer? = null
|
||||||
|
private var recPlayingPath: String? = null
|
||||||
|
private var recLongPressFired = false
|
||||||
|
private var recListAdapter: ArrayAdapter<File>? = null
|
||||||
|
private val recLongPressTask = Runnable {
|
||||||
|
recLongPressFired = true
|
||||||
|
Log.d(TAG, "recBtn long-press FIRED")
|
||||||
|
openRecordingsList()
|
||||||
|
}
|
||||||
|
|
||||||
private val mainHandler = Handler(Looper.getMainLooper())
|
private val mainHandler = Handler(Looper.getMainLooper())
|
||||||
|
private var titleHoldRunnable: Runnable? = null
|
||||||
|
private var titleResetRunnable: Runnable? = null
|
||||||
|
private var titleTaps = 0
|
||||||
|
|
||||||
|
private data class TalkLogEntry(val time: Long, val callsign: String, val tg: Long)
|
||||||
|
|
||||||
|
private val talkLog = ArrayDeque<TalkLogEntry>()
|
||||||
|
|
||||||
private var connected = false
|
private var connected = false
|
||||||
|
private var monitoring = false
|
||||||
|
private var connectedSettings: ConnectionSettings? = null
|
||||||
private var settings: ConnectionSettings = ConnectionSettings("", 5300, "", "", 11)
|
private var settings: ConnectionSettings = ConnectionSettings("", 5300, "", "", 11)
|
||||||
|
|
||||||
|
// Динамический мониторинг: если на группе нет голоса 15 секунд,
|
||||||
|
// возвращаемся к мониторингу всех групп (базовая группа).
|
||||||
|
private val MONITOR_IDLE_MS = 15_000L
|
||||||
|
private var monitorIdleTask: Runnable? = null
|
||||||
|
|
||||||
private var svc: SvxService? = null
|
private var svc: SvxService? = null
|
||||||
private val svcConn = object : ServiceConnection {
|
private val svcConn = object : ServiceConnection {
|
||||||
override fun onServiceConnected(name: ComponentName, binder: IBinder) {
|
override fun onServiceConnected(name: ComponentName, binder: IBinder) {
|
||||||
svc = (binder as SvxService.LocalBinder).service()
|
svc = (binder as SvxService.LocalBinder).service()
|
||||||
svc?.listener = this@MainActivity
|
svc?.listener = this@MainActivity
|
||||||
|
updateRecordUi(svc?.isRecording() ?: false)
|
||||||
}
|
}
|
||||||
|
|
||||||
override fun onServiceDisconnected(name: ComponentName) {
|
override fun onServiceDisconnected(name: ComponentName) {
|
||||||
@@ -76,66 +117,148 @@ class MainActivity : Activity(), SvxService.Listener {
|
|||||||
private var pendingUpdate: UpdateChecker.UpdateInfo? = null
|
private var pendingUpdate: UpdateChecker.UpdateInfo? = null
|
||||||
private var updateDialog: AlertDialog? = null
|
private var updateDialog: AlertDialog? = null
|
||||||
|
|
||||||
|
// ---------- APRS метеостанции (экспериментально) ----------
|
||||||
|
private var aprsMeteo: AprsMeteo? = null
|
||||||
|
private var lastMeteo: String? = null
|
||||||
|
private var lastAprsCoords = ""
|
||||||
|
|
||||||
|
private fun startAprsMeteo() {
|
||||||
|
aprsMeteo?.stop()
|
||||||
|
aprsMeteo = null
|
||||||
|
// Пустые координаты — центр Санкт-Петербурга
|
||||||
|
val coords = Prefs.aprsCoords(this)
|
||||||
|
.split(',')
|
||||||
|
.mapNotNull { it.trim().toDoubleOrNull() }
|
||||||
|
.take(2)
|
||||||
|
.let { if (it.size == 2) it[0] to it[1] else 59.95 to 30.30 }
|
||||||
|
aprsMeteo = AprsMeteo(coords) { wx ->
|
||||||
|
lastMeteo = wx
|
||||||
|
lblSubtitle.text = wx
|
||||||
|
}.also { it.start() }
|
||||||
|
}
|
||||||
|
|
||||||
override fun onCreate(savedInstanceState: Bundle?) {
|
override fun onCreate(savedInstanceState: Bundle?) {
|
||||||
super.onCreate(savedInstanceState)
|
super.onCreate(savedInstanceState)
|
||||||
|
SplashActivity.mainAlive = true
|
||||||
setContentView(R.layout.activity_main)
|
setContentView(R.layout.activity_main)
|
||||||
window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
|
window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
|
||||||
checkForUpdates()
|
checkForUpdates()
|
||||||
|
|
||||||
statusChip = findViewById(R.id.status_chip)
|
statusChip = findViewById(R.id.status_chip)
|
||||||
|
lblAppTitle = findViewById(R.id.lbl_app_title)
|
||||||
lblSubtitle = findViewById(R.id.lbl_subtitle)
|
lblSubtitle = findViewById(R.id.lbl_subtitle)
|
||||||
lblTalkerTitle = findViewById(R.id.lbl_talker_title)
|
|
||||||
lblTalker = findViewById(R.id.lbl_talker)
|
lblTalker = findViewById(R.id.lbl_talker)
|
||||||
lblPttHint = findViewById(R.id.lbl_ptt_hint)
|
lblDuplex = findViewById(R.id.lbl_duplex)
|
||||||
lblTxState = findViewById(R.id.lbl_tx_state)
|
lblTxState = findViewById(R.id.lbl_tx_state)
|
||||||
lblConnectHint = findViewById(R.id.lbl_connect_hint)
|
lblConnectHint = findViewById(R.id.lbl_connect_hint)
|
||||||
connectZone = findViewById(R.id.connect_zone)
|
connectZone = findViewById(R.id.connect_zone)
|
||||||
lblCallsign = findViewById(R.id.lbl_callsign)
|
lblCallsign = findViewById(R.id.lbl_callsign)
|
||||||
lblTg = findViewById(R.id.lbl_tg)
|
lblTg = findViewById(R.id.lbl_tg)
|
||||||
rxBarFill = findViewById(R.id.rx_bar_fill)
|
rxMeter = findViewById(R.id.rx_meter)
|
||||||
rxDb = findViewById(R.id.rx_db)
|
micMeter = findViewById(R.id.mic_meter)
|
||||||
micBarFill = findViewById(R.id.mic_bar_fill)
|
micMeter.setColor(0xFFF85149.toInt())
|
||||||
micDb = findViewById(R.id.mic_db)
|
lblRxStats = findViewById(R.id.lbl_rx_stats)
|
||||||
|
lblRxStats.visibility = if (Prefs.rxStatsEnabled(this)) View.VISIBLE else View.GONE
|
||||||
pttButton = findViewById(R.id.ptt_button)
|
pttButton = findViewById(R.id.ptt_button)
|
||||||
btnSettings = findViewById(R.id.btn_settings)
|
btnSettings = findViewById(R.id.btn_settings)
|
||||||
|
btnMonitor = findViewById(R.id.btn_monitor)
|
||||||
|
btnRecord = findViewById(R.id.btn_record)
|
||||||
pttButton.enabled2 = false
|
pttButton.enabled2 = false
|
||||||
|
|
||||||
|
btnMonitor.setOnClickListener { toggleMonitoring() }
|
||||||
|
btnRecord.setOnClickListener { toggleRecording() }
|
||||||
|
btnRecord.setOnTouchListener { _, event ->
|
||||||
|
when (event.action) {
|
||||||
|
MotionEvent.ACTION_DOWN -> {
|
||||||
|
recLongPressFired = false
|
||||||
|
Log.d(TAG, "recBtn DOWN, scheduling long-press")
|
||||||
|
mainHandler.postDelayed(recLongPressTask, 3000)
|
||||||
|
false
|
||||||
|
}
|
||||||
|
MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> {
|
||||||
|
Log.d(TAG, "recBtn UP/CANCEL, longFired=$recLongPressFired")
|
||||||
|
mainHandler.removeCallbacks(recLongPressTask)
|
||||||
|
// Если сработал долгий тап — гасим клик (иначе переключит запись)
|
||||||
|
recLongPressFired
|
||||||
|
}
|
||||||
|
else -> false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
updateMonitorButton()
|
||||||
|
val testText = intent?.getStringExtra("node_toast_test")
|
||||||
|
if (testText != null) {
|
||||||
|
mainHandler.postDelayed({ showNodeOverlay(testText) }, 1500)
|
||||||
|
}
|
||||||
|
|
||||||
btnSettings.setOnClickListener {
|
btnSettings.setOnClickListener {
|
||||||
startActivity(Intent(this, SettingsActivity::class.java))
|
startActivity(Intent(this, SettingsActivity::class.java))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
findViewById<ImageButton>(R.id.btn_power).setOnClickListener {
|
||||||
|
svc?.disconnect()
|
||||||
|
stopService(Intent(this, SvxService::class.java))
|
||||||
|
SplashActivity.mainAlive = false
|
||||||
|
finishAffinity()
|
||||||
|
}
|
||||||
|
|
||||||
|
lblTg.setOnClickListener { showGroupsDialog() }
|
||||||
|
|
||||||
|
lblCallsign.setOnClickListener { showNodesDialog() }
|
||||||
|
|
||||||
|
lblTalker.setOnClickListener { showTalkLogDialog() }
|
||||||
|
|
||||||
|
// Удержание на надписи «На связи» — демо-окно индикаторов звука
|
||||||
|
lblTxState.setOnLongClickListener {
|
||||||
|
showSoundMetersPreview()
|
||||||
|
true
|
||||||
|
}
|
||||||
|
|
||||||
|
// Удержание на названии программы (> 2 с) — выбор профиля настроек;
|
||||||
|
// короткие тапы считаем: тройной тап — настройки
|
||||||
|
lblAppTitle.setOnTouchListener { _, event ->
|
||||||
|
when (event.actionMasked) {
|
||||||
|
MotionEvent.ACTION_DOWN -> {
|
||||||
|
val r = Runnable {
|
||||||
|
titleHoldRunnable = null
|
||||||
|
showProfileDialog()
|
||||||
|
}
|
||||||
|
titleHoldRunnable = r
|
||||||
|
mainHandler.postDelayed(r, 2000)
|
||||||
|
true
|
||||||
|
}
|
||||||
|
MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> {
|
||||||
|
val wasHold = titleHoldRunnable == null
|
||||||
|
titleHoldRunnable?.let { mainHandler.removeCallbacks(it) }
|
||||||
|
titleHoldRunnable = null
|
||||||
|
if (!wasHold) {
|
||||||
|
titleTaps++
|
||||||
|
// Скользящее окно: сброс от последнего тапа
|
||||||
|
titleResetRunnable?.let { mainHandler.removeCallbacks(it) }
|
||||||
|
val reset = Runnable { titleTaps = 0 }
|
||||||
|
titleResetRunnable = reset
|
||||||
|
mainHandler.postDelayed(reset, 2000)
|
||||||
|
if (titleTaps >= 3) {
|
||||||
|
titleTaps = 0
|
||||||
|
titleResetRunnable?.let { mainHandler.removeCallbacks(it) }
|
||||||
|
startActivity(Intent(this, AudioSettingsActivity::class.java))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
true
|
||||||
|
}
|
||||||
|
else -> true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
connectZone.setOnClickListener {
|
connectZone.setOnClickListener {
|
||||||
val s = svc
|
if (connected) {
|
||||||
if (connected && s != null) {
|
svc?.disconnect()
|
||||||
s.disconnect()
|
|
||||||
} else {
|
} else {
|
||||||
settings = Prefs.load(this)
|
|
||||||
if (settings.host.isBlank() || settings.callsign.isBlank()) {
|
if (settings.host.isBlank() || settings.callsign.isBlank()) {
|
||||||
toast(getString(R.string.toast_need_settings))
|
toast(getString(R.string.toast_need_settings))
|
||||||
return@setOnClickListener
|
return@setOnClickListener
|
||||||
}
|
}
|
||||||
if (checkSelfPermission(Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {
|
requestPermissionsIfNeeded()
|
||||||
requestPermissions(arrayOf(Manifest.permission.RECORD_AUDIO), REQ_MIC)
|
connect()
|
||||||
return@setOnClickListener
|
|
||||||
}
|
|
||||||
if (Build.VERSION.SDK_INT >= 33 &&
|
|
||||||
checkSelfPermission(Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED
|
|
||||||
) {
|
|
||||||
requestPermissions(arrayOf(Manifest.permission.POST_NOTIFICATIONS), REQ_NOTIF)
|
|
||||||
}
|
|
||||||
startForegroundService(Intent(this, SvxService::class.java))
|
|
||||||
bindService(Intent(this, SvxService::class.java), svcConn, Context.BIND_AUTO_CREATE)
|
|
||||||
mainHandler.postDelayed({
|
|
||||||
svc?.connect(
|
|
||||||
ReflectorClient.Settings(
|
|
||||||
host = settings.host,
|
|
||||||
port = settings.port,
|
|
||||||
callsign = settings.callsign,
|
|
||||||
authKey = settings.authKey,
|
|
||||||
talkGroup = settings.talkGroup
|
|
||||||
)
|
|
||||||
)
|
|
||||||
}, 300)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -149,38 +272,80 @@ class MainActivity : Activity(), SvxService.Listener {
|
|||||||
toast(getString(R.string.perm_mic))
|
toast(getString(R.string.perm_mic))
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
lblPttHint.text = getString(R.string.ptt_talking)
|
|
||||||
lblTxState.text = getString(R.string.status_big_talking)
|
lblTxState.text = getString(R.string.status_big_talking)
|
||||||
|
showDuplex(getString(R.string.duplex_tx), R.color.danger, null)
|
||||||
svc?.startTx()
|
svc?.startTx()
|
||||||
}
|
}
|
||||||
|
|
||||||
override fun onPttUp() {
|
override fun onPttUp() {
|
||||||
|
Log.d("SVXRemote", "PTT up")
|
||||||
svc?.stopTx()
|
svc?.stopTx()
|
||||||
lblPttHint.text = getString(R.string.hold_to_talk)
|
|
||||||
lblTxState.text =
|
lblTxState.text =
|
||||||
if (connected) getString(R.string.status_big_connected)
|
if (connected) getString(R.string.status_big_connected)
|
||||||
else getString(R.string.status_big_disconnected)
|
else getString(R.string.status_big_disconnected)
|
||||||
|
hideDuplex()
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
refreshUi()
|
refreshUi()
|
||||||
|
startAprsMeteo()
|
||||||
|
lastAprsCoords = Prefs.aprsCoords(this).trim()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private var autoConnectAttempted = false
|
||||||
|
|
||||||
override fun onResume() {
|
override fun onResume() {
|
||||||
super.onResume()
|
super.onResume()
|
||||||
|
val prev = settings
|
||||||
settings = Prefs.load(this)
|
settings = Prefs.load(this)
|
||||||
|
if (prev != settings && connectedSettings != null) {
|
||||||
|
if (settings.host.isBlank() || settings.callsign.isBlank()) {
|
||||||
|
monitoring = false
|
||||||
|
updateMonitorButton()
|
||||||
|
updatePttEnabled()
|
||||||
|
svc?.disconnect()
|
||||||
|
} else if (connected) {
|
||||||
|
svc?.disconnect()
|
||||||
|
mainHandler.postDelayed({ connect() }, 500)
|
||||||
|
} else {
|
||||||
|
connect()
|
||||||
|
}
|
||||||
|
}
|
||||||
refreshUi()
|
refreshUi()
|
||||||
|
val aprsCoords = Prefs.aprsCoords(this).trim()
|
||||||
|
if (aprsCoords != lastAprsCoords) {
|
||||||
|
lastAprsCoords = aprsCoords
|
||||||
|
startAprsMeteo()
|
||||||
|
}
|
||||||
|
if (!autoConnectAttempted &&
|
||||||
|
settings.host.isNotBlank() &&
|
||||||
|
settings.callsign.isNotBlank()
|
||||||
|
) {
|
||||||
|
autoConnectAttempted = true
|
||||||
|
requestPermissionsIfNeeded()
|
||||||
|
connect()
|
||||||
|
}
|
||||||
|
if (pendingUpdate != null && updateDialog == null && canInstall()) {
|
||||||
|
startUpdate()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
override fun onDestroy() {
|
override fun onDestroy() {
|
||||||
super.onDestroy()
|
super.onDestroy()
|
||||||
|
hideNodeOverlay()
|
||||||
|
aprsMeteo?.stop()
|
||||||
|
aprsMeteo = null
|
||||||
|
mainHandler.removeCallbacks(recLongPressTask)
|
||||||
|
stopRecordingPlayback()
|
||||||
|
mainHandler.removeCallbacksAndMessages(null)
|
||||||
|
SplashActivity.mainAlive = false
|
||||||
svc?.listener = null
|
svc?.listener = null
|
||||||
unbindService(svcConn)
|
unbindService(svcConn)
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun refreshUi() {
|
private fun refreshUi() {
|
||||||
val host = settings.host
|
val host = settings.host
|
||||||
lblSubtitle.text = if (host.isBlank()) {
|
lblSubtitle.text = lastMeteo ?: if (host.isBlank()) {
|
||||||
getString(R.string.settings_not_configured)
|
getString(R.string.settings_not_configured)
|
||||||
} else {
|
} else {
|
||||||
getString(R.string.server_subtitle, host, settings.port, settings.talkGroup)
|
getString(R.string.server_subtitle, host, settings.port, settings.talkGroup)
|
||||||
@@ -207,7 +372,6 @@ class MainActivity : Activity(), SvxService.Listener {
|
|||||||
lblTxState.text = getString(R.string.status_big_disconnected)
|
lblTxState.text = getString(R.string.status_big_disconnected)
|
||||||
lblTxState.setTextColor(getColor(R.color.danger))
|
lblTxState.setTextColor(getColor(R.color.danger))
|
||||||
lblConnectHint.text = getString(R.string.hint_connect)
|
lblConnectHint.text = getString(R.string.hint_connect)
|
||||||
lblPttHint.text = getString(R.string.hold_to_talk)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
ReflectorClient.STATE_CONNECTING,
|
ReflectorClient.STATE_CONNECTING,
|
||||||
@@ -226,7 +390,11 @@ class MainActivity : Activity(), SvxService.Listener {
|
|||||||
ReflectorClient.STATE_READY -> {
|
ReflectorClient.STATE_READY -> {
|
||||||
connected = true
|
connected = true
|
||||||
updatePttEnabled()
|
updatePttEnabled()
|
||||||
statusChip.text = getString(R.string.status_connected)
|
statusChip.text = if (monitoring) {
|
||||||
|
getString(R.string.status_monitoring, monitorTgLabel())
|
||||||
|
} else {
|
||||||
|
getString(R.string.status_connected)
|
||||||
|
}
|
||||||
statusChip.setTextColor(getColor(R.color.accent))
|
statusChip.setTextColor(getColor(R.color.accent))
|
||||||
lblTxState.text = getString(R.string.status_big_connected)
|
lblTxState.text = getString(R.string.status_big_connected)
|
||||||
lblTxState.setTextColor(getColor(R.color.accent))
|
lblTxState.setTextColor(getColor(R.color.accent))
|
||||||
@@ -267,13 +435,91 @@ class MainActivity : Activity(), SvxService.Listener {
|
|||||||
|
|
||||||
override fun onTalkerStart(tg: Long, callsign: String) {
|
override fun onTalkerStart(tg: Long, callsign: String) {
|
||||||
mainHandler.post {
|
mainHandler.post {
|
||||||
lblTalkerTitle.text = getString(R.string.talker_now, callsign)
|
Log.d("SVXRemote", "talkerStart tg=$tg cs=$callsign monitoring=$monitoring ptt=${pttButton.isPressed2}")
|
||||||
lblTalker.text = callsign
|
talkLog.addLast(TalkLogEntry(System.currentTimeMillis(), callsign, tg))
|
||||||
|
while (talkLog.size > TALK_LOG_MAX) {
|
||||||
|
talkLog.removeFirst()
|
||||||
|
}
|
||||||
|
if (monitoring) {
|
||||||
|
// Переключаемся на группу, где началась передача, и даём ей
|
||||||
|
// 15 секунд; после тишины вернёмся ко всем группам.
|
||||||
|
// Во время своей передачи группу не меняем.
|
||||||
|
if (!pttButton.isPressed2) {
|
||||||
|
svc?.selectGroup(tg)
|
||||||
|
}
|
||||||
|
resetMonitorIdle()
|
||||||
|
}
|
||||||
|
lastTalkerCs = callsign
|
||||||
|
lastTalkerTg = tg
|
||||||
|
updateTalkerLine(active = true)
|
||||||
|
if (!pttButton.isPressed2) {
|
||||||
|
showDuplex(getString(R.string.duplex_rx), R.color.accent, DUPLEX_RX_HIDE_MS)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
override fun onTalkerStop(tg: Long, callsign: String) {
|
override fun onTalkerStop(tg: Long, callsign: String) {
|
||||||
// последний говоривший остаётся на экране
|
// последний говоривший остаётся на экране, но без префикса «Говорит»
|
||||||
|
mainHandler.post { updateTalkerLine(active = false) }
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Единая строка говорящего: «Говорит …» при приёме, иначе позывной+TG. */
|
||||||
|
private fun updateTalkerLine(active: Boolean) {
|
||||||
|
if (lastTalkerCs.isEmpty()) {
|
||||||
|
lblTalker.text = ""
|
||||||
|
return
|
||||||
|
}
|
||||||
|
lblTalker.text = if (active)
|
||||||
|
getString(R.string.talker_active_fmt, lastTalkerCs, lastTalkerTg)
|
||||||
|
else
|
||||||
|
getString(R.string.talker_idle_fmt, lastTalkerCs, lastTalkerTg)
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onNodeJoined(callsign: String, tg: Long?) {
|
||||||
|
showNodeToast(R.string.toast_node_joined, callsign, tg)
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onNodeLeft(callsign: String, tg: Long?) {
|
||||||
|
showNodeToast(R.string.toast_node_left, callsign, tg)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun showNodeToast(tpl: Int, callsign: String, tg: Long?) {
|
||||||
|
if (!Prefs.nodeToastsEnabled(this)) return
|
||||||
|
if (callsign.equals(settings.callsign, ignoreCase = true)) return
|
||||||
|
val suffix = if (tg != null) getString(R.string.node_tg_suffix, tg) else ""
|
||||||
|
mainHandler.post { showNodeOverlay(getString(tpl, callsign, suffix)) }
|
||||||
|
}
|
||||||
|
|
||||||
|
private var nodeOverlay: View? = null
|
||||||
|
|
||||||
|
private fun showNodeOverlay(text: String) {
|
||||||
|
hideNodeOverlay()
|
||||||
|
val view = layoutInflater.inflate(R.layout.view_node_toast, null, false)
|
||||||
|
view.findViewById<TextView>(R.id.lbl_node_toast).text = text
|
||||||
|
try {
|
||||||
|
windowManager.addView(
|
||||||
|
view,
|
||||||
|
WindowManager.LayoutParams(
|
||||||
|
WindowManager.LayoutParams.WRAP_CONTENT,
|
||||||
|
WindowManager.LayoutParams.WRAP_CONTENT,
|
||||||
|
WindowManager.LayoutParams.TYPE_APPLICATION,
|
||||||
|
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE or
|
||||||
|
WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE,
|
||||||
|
PixelFormat.TRANSLUCENT
|
||||||
|
).apply { gravity = Gravity.CENTER }
|
||||||
|
)
|
||||||
|
nodeOverlay = view
|
||||||
|
mainHandler.postDelayed({ hideNodeOverlay() }, 5000)
|
||||||
|
} catch (_: Exception) {
|
||||||
|
toast(text)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun hideNodeOverlay() {
|
||||||
|
nodeOverlay?.let { v ->
|
||||||
|
try { windowManager.removeView(v) } catch (_: Exception) { }
|
||||||
|
nodeOverlay = null
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
override fun onAudioPacket(packet: ByteArray, seq: Int) {
|
override fun onAudioPacket(packet: ByteArray, seq: Int) {
|
||||||
@@ -284,21 +530,63 @@ class MainActivity : Activity(), SvxService.Listener {
|
|||||||
|
|
||||||
override fun onLevel(source: Int, level: Float) {
|
override fun onLevel(source: Int, level: Float) {
|
||||||
mainHandler.post {
|
mainHandler.post {
|
||||||
val db = if (level <= 0.001f) {
|
|
||||||
getString(R.string.meter_idle)
|
|
||||||
} else {
|
|
||||||
getString(R.string.meter_db, (level * 60).toInt().coerceIn(1, 60))
|
|
||||||
}
|
|
||||||
if (source == 0) { // SRC_MIC
|
if (source == 0) { // SRC_MIC
|
||||||
micBarFill.scaleX = level.coerceIn(0f, 1f)
|
micMeter.setLevel(level)
|
||||||
micDb.text = db
|
|
||||||
} else { // SRC_SPEAKER
|
} else { // SRC_SPEAKER
|
||||||
rxBarFill.scaleX = level.coerceIn(0f, 1f)
|
rxMeter.setLevel(level)
|
||||||
rxDb.text = db
|
// «RX» пока идёт голос; при своей передаче не показываем
|
||||||
|
if (!pttButton.isPressed2 && level > 0.03f) {
|
||||||
|
showDuplex(getString(R.string.duplex_rx), R.color.accent, DUPLEX_RX_HIDE_MS)
|
||||||
|
}
|
||||||
|
// Голос на текущей группе — откладываем возврат ко всем группам
|
||||||
|
if (monitoring && connected && level > 0.03f) {
|
||||||
|
resetMonitorIdle()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
override fun onRxStats(lossPct: Double, jitterMs: Double) {
|
||||||
|
mainHandler.post {
|
||||||
|
if (!Prefs.rxStatsEnabled(this)) return@post
|
||||||
|
lblRxStats.visibility = View.VISIBLE
|
||||||
|
lblRxStats.text = getString(R.string.rx_stats_fmt, lossPct, jitterMs.toInt())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Сбросить таймер молчания: группа жива — продолжаем её слушать. */
|
||||||
|
private fun resetMonitorIdle() {
|
||||||
|
monitorIdleTask?.let { mainHandler.removeCallbacks(it) }
|
||||||
|
val task = Runnable {
|
||||||
|
// Во время своей передачи на базу не возвращаемся
|
||||||
|
if (monitoring && connected && !pttButton.isPressed2) {
|
||||||
|
svc?.selectGroup(settings.talkGroup)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
monitorIdleTask = task
|
||||||
|
mainHandler.postDelayed(task, MONITOR_IDLE_MS)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- Индикатор RX/TX ----------
|
||||||
|
private val DUPLEX_RX_HIDE_MS = 1500L
|
||||||
|
private var duplexHideTask: Runnable? = null
|
||||||
|
|
||||||
|
private fun showDuplex(text: String, colorRes: Int, hideAfterMs: Long?) {
|
||||||
|
lblDuplex.text = text
|
||||||
|
lblDuplex.setTextColor(getColor(colorRes))
|
||||||
|
lblDuplex.visibility = View.VISIBLE
|
||||||
|
duplexHideTask?.let { mainHandler.removeCallbacks(it) }
|
||||||
|
if (hideAfterMs != null) {
|
||||||
|
val t = Runnable { lblDuplex.visibility = View.INVISIBLE }
|
||||||
|
duplexHideTask = t
|
||||||
|
mainHandler.postDelayed(t, hideAfterMs)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun hideDuplex() {
|
||||||
|
duplexHideTask?.let { mainHandler.removeCallbacks(it) }
|
||||||
|
lblDuplex.visibility = View.INVISIBLE
|
||||||
|
}
|
||||||
override fun onError(detail: String) {
|
override fun onError(detail: String) {
|
||||||
mainHandler.post {
|
mainHandler.post {
|
||||||
toast(detail)
|
toast(detail)
|
||||||
@@ -306,9 +594,329 @@ class MainActivity : Activity(), SvxService.Listener {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private fun updatePttEnabled() {
|
private fun updatePttEnabled() {
|
||||||
|
// PTT работает и в режиме мониторинга: передача идёт на выбранной группе
|
||||||
pttButton.enabled2 = connected
|
pttButton.enabled2 = connected
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private fun requestPermissionsIfNeeded() {
|
||||||
|
if (checkSelfPermission(Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {
|
||||||
|
requestPermissions(arrayOf(Manifest.permission.RECORD_AUDIO), REQ_MIC)
|
||||||
|
}
|
||||||
|
if (Build.VERSION.SDK_INT >= 33 &&
|
||||||
|
checkSelfPermission(Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED
|
||||||
|
) {
|
||||||
|
requestPermissions(arrayOf(Manifest.permission.POST_NOTIFICATIONS), REQ_NOTIF)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Запустить сервис и подключиться с текущими настройками. */
|
||||||
|
private fun connect() {
|
||||||
|
connectedSettings = settings
|
||||||
|
startForegroundService(Intent(this, SvxService::class.java))
|
||||||
|
bindService(Intent(this, SvxService::class.java), svcConn, Context.BIND_AUTO_CREATE)
|
||||||
|
mainHandler.postDelayed({
|
||||||
|
svc?.connect(
|
||||||
|
ReflectorClient.Settings(
|
||||||
|
host = settings.host,
|
||||||
|
port = settings.port,
|
||||||
|
callsign = settings.callsign,
|
||||||
|
authKey = settings.authKey,
|
||||||
|
talkGroup = settings.talkGroup,
|
||||||
|
monitorTgs = if (monitoring) settings.groups else null
|
||||||
|
)
|
||||||
|
)
|
||||||
|
}, 300)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Включить/выключить режим мониторинга групп по живому соединению. */
|
||||||
|
private fun toggleMonitoring() {
|
||||||
|
val enabling = !monitoring
|
||||||
|
if (enabling) {
|
||||||
|
showToast(R.string.monitoring_dev_warning, 10000)
|
||||||
|
} else {
|
||||||
|
showToast(R.string.monitor_off)
|
||||||
|
}
|
||||||
|
monitoring = enabling
|
||||||
|
updateMonitorButton()
|
||||||
|
updatePttEnabled()
|
||||||
|
if (connected) {
|
||||||
|
monitorIdleTask?.let { mainHandler.removeCallbacks(it) }
|
||||||
|
if (enabling) {
|
||||||
|
// Без переподключения: сервер начнёт присылать уведомления
|
||||||
|
// со всех групп, сами сидим на базовой.
|
||||||
|
svc?.setMonitorTgs(settings.groups)
|
||||||
|
svc?.selectGroup(settings.talkGroup)
|
||||||
|
statusChip.text = getString(R.string.status_monitoring, monitorTgLabel())
|
||||||
|
} else {
|
||||||
|
svc?.selectGroup(settings.talkGroup)
|
||||||
|
svc?.setMonitorTgs(listOf(settings.talkGroup))
|
||||||
|
statusChip.text = getString(R.string.status_connected)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
connect()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Окно с сообщением на заданное время (мс). */
|
||||||
|
private fun showToast(resId: Int, durationMs: Int = Toast.LENGTH_SHORT) {
|
||||||
|
val toast = Toast.makeText(this, resId, Toast.LENGTH_SHORT)
|
||||||
|
toast.show()
|
||||||
|
if (durationMs > Toast.LENGTH_SHORT) {
|
||||||
|
mainHandler.postDelayed({ toast.cancel() }, durationMs.toLong())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Список профилей: выбор сразу подключается с новыми настройками. */
|
||||||
|
private fun showProfileDialog() {
|
||||||
|
val profiles = Prefs.loadProfiles(this)
|
||||||
|
val active = Prefs.activeProfileIndex(this)
|
||||||
|
val items = profiles.mapIndexed { i, p ->
|
||||||
|
val s = p.settings
|
||||||
|
val detail = if (s.callsign.isBlank()) {
|
||||||
|
getString(R.string.profile_empty)
|
||||||
|
} else {
|
||||||
|
"${s.callsign} @ ${s.host}:${s.port}"
|
||||||
|
}
|
||||||
|
val marker = if (i == active) getString(R.string.profile_current) else ""
|
||||||
|
"${p.name} — $detail$marker"
|
||||||
|
}.toTypedArray()
|
||||||
|
AlertDialog.Builder(this)
|
||||||
|
.setTitle(getString(R.string.profiles_title))
|
||||||
|
.setItems(items) { _, which ->
|
||||||
|
if (which != active) {
|
||||||
|
Prefs.setActiveProfile(this, which)
|
||||||
|
settings = Prefs.load(this)
|
||||||
|
monitoring = false
|
||||||
|
updateMonitorButton()
|
||||||
|
updatePttEnabled()
|
||||||
|
refreshUi()
|
||||||
|
if (settings.host.isBlank() || settings.callsign.isBlank()) {
|
||||||
|
toast(getString(R.string.toast_need_settings))
|
||||||
|
} else if (connected) {
|
||||||
|
svc?.disconnect()
|
||||||
|
mainHandler.postDelayed({ connect() }, 500)
|
||||||
|
} else {
|
||||||
|
connect()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
.setNegativeButton(getString(R.string.cancel), null)
|
||||||
|
.show()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun updateMonitorButton() {
|
||||||
|
val active = monitoring
|
||||||
|
btnMonitor.imageTintList = ColorStateList.valueOf(
|
||||||
|
if (active) Color.parseColor("#58A6FF") else Color.parseColor("#8B949E")
|
||||||
|
)
|
||||||
|
btnMonitor.setBackgroundResource(if (active) R.drawable.bg_monitor_on else 0)
|
||||||
|
btnMonitor.contentDescription =
|
||||||
|
getString(if (active) R.string.btn_monitor_on else R.string.btn_monitor)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun toggleRecording() {
|
||||||
|
val s = svc ?: return
|
||||||
|
if (s.isRecording()) {
|
||||||
|
val path = s.stopRecording()
|
||||||
|
updateRecordUi(false)
|
||||||
|
toast(getString(R.string.record_saved, path ?: ""))
|
||||||
|
} else {
|
||||||
|
val path = s.startRecording()
|
||||||
|
if (path != null) {
|
||||||
|
updateRecordUi(true)
|
||||||
|
toast(getString(R.string.record_started))
|
||||||
|
} else {
|
||||||
|
toast(getString(R.string.record_failed))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun updateRecordUi(active: Boolean) {
|
||||||
|
btnRecord.imageTintList = ColorStateList.valueOf(
|
||||||
|
if (active) Color.parseColor("#F85149") else Color.parseColor("#8B949E")
|
||||||
|
)
|
||||||
|
btnRecord.contentDescription = getString(R.string.btn_record)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- Список записей: воспроизведение / удаление ----------
|
||||||
|
|
||||||
|
private fun recordingsDir(): File =
|
||||||
|
File(getExternalFilesDir(null) ?: filesDir, "recordings")
|
||||||
|
|
||||||
|
private fun openRecordingsList() {
|
||||||
|
Log.d(TAG, "openRecordingsList")
|
||||||
|
val dir = recordingsDir()
|
||||||
|
Log.d(TAG, "recordings dir exists=${dir.exists()} path=${dir.absolutePath}")
|
||||||
|
val files = (dir.listFiles { f -> f.extension.equals("ogg", true) }
|
||||||
|
?: emptyArray()).toMutableList()
|
||||||
|
.apply { sortByDescending { it.name } }
|
||||||
|
Log.d(TAG, "recordings count=${files.size}")
|
||||||
|
if (files.isEmpty()) {
|
||||||
|
toast("Нет записей")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
val dialog = AlertDialog.Builder(this)
|
||||||
|
.setTitle(R.string.recordings_title)
|
||||||
|
.create()
|
||||||
|
val listView = ListView(this).apply {
|
||||||
|
val adapter = object : ArrayAdapter<File>(this@MainActivity, 0, files) {
|
||||||
|
override fun getView(pos: Int, convertView: View?, parent: ViewGroup): View {
|
||||||
|
val file = getItem(pos)!!
|
||||||
|
val row = convertView
|
||||||
|
?: layoutInflater.inflate(R.layout.dialog_recording_item, parent, false)
|
||||||
|
row.findViewById<TextView>(R.id.rec_name).text = file.name
|
||||||
|
val playBtn = row.findViewById<ImageButton>(R.id.rec_play)
|
||||||
|
val delBtn = row.findViewById<ImageButton>(R.id.rec_delete)
|
||||||
|
val playing = recPlayingPath == file.absolutePath && recPlayer?.isPlaying == true
|
||||||
|
playBtn.setImageResource(if (playing) R.drawable.ic_stop else R.drawable.ic_play)
|
||||||
|
playBtn.setOnClickListener { togglePlayRecording(file.absolutePath) }
|
||||||
|
delBtn.setOnClickListener { confirmDeleteRecording(file, this, dialog) }
|
||||||
|
return row
|
||||||
|
}
|
||||||
|
}
|
||||||
|
recListAdapter = adapter
|
||||||
|
this.adapter = adapter
|
||||||
|
layoutParams = ViewGroup.LayoutParams(
|
||||||
|
ViewGroup.LayoutParams.MATCH_PARENT,
|
||||||
|
(resources.displayMetrics.heightPixels * 0.6).toInt()
|
||||||
|
)
|
||||||
|
}
|
||||||
|
dialog.setView(listView)
|
||||||
|
dialog.setOnDismissListener { stopRecordingPlayback() }
|
||||||
|
dialog.show()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun togglePlayRecording(path: String) {
|
||||||
|
if (recPlayingPath == path && recPlayer?.isPlaying == true) {
|
||||||
|
stopRecordingPlayback()
|
||||||
|
refreshRecordingList()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
stopRecordingPlayback()
|
||||||
|
try {
|
||||||
|
val mp = MediaPlayer().apply {
|
||||||
|
setDataSource(path)
|
||||||
|
setOnCompletionListener { stopRecordingPlayback(); refreshRecordingList() }
|
||||||
|
prepare()
|
||||||
|
start()
|
||||||
|
}
|
||||||
|
recPlayer = mp
|
||||||
|
recPlayingPath = path
|
||||||
|
refreshRecordingList()
|
||||||
|
} catch (e: Exception) {
|
||||||
|
toast(getString(R.string.record_play_failed))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun stopRecordingPlayback() {
|
||||||
|
try { recPlayer?.stop() } catch (_: Exception) {}
|
||||||
|
try { recPlayer?.release() } catch (_: Exception) {}
|
||||||
|
recPlayer = null
|
||||||
|
recPlayingPath = null
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun refreshRecordingList() {
|
||||||
|
recListAdapter?.notifyDataSetChanged()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun confirmDeleteRecording(file: File, adapter: ArrayAdapter<File>, dialog: AlertDialog) {
|
||||||
|
AlertDialog.Builder(this)
|
||||||
|
.setTitle(R.string.record_delete_title)
|
||||||
|
.setMessage(file.name)
|
||||||
|
.setPositiveButton(R.string.record_delete_yes) { _, _ ->
|
||||||
|
if (recPlayingPath == file.absolutePath) stopRecordingPlayback()
|
||||||
|
file.delete()
|
||||||
|
adapter.remove(file)
|
||||||
|
adapter.notifyDataSetChanged()
|
||||||
|
toast(getString(R.string.record_deleted))
|
||||||
|
if (adapter.count == 0) dialog.dismiss()
|
||||||
|
}
|
||||||
|
.setNegativeButton(R.string.cancel, null)
|
||||||
|
.show()
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Переключиться на другую группу: отправить серверу по живому соединению. */
|
||||||
|
private fun switchGroup(tg: Long) {
|
||||||
|
settings = settings.copy(talkGroup = tg)
|
||||||
|
connectedSettings = settings
|
||||||
|
Prefs.save(this, settings)
|
||||||
|
refreshUi()
|
||||||
|
svc?.selectGroup(tg)
|
||||||
|
if (!monitoring) {
|
||||||
|
svc?.setMonitorTgs(listOf(tg))
|
||||||
|
} else {
|
||||||
|
resetMonitorIdle()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun monitorTgLabel(): String =
|
||||||
|
settings.groups.joinToString(", ") { "TG$it" }
|
||||||
|
|
||||||
|
private fun showNodesDialog() {
|
||||||
|
val nodes = svc?.nodeList().orEmpty()
|
||||||
|
if (nodes.isEmpty()) {
|
||||||
|
toast(getString(R.string.toast_nodes_empty))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
val myCs = settings.callsign.trim()
|
||||||
|
val items = nodes
|
||||||
|
.map { (cs, tg) ->
|
||||||
|
val t = tg ?: if (cs.equals(myCs, ignoreCase = true)) settings.talkGroup else null
|
||||||
|
if (t != null) getString(R.string.node_with_tg, cs, t) else cs
|
||||||
|
}
|
||||||
|
.sorted()
|
||||||
|
AlertDialog.Builder(this)
|
||||||
|
.setTitle(getString(R.string.nodes_title, items.size))
|
||||||
|
.setItems(items.toTypedArray(), null)
|
||||||
|
.show()
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Лог последних выходов на передачу (до 15, время — позывной — группа). */
|
||||||
|
private fun showTalkLogDialog() {
|
||||||
|
if (talkLog.isEmpty()) {
|
||||||
|
toast(getString(R.string.talk_log_empty))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
val fmt = java.text.SimpleDateFormat("HH:mm", java.util.Locale.getDefault())
|
||||||
|
val items = talkLog.map { e ->
|
||||||
|
getString(R.string.talk_log_entry, fmt.format(java.util.Date(e.time)), e.callsign, e.tg)
|
||||||
|
}.toTypedArray()
|
||||||
|
AlertDialog.Builder(this)
|
||||||
|
.setTitle(R.string.talk_log_title)
|
||||||
|
.setItems(items, null)
|
||||||
|
.setPositiveButton(R.string.close, null)
|
||||||
|
.show()
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Демо-окно с примерами индикаторов звука (удержание на «На связи»). */
|
||||||
|
private fun showSoundMetersPreview() {
|
||||||
|
AlertDialog.Builder(this)
|
||||||
|
.setTitle(R.string.meter_preview_title)
|
||||||
|
.setMessage(R.string.meter_preview_hint)
|
||||||
|
.setView(SoundMeterPreviewView(this))
|
||||||
|
.setPositiveButton(R.string.close, null)
|
||||||
|
.show()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun showGroupsDialog() {
|
||||||
|
val groups = (settings.groups + settings.talkGroup).distinct()
|
||||||
|
if (groups.isEmpty()) {
|
||||||
|
toast(getString(R.string.toast_groups_empty))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
val current = settings.talkGroup
|
||||||
|
AlertDialog.Builder(this)
|
||||||
|
.setTitle(R.string.select_tg)
|
||||||
|
.setItems(groups.map { tg ->
|
||||||
|
val label = getString(R.string.tg_badge, tg)
|
||||||
|
if (tg == current) "$label ✓" else label
|
||||||
|
}.toTypedArray()) { _, which ->
|
||||||
|
val tg = groups[which]
|
||||||
|
if (tg != current) switchGroup(tg)
|
||||||
|
}
|
||||||
|
.show()
|
||||||
|
}
|
||||||
|
|
||||||
private fun checkForUpdates() {
|
private fun checkForUpdates() {
|
||||||
Thread {
|
Thread {
|
||||||
val version = try {
|
val version = try {
|
||||||
|
|||||||
@@ -2,36 +2,67 @@ package ru.ua1zbe.svxremote
|
|||||||
|
|
||||||
import android.app.Activity
|
import android.app.Activity
|
||||||
import android.os.Bundle
|
import android.os.Bundle
|
||||||
|
import android.view.View
|
||||||
|
import android.widget.AdapterView
|
||||||
|
import android.widget.ArrayAdapter
|
||||||
import android.widget.Button
|
import android.widget.Button
|
||||||
|
import android.widget.CheckBox
|
||||||
import android.widget.EditText
|
import android.widget.EditText
|
||||||
|
import android.widget.Spinner
|
||||||
|
import android.widget.TextView
|
||||||
import android.widget.Toast
|
import android.widget.Toast
|
||||||
import ru.ua1zbe.svxremote.prefs.ConnectionSettings
|
import ru.ua1zbe.svxremote.prefs.ConnectionSettings
|
||||||
import ru.ua1zbe.svxremote.prefs.Prefs
|
import ru.ua1zbe.svxremote.prefs.Prefs
|
||||||
|
import ru.ua1zbe.svxremote.prefs.Profile
|
||||||
|
|
||||||
class SettingsActivity : Activity() {
|
class SettingsActivity : Activity() {
|
||||||
|
|
||||||
|
private lateinit var spinnerProfile: Spinner
|
||||||
private lateinit var inputHost: EditText
|
private lateinit var inputHost: EditText
|
||||||
private lateinit var inputPort: EditText
|
private lateinit var inputPort: EditText
|
||||||
private lateinit var inputCallsign: EditText
|
private lateinit var inputCallsign: EditText
|
||||||
private lateinit var inputAuthKey: EditText
|
private lateinit var inputAuthKey: EditText
|
||||||
private lateinit var inputTg: EditText
|
private lateinit var inputTg: EditText
|
||||||
|
private lateinit var inputGroups: EditText
|
||||||
|
private lateinit var inputAprsCoords: EditText
|
||||||
|
private var currentProfile = 0
|
||||||
|
|
||||||
override fun onCreate(savedInstanceState: Bundle?) {
|
override fun onCreate(savedInstanceState: Bundle?) {
|
||||||
super.onCreate(savedInstanceState)
|
super.onCreate(savedInstanceState)
|
||||||
setContentView(R.layout.activity_settings)
|
setContentView(R.layout.activity_settings)
|
||||||
|
|
||||||
|
spinnerProfile = findViewById(R.id.spinner_profile)
|
||||||
inputHost = findViewById(R.id.input_host)
|
inputHost = findViewById(R.id.input_host)
|
||||||
inputPort = findViewById(R.id.input_port)
|
inputPort = findViewById(R.id.input_port)
|
||||||
inputCallsign = findViewById(R.id.input_callsign)
|
inputCallsign = findViewById(R.id.input_callsign)
|
||||||
inputAuthKey = findViewById(R.id.input_auth_key)
|
inputAuthKey = findViewById(R.id.input_auth_key)
|
||||||
inputTg = findViewById(R.id.input_tg)
|
inputTg = findViewById(R.id.input_tg)
|
||||||
|
inputGroups = findViewById(R.id.input_groups)
|
||||||
|
inputAprsCoords = findViewById(R.id.input_aprs_coords)
|
||||||
|
val chkNodeToasts = findViewById<CheckBox>(R.id.chk_node_toasts)
|
||||||
|
chkNodeToasts.isChecked = Prefs.nodeToastsEnabled(this)
|
||||||
|
inputAprsCoords.setText(Prefs.aprsCoords(this))
|
||||||
|
findViewById<TextView>(R.id.lbl_version).text =
|
||||||
|
getString(R.string.app_version_fmt, BuildConfig.VERSION_NAME)
|
||||||
|
|
||||||
val s = Prefs.load(this)
|
val profileNames = (1..Prefs.PROFILE_COUNT)
|
||||||
inputHost.setText(s.host)
|
.map { getString(R.string.profile_name, it) }
|
||||||
inputPort.setText(s.port.toString())
|
spinnerProfile.adapter = ArrayAdapter(
|
||||||
inputCallsign.setText(s.callsign)
|
this, android.R.layout.simple_spinner_dropdown_item, profileNames
|
||||||
inputAuthKey.setText(s.authKey)
|
)
|
||||||
inputTg.setText(s.talkGroup.toString())
|
currentProfile = Prefs.activeProfileIndex(this)
|
||||||
|
spinnerProfile.setSelection(currentProfile)
|
||||||
|
spinnerProfile.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
|
||||||
|
override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
|
||||||
|
if (position != currentProfile) {
|
||||||
|
currentProfile = position
|
||||||
|
loadFields(Prefs.loadProfile(this@SettingsActivity, position).settings)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onNothingSelected(parent: AdapterView<*>?) {}
|
||||||
|
}
|
||||||
|
loadFields(Prefs.loadProfile(this, currentProfile).settings)
|
||||||
|
|
||||||
findViewById<Button>(R.id.btn_save).setOnClickListener {
|
findViewById<Button>(R.id.btn_save).setOnClickListener {
|
||||||
val host = inputHost.text.toString().trim()
|
val host = inputHost.text.toString().trim()
|
||||||
@@ -39,27 +70,45 @@ class SettingsActivity : Activity() {
|
|||||||
val callsign = inputCallsign.text.toString().trim()
|
val callsign = inputCallsign.text.toString().trim()
|
||||||
val authKey = inputAuthKey.text.toString()
|
val authKey = inputAuthKey.text.toString()
|
||||||
val tg = inputTg.text.toString().trim().toLongOrNull() ?: 11
|
val tg = inputTg.text.toString().trim().toLongOrNull() ?: 11
|
||||||
|
val groups = inputGroups.text.toString()
|
||||||
|
.split(',')
|
||||||
|
.mapNotNull { it.trim().toLongOrNull() }
|
||||||
|
.distinct()
|
||||||
|
|
||||||
if (host.isBlank() || callsign.isBlank()) {
|
if (host.isBlank() || callsign.isBlank()) {
|
||||||
toast(getString(R.string.toast_settings_empty))
|
toast(getString(R.string.toast_settings_empty))
|
||||||
return@setOnClickListener
|
return@setOnClickListener
|
||||||
}
|
}
|
||||||
|
|
||||||
Prefs.save(
|
val profile = Profile(
|
||||||
this,
|
name = getString(R.string.profile_name, currentProfile + 1),
|
||||||
ConnectionSettings(
|
settings = ConnectionSettings(
|
||||||
host = host,
|
host = host,
|
||||||
port = port.coerceIn(1, 65535),
|
port = port.coerceIn(1, 65535),
|
||||||
callsign = callsign,
|
callsign = callsign,
|
||||||
authKey = authKey,
|
authKey = authKey,
|
||||||
talkGroup = tg.coerceAtLeast(0)
|
talkGroup = tg.coerceAtLeast(0),
|
||||||
|
groups = groups
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
|
Prefs.saveProfile(this, currentProfile, profile)
|
||||||
|
Prefs.setActiveProfile(this, currentProfile)
|
||||||
|
Prefs.setNodeToastsEnabled(this, chkNodeToasts.isChecked)
|
||||||
|
Prefs.setAprsCoords(this, inputAprsCoords.text.toString())
|
||||||
toast(getString(R.string.saved))
|
toast(getString(R.string.saved))
|
||||||
finish()
|
finish()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private fun loadFields(s: ConnectionSettings) {
|
||||||
|
inputHost.setText(s.host)
|
||||||
|
inputPort.setText(s.port.toString())
|
||||||
|
inputCallsign.setText(s.callsign)
|
||||||
|
inputAuthKey.setText(s.authKey)
|
||||||
|
inputTg.setText(s.talkGroup.toString())
|
||||||
|
inputGroups.setText(s.groups.joinToString(", "))
|
||||||
|
}
|
||||||
|
|
||||||
private fun toast(msg: String) {
|
private fun toast(msg: String) {
|
||||||
Toast.makeText(this, msg, Toast.LENGTH_SHORT).show()
|
Toast.makeText(this, msg, Toast.LENGTH_SHORT).show()
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -9,15 +9,23 @@ import android.view.animation.AccelerateDecelerateInterpolator
|
|||||||
/** Красивая заставка с плавным появлением логотипа. */
|
/** Красивая заставка с плавным появлением логотипа. */
|
||||||
class SplashActivity : Activity() {
|
class SplashActivity : Activity() {
|
||||||
|
|
||||||
|
companion object {
|
||||||
|
@Volatile
|
||||||
|
var mainAlive = false
|
||||||
|
}
|
||||||
|
|
||||||
override fun onCreate(savedInstanceState: Bundle?) {
|
override fun onCreate(savedInstanceState: Bundle?) {
|
||||||
super.onCreate(savedInstanceState)
|
super.onCreate(savedInstanceState)
|
||||||
|
if (mainAlive) {
|
||||||
|
openMain()
|
||||||
|
return
|
||||||
|
}
|
||||||
setContentView(R.layout.activity_splash)
|
setContentView(R.layout.activity_splash)
|
||||||
|
|
||||||
val title = findViewById<View>(R.id.splash_title)
|
val title = findViewById<View>(R.id.splash_title)
|
||||||
val subtitle = findViewById<View>(R.id.splash_subtitle)
|
val subtitle = findViewById<View>(R.id.splash_subtitle)
|
||||||
val line = findViewById<View>(R.id.splash_line)
|
val line = findViewById<View>(R.id.splash_line)
|
||||||
|
|
||||||
val baseAlpha = title.alpha
|
|
||||||
title.alpha = 0f
|
title.alpha = 0f
|
||||||
subtitle.alpha = 0f
|
subtitle.alpha = 0f
|
||||||
line.alpha = 0f
|
line.alpha = 0f
|
||||||
@@ -44,10 +52,21 @@ class SplashActivity : Activity() {
|
|||||||
.start()
|
.start()
|
||||||
|
|
||||||
window.decorView.postDelayed({
|
window.decorView.postDelayed({
|
||||||
|
openMain()
|
||||||
|
}, 4000)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun openMain() {
|
||||||
val intent = Intent(this, MainActivity::class.java)
|
val intent = Intent(this, MainActivity::class.java)
|
||||||
|
.addFlags(
|
||||||
|
Intent.FLAG_ACTIVITY_NEW_TASK or
|
||||||
|
Intent.FLAG_ACTIVITY_CLEAR_TOP or
|
||||||
|
Intent.FLAG_ACTIVITY_SINGLE_TOP
|
||||||
|
)
|
||||||
|
val testText = this.intent?.getStringExtra("node_toast_test")
|
||||||
|
if (testText != null) intent.putExtra("node_toast_test", testText)
|
||||||
startActivity(intent)
|
startActivity(intent)
|
||||||
overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out)
|
overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out)
|
||||||
finish()
|
finish()
|
||||||
}, 4000)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -3,11 +3,15 @@ package ru.ua1zbe.svxremote
|
|||||||
import android.app.Notification
|
import android.app.Notification
|
||||||
import android.app.NotificationChannel
|
import android.app.NotificationChannel
|
||||||
import android.app.NotificationManager
|
import android.app.NotificationManager
|
||||||
|
import android.app.PendingIntent
|
||||||
import android.app.Service
|
import android.app.Service
|
||||||
import android.content.Intent
|
import android.content.Intent
|
||||||
import android.os.Binder
|
import android.os.Binder
|
||||||
import android.os.IBinder
|
import android.os.IBinder
|
||||||
|
import android.util.Log
|
||||||
import ru.ua1zbe.svxremote.audio.OpusEngine
|
import ru.ua1zbe.svxremote.audio.OpusEngine
|
||||||
|
import ru.ua1zbe.svxremote.audio.RxRecorder
|
||||||
|
import ru.ua1zbe.svxremote.prefs.Prefs
|
||||||
import ru.ua1zbe.svxremote.proto.MsgParser
|
import ru.ua1zbe.svxremote.proto.MsgParser
|
||||||
import ru.ua1zbe.svxremote.proto.ReflectorClient
|
import ru.ua1zbe.svxremote.proto.ReflectorClient
|
||||||
|
|
||||||
@@ -22,19 +26,28 @@ class SvxService : Service(), ReflectorClient.Callbacks {
|
|||||||
fun onServerInfo(info: MsgParser.ServerInfo)
|
fun onServerInfo(info: MsgParser.ServerInfo)
|
||||||
fun onTalkerStart(tg: Long, callsign: String)
|
fun onTalkerStart(tg: Long, callsign: String)
|
||||||
fun onTalkerStop(tg: Long, callsign: String)
|
fun onTalkerStop(tg: Long, callsign: String)
|
||||||
|
fun onNodeJoined(callsign: String, tg: Long?)
|
||||||
|
fun onNodeLeft(callsign: String, tg: Long?)
|
||||||
fun onAudioPacket(packet: ByteArray, seq: Int)
|
fun onAudioPacket(packet: ByteArray, seq: Int)
|
||||||
fun onAudioFlush()
|
fun onAudioFlush()
|
||||||
fun onError(detail: String)
|
fun onError(detail: String)
|
||||||
fun onLevel(source: Int, level: Float)
|
fun onLevel(source: Int, level: Float)
|
||||||
|
fun onRxStats(lossPct: Double, jitterMs: Double)
|
||||||
}
|
}
|
||||||
|
|
||||||
var listener: Listener? = null
|
var listener: Listener? = null
|
||||||
|
|
||||||
private val engine by lazy {
|
private val engine by lazy {
|
||||||
OpusEngine { source, level -> listener?.onLevel(source, level) }
|
OpusEngine(
|
||||||
|
onLevel = { source, level -> listener?.onLevel(source, level) },
|
||||||
|
onRxStats = { lossPct, jitterMs -> listener?.onRxStats(lossPct, jitterMs) }
|
||||||
|
).also { it.rxTap = { pcm, real -> recorder.feed(pcm, real) } }
|
||||||
}
|
}
|
||||||
val client: ReflectorClient by lazy { ReflectorClient(this) }
|
val client: ReflectorClient by lazy { ReflectorClient(this) }
|
||||||
|
|
||||||
|
/** Запись приёма в OGG (управляется из UI). */
|
||||||
|
private val recorder = RxRecorder()
|
||||||
|
|
||||||
private val binder = LocalBinder()
|
private val binder = LocalBinder()
|
||||||
|
|
||||||
inner class LocalBinder : Binder() {
|
inner class LocalBinder : Binder() {
|
||||||
@@ -53,11 +66,22 @@ class SvxService : Service(), ReflectorClient.Callbacks {
|
|||||||
nm.createNotificationChannel(
|
nm.createNotificationChannel(
|
||||||
NotificationChannel("svx", "SVXRemote", NotificationManager.IMPORTANCE_LOW)
|
NotificationChannel("svx", "SVXRemote", NotificationManager.IMPORTANCE_LOW)
|
||||||
)
|
)
|
||||||
|
updateNotification(getString(R.string.notif_connected))
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun updateNotification(text: String) {
|
||||||
|
val contentIntent = PendingIntent.getActivity(
|
||||||
|
this, 0,
|
||||||
|
Intent(this, MainActivity::class.java)
|
||||||
|
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_SINGLE_TOP),
|
||||||
|
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
|
||||||
|
)
|
||||||
val n = Notification.Builder(this, "svx")
|
val n = Notification.Builder(this, "svx")
|
||||||
.setContentTitle("SVXRemote")
|
.setContentTitle("SVXRemote")
|
||||||
.setContentText(getString(R.string.notif_connected))
|
.setContentText(text)
|
||||||
.setSmallIcon(android.R.drawable.ic_menu_call)
|
.setSmallIcon(R.drawable.ic_launcher_fg)
|
||||||
.setOngoing(true)
|
.setOngoing(true)
|
||||||
|
.setContentIntent(contentIntent)
|
||||||
.build()
|
.build()
|
||||||
startForeground(1, n)
|
startForeground(1, n)
|
||||||
}
|
}
|
||||||
@@ -73,20 +97,41 @@ class SvxService : Service(), ReflectorClient.Callbacks {
|
|||||||
|
|
||||||
fun isRunning(): Boolean = client.isRunning()
|
fun isRunning(): Boolean = client.isRunning()
|
||||||
|
|
||||||
|
fun selectGroup(tg: Long) {
|
||||||
|
// Сеть запрещена в главном потоке (NetworkOnMainThreadException)
|
||||||
|
Thread { client.selectGroup(tg) }.start()
|
||||||
|
}
|
||||||
|
|
||||||
|
fun setMonitorTgs(tgs: List<Long>) {
|
||||||
|
// Сеть запрещена в главном потоке (NetworkOnMainThreadException)
|
||||||
|
Thread { client.setMonitorTgs(tgs) }.start()
|
||||||
|
}
|
||||||
|
|
||||||
fun startTx() {
|
fun startTx() {
|
||||||
engine.startCapture { packet -> client.sendAudio(packet) }
|
engine.startCapture(Prefs.micGain(this)) { packet -> client.sendAudio(packet) }
|
||||||
}
|
}
|
||||||
|
|
||||||
fun stopTx() {
|
fun stopTx() {
|
||||||
|
Log.d("SVXRemote", "stopTx")
|
||||||
|
// В фоне: сеть запрещена в главном потоке (NetworkOnMainThreadException),
|
||||||
|
// а join потока захвата блокировал бы UI
|
||||||
|
Thread {
|
||||||
engine.stopCapture()
|
engine.stopCapture()
|
||||||
client.sendAudioFlush()
|
client.sendAudioFlush()
|
||||||
|
}.start()
|
||||||
}
|
}
|
||||||
|
|
||||||
// ---------- Callbacks (фоновые потоки) ----------
|
// ---------- Callbacks (фоновые потоки) ----------
|
||||||
|
|
||||||
override fun onState(state: Int, detail: String?) {
|
override fun onState(state: Int, detail: String?) {
|
||||||
when (state) {
|
when (state) {
|
||||||
ReflectorClient.STATE_READY -> engine.startDecoder()
|
ReflectorClient.STATE_READY -> {
|
||||||
|
updateNotification(getString(R.string.notif_connected))
|
||||||
|
engine.rxBufferMs = Prefs.rxBufferMs(this)
|
||||||
|
engine.jitterFrames = (Prefs.rxJitterMs(this) / 20).coerceAtLeast(1)
|
||||||
|
engine.txBitrateKbps = Prefs.txBitrateKbps(this)
|
||||||
|
engine.startDecoder()
|
||||||
|
}
|
||||||
ReflectorClient.STATE_DISCONNECTED -> {
|
ReflectorClient.STATE_DISCONNECTED -> {
|
||||||
engine.stopDecoder()
|
engine.stopDecoder()
|
||||||
stopForeground(STOP_FOREGROUND_REMOVE)
|
stopForeground(STOP_FOREGROUND_REMOVE)
|
||||||
@@ -96,25 +141,49 @@ class SvxService : Service(), ReflectorClient.Callbacks {
|
|||||||
}
|
}
|
||||||
|
|
||||||
override fun onServerInfo(info: MsgParser.ServerInfo) {
|
override fun onServerInfo(info: MsgParser.ServerInfo) {
|
||||||
|
synchronized(nodeSet) {
|
||||||
|
nodeSet.clear()
|
||||||
|
nodeSet.addAll(info.nodes)
|
||||||
|
}
|
||||||
listener?.onServerInfo(info)
|
listener?.onServerInfo(info)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private val nodeSet = LinkedHashSet<String>()
|
||||||
|
private val nodeTgs = HashMap<String, Long>()
|
||||||
|
|
||||||
|
/** Текущий список узлов и известные группы (копия для UI). */
|
||||||
|
fun nodeList(): List<Pair<String, Long?>> = synchronized(nodeSet) {
|
||||||
|
nodeSet.map { it to nodeTgs[it] }
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onNodeJoined(callsign: String, tg: Long?) {
|
||||||
|
synchronized(nodeSet) { nodeSet.add(callsign) }
|
||||||
|
listener?.onNodeJoined(callsign, tg)
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onNodeLeft(callsign: String, tg: Long?) {
|
||||||
|
synchronized(nodeSet) {
|
||||||
|
nodeSet.remove(callsign)
|
||||||
|
nodeTgs.remove(callsign)
|
||||||
|
}
|
||||||
|
listener?.onNodeLeft(callsign, tg)
|
||||||
|
}
|
||||||
|
|
||||||
override fun onTalkerStart(tg: Long, callsign: String) {
|
override fun onTalkerStart(tg: Long, callsign: String) {
|
||||||
|
synchronized(nodeSet) {
|
||||||
|
if (callsign in nodeSet) nodeTgs[callsign] = tg
|
||||||
|
}
|
||||||
|
updateNotification(getString(R.string.notif_talking, callsign))
|
||||||
listener?.onTalkerStart(tg, callsign)
|
listener?.onTalkerStart(tg, callsign)
|
||||||
}
|
}
|
||||||
|
|
||||||
override fun onTalkerStop(tg: Long, callsign: String) {
|
override fun onTalkerStop(tg: Long, callsign: String) {
|
||||||
|
updateNotification(getString(R.string.notif_last_talker, callsign))
|
||||||
listener?.onTalkerStop(tg, callsign)
|
listener?.onTalkerStop(tg, callsign)
|
||||||
}
|
}
|
||||||
|
|
||||||
override fun onNodeJoined(callsign: String) {
|
|
||||||
}
|
|
||||||
|
|
||||||
override fun onNodeLeft(callsign: String) {
|
|
||||||
}
|
|
||||||
|
|
||||||
override fun onAudioPacket(packet: ByteArray, seq: Int) {
|
override fun onAudioPacket(packet: ByteArray, seq: Int) {
|
||||||
engine.onAudioPacket(packet)
|
engine.onAudioPacket(packet, seq)
|
||||||
}
|
}
|
||||||
|
|
||||||
override fun onAudioFlush() {
|
override fun onAudioFlush() {
|
||||||
@@ -124,4 +193,27 @@ class SvxService : Service(), ReflectorClient.Callbacks {
|
|||||||
override fun onError(detail: String) {
|
override fun onError(detail: String) {
|
||||||
listener?.onError(detail)
|
listener?.onError(detail)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ---------- Запись приёма в файл ----------
|
||||||
|
|
||||||
|
fun isRecording(): Boolean = recorder.isRecording()
|
||||||
|
|
||||||
|
/** Начать запись. Возвращает путь к файлу или null при ошибке. */
|
||||||
|
fun startRecording(): String? {
|
||||||
|
if (recorder.isRecording()) return recorder.getFilePath()
|
||||||
|
val dir = getExternalFilesDir(null) ?: filesDir
|
||||||
|
return if (recorder.start(dir)) recorder.getFilePath() else null
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Остановить запись. Возвращает путь к сохранённому файлу или null. */
|
||||||
|
fun stopRecording(): String? {
|
||||||
|
if (!recorder.isRecording()) return null
|
||||||
|
recorder.stop()
|
||||||
|
return recorder.getFilePath()
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onDestroy() {
|
||||||
|
recorder.stop()
|
||||||
|
super.onDestroy()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
157
app/src/main/java/ru/ua1zbe/svxremote/aprs/AprsMeteo.kt
Normal file
157
app/src/main/java/ru/ua1zbe/svxremote/aprs/AprsMeteo.kt
Normal file
@@ -0,0 +1,157 @@
|
|||||||
|
package ru.ua1zbe.svxremote.aprs
|
||||||
|
|
||||||
|
import android.os.Handler
|
||||||
|
import android.os.Looper
|
||||||
|
import android.util.Log
|
||||||
|
import ru.ua1zbe.svxremote.BuildConfig
|
||||||
|
import java.io.BufferedReader
|
||||||
|
import java.io.InputStreamReader
|
||||||
|
import java.net.InetSocketAddress
|
||||||
|
import java.net.Socket
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Экспериментально: приём метеостанций с APRS-IS (aprs2.net) в радиусе 250 км
|
||||||
|
* от координат (фильтр r/). Весь код — в этом файле, удаляется вместе с
|
||||||
|
* вызовом в MainActivity и полями в настройках.
|
||||||
|
*/
|
||||||
|
class AprsMeteo(
|
||||||
|
private val coords: Pair<Double, Double>?,
|
||||||
|
private val onWeather: (String) -> Unit
|
||||||
|
) {
|
||||||
|
private val tag = "AprsMeteo"
|
||||||
|
private val main = Handler(Looper.getMainLooper())
|
||||||
|
@Volatile private var running = false
|
||||||
|
private var hostIdx = 0
|
||||||
|
|
||||||
|
fun start() {
|
||||||
|
if (running) return
|
||||||
|
running = true
|
||||||
|
Thread({ run() }, "aprs-meteo").start()
|
||||||
|
}
|
||||||
|
|
||||||
|
fun stop() {
|
||||||
|
running = false
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun run() {
|
||||||
|
while (running) {
|
||||||
|
try {
|
||||||
|
runOnce()
|
||||||
|
} catch (e: Exception) {
|
||||||
|
if (running) Log.d(tag, "err: ${e.message}")
|
||||||
|
}
|
||||||
|
if (running) {
|
||||||
|
try {
|
||||||
|
Thread.sleep(30_000)
|
||||||
|
} catch (_: InterruptedException) {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun runOnce() {
|
||||||
|
val sock = Socket()
|
||||||
|
try {
|
||||||
|
sock.connect(InetSocketAddress(APRS_HOSTS[hostIdx], APRS_PORT), 10_000)
|
||||||
|
sock.soTimeout = 90_000
|
||||||
|
val filter = if (coords != null) {
|
||||||
|
"r/${coords.first}/${coords.second}/250"
|
||||||
|
} else {
|
||||||
|
// Координаты не заданы — функция отключена (MainActivity не запускает)
|
||||||
|
"b/$APRS_CALL/250"
|
||||||
|
}
|
||||||
|
// ВАЖНО: без "vers" — сервер пользователя (T2SPB/T2APATITY)
|
||||||
|
// не принимает фильтр и молчит; с "vers" — фильтр игнорируется
|
||||||
|
val login = "user $APRS_CALL pass ${passcode(APRS_CALL)} " +
|
||||||
|
"filter $filter\r\n"
|
||||||
|
sock.getOutputStream().write(login.toByteArray())
|
||||||
|
sock.getOutputStream().flush()
|
||||||
|
Log.d(tag, "connected to ${APRS_HOSTS[hostIdx]}, filter=$filter")
|
||||||
|
val reader = BufferedReader(InputStreamReader(sock.getInputStream()))
|
||||||
|
val start = System.currentTimeMillis()
|
||||||
|
var sawPacket = false
|
||||||
|
while (running) {
|
||||||
|
val line = try {
|
||||||
|
reader.readLine()
|
||||||
|
} catch (e: java.net.SocketTimeoutException) {
|
||||||
|
// Нет строк (даже heartbeat) — канал мёртв, переподключаемся
|
||||||
|
break
|
||||||
|
} ?: break
|
||||||
|
if (line.startsWith("#")) {
|
||||||
|
if (line.contains("logresp")) {
|
||||||
|
val server = line.substringAfter("server", "?").trim()
|
||||||
|
Log.d(tag, "server=$server")
|
||||||
|
}
|
||||||
|
// Сервер шлёт heartbeat, но не отдаёт пакеты. На основном
|
||||||
|
// сервере слушаем долго (станции передают редко), на
|
||||||
|
// запасном — 3 минуты, и возвращаемся на основной
|
||||||
|
val wait = if (hostIdx == 0) 900_000L else 180_000L
|
||||||
|
if (!sawPacket && System.currentTimeMillis() - start > wait) break
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
sawPacket = true
|
||||||
|
if (BuildConfig.DEBUG) Log.d(tag, "pkt: " + line.substringBefore('>'))
|
||||||
|
parse(line)?.let { wx ->
|
||||||
|
Log.d(tag, "wx: $wx RAW=${line.length} $line")
|
||||||
|
main.post { onWeather(wx) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Сервер принял логин, но не отдал ни одного пакета (аплинк молчит) —
|
||||||
|
// в следующий раз пробуем следующий сервер. С пакетами — возвращаемся
|
||||||
|
// к первому (сервер пользователя)
|
||||||
|
hostIdx = if (sawPacket) 0 else (hostIdx + 1) % APRS_HOSTS.size
|
||||||
|
} finally {
|
||||||
|
try {
|
||||||
|
sock.close()
|
||||||
|
} catch (_: Exception) {
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Парсинг: CALL>...:!|@|=<lat/lon>_<метео> -> "<call> Температура <T>C". */
|
||||||
|
private fun parse(line: String): String? {
|
||||||
|
if (line.startsWith("#") || line.isEmpty()) return null
|
||||||
|
// Разделитель заголовка — ПЕРВЫЙ ':' после '>'; в info могут быть свои ':'
|
||||||
|
// (например "Temp: 16.4°C Uptime: 319h")
|
||||||
|
val gt = line.indexOf('>')
|
||||||
|
val idx = line.indexOf(':', gt)
|
||||||
|
if (idx < 0 || idx + 1 >= line.length) return null
|
||||||
|
val body = line.substring(idx + 1)
|
||||||
|
if (body.isEmpty() || body[0] !in "!@=") return null
|
||||||
|
val temp = parseTemp(body) ?: return null
|
||||||
|
// В APRS метео-часть температура в градусах Фаренгейта
|
||||||
|
val c = (temp - 32.0) * 5.0 / 9.0
|
||||||
|
val t = Math.round(c).toString()
|
||||||
|
return "WX " + line.substringBefore('>') + " Температура: " + t + " °C"
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Температура из метео-части после символа '_': t057=57°F, t06=6°F, t-08=-8°F.
|
||||||
|
* В APRS метео-формате температура — целые градусы Фаренгейта. */
|
||||||
|
private fun parseTemp(body: String): Double? {
|
||||||
|
val u = body.indexOf('_')
|
||||||
|
if (u < 0) return null
|
||||||
|
val meta = body.substring(u + 1).substringBefore(' ') // до комментария
|
||||||
|
val m = Regex("[tT]([+-]?)(\\d{2,3})").find(meta) ?: return null
|
||||||
|
val sign = if (m.groupValues[1] == "-") -1 else 1
|
||||||
|
return sign * m.groupValues[2].toInt().toDouble()
|
||||||
|
}
|
||||||
|
|
||||||
|
/** APRS-IS passcode по позывному (алгоритм aprsc). */
|
||||||
|
private fun passcode(call: String): Int {
|
||||||
|
var hash = 0x73E2
|
||||||
|
for (c in call.uppercase()) {
|
||||||
|
hash = hash xor (c.code shl 8)
|
||||||
|
hash = ((hash and 0xFFFF) * 0x89) and 0xFFFF
|
||||||
|
}
|
||||||
|
return hash and 0x7FFF
|
||||||
|
}
|
||||||
|
|
||||||
|
companion object {
|
||||||
|
// Позывной для подключения к APRS-IS (SVX). Сначала сервер пользователя;
|
||||||
|
// если он не отдаёт трафик (аплинк молчит), переходим на публичный aprs2.net
|
||||||
|
private const val APRS_CALL = "SVX"
|
||||||
|
private val APRS_HOSTS = listOf("rotate.radiorubka.org", "rotate.aprs2.net")
|
||||||
|
private const val APRS_PORT = 14580
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -20,7 +20,8 @@ import kotlin.math.log10
|
|||||||
* SVXLink: моно, 8 кГц, 16 бит PCM, кадры 20 мс. Поток уровня сигнала 0..1.
|
* SVXLink: моно, 8 кГц, 16 бит PCM, кадры 20 мс. Поток уровня сигнала 0..1.
|
||||||
*/
|
*/
|
||||||
class OpusEngine(
|
class OpusEngine(
|
||||||
private val onLevel: (source: Int, level: Float) -> Unit
|
private val onLevel: (source: Int, level: Float) -> Unit,
|
||||||
|
private val onRxStats: ((lossPct: Double, jitterMs: Double) -> Unit)? = null
|
||||||
) {
|
) {
|
||||||
|
|
||||||
companion object {
|
companion object {
|
||||||
@@ -30,6 +31,10 @@ class OpusEngine(
|
|||||||
const val CHANNELS = 1
|
const val CHANNELS = 1
|
||||||
const val FRAME_SIZE = 160 // 20 мс в 8 кГц
|
const val FRAME_SIZE = 160 // 20 мс в 8 кГц
|
||||||
const val BIT_RATE = 20000
|
const val BIT_RATE = 20000
|
||||||
|
// Авто-адаптация битрейта TX (0 = авто включено в настройках)
|
||||||
|
const val AUTO_BITRATE_MIN = 8
|
||||||
|
const val AUTO_BITRATE_MAX = 24
|
||||||
|
const val AUTO_BITRATE_STEP = 4
|
||||||
|
|
||||||
const val SRC_MIC = 0
|
const val SRC_MIC = 0
|
||||||
const val SRC_SPEAKER = 1
|
const val SRC_SPEAKER = 1
|
||||||
@@ -47,40 +52,69 @@ class OpusEngine(
|
|||||||
private var recThread: Thread? = null
|
private var recThread: Thread? = null
|
||||||
|
|
||||||
private val encodeBufferInfo = MediaCodec.BufferInfo()
|
private val encodeBufferInfo = MediaCodec.BufferInfo()
|
||||||
private val decodeBufferInfo = MediaCodec.BufferInfo()
|
|
||||||
|
|
||||||
// ---------- Воспроизведение (RX) ----------
|
// ---------- Воспроизведение (RX) ----------
|
||||||
|
|
||||||
private var headSent = false
|
|
||||||
private val rxQueue = java.util.concurrent.ConcurrentLinkedQueue<ByteArray>()
|
private val rxQueue = java.util.concurrent.ConcurrentLinkedQueue<ByteArray>()
|
||||||
private var drainThread: Thread? = null
|
private val freeInputs = java.util.concurrent.ConcurrentLinkedQueue<Int>()
|
||||||
private var ptsCounter = 0L
|
private var ptsCounter = 0L
|
||||||
|
private var receivedAny = false
|
||||||
|
private var concealLogs = 0
|
||||||
|
private var dbgOut = 0
|
||||||
|
private var playStarted = false
|
||||||
|
private var gateStart = 0L
|
||||||
|
private var lastRealPacketTime = 0L
|
||||||
|
// Настраивается из скрытых настроек звука (AudioSettingsActivity)
|
||||||
|
@Volatile
|
||||||
|
var rxBufferMs = 417 // буфер AudioTrack, мс (40000 байт ≈ 417 мс при 48 кГц)
|
||||||
|
@Volatile
|
||||||
|
var jitterFrames = 10 // сколько кадров накопить до первого слива (кадр = 20 мс)
|
||||||
|
// Скорость передачи Opus, кбит/с. 0 = Авто (адаптация под интернет).
|
||||||
|
@Volatile
|
||||||
|
var txBitrateKbps = 0
|
||||||
|
// Перехват декодированного RX PCM (для записи в файл). Аргументы: PCM, реальный приём?
|
||||||
|
@Volatile
|
||||||
|
var rxTap: ((pcm: ByteArray, isReal: Boolean) -> Unit)? = null
|
||||||
|
// Текущий битрейт в режиме Авто (пересчитывается по статистике приёма)
|
||||||
|
@Volatile
|
||||||
|
private var autoKbps = 16
|
||||||
|
private val configBuffers = ArrayList<ByteArray>()
|
||||||
|
private var configIdx = 0
|
||||||
|
|
||||||
|
// ---------- Статистика приёма для авто-битрейта ----------
|
||||||
|
private var lastSeq = -1
|
||||||
|
private var lastPktTime = 0L
|
||||||
|
private var lossCount = 0L
|
||||||
|
private var pktCount = 0L
|
||||||
|
private var jitterAccum = 0.0
|
||||||
|
private var jitterN = 0
|
||||||
|
private var lastEvalTime = 0L
|
||||||
|
private var goodWindows = 0
|
||||||
|
|
||||||
|
/** Размер пакета при 20 мс кадре: bitrate * 0.02 / 8 байт. */
|
||||||
|
fun bitrateBytes(kbps: Int): Int = (kbps * 20) / 8
|
||||||
|
|
||||||
|
/** Эффективный битрейт для следующей передачи, бит/с. */
|
||||||
|
fun effectiveBitrate(): Int {
|
||||||
|
val kbps = if (txBitrateKbps > 0) txBitrateKbps else autoKbps
|
||||||
|
return kbps * 1000
|
||||||
|
}
|
||||||
|
|
||||||
fun startDecoder() {
|
fun startDecoder() {
|
||||||
if (decoder != null) return
|
if (decoder != null) return
|
||||||
val format = MediaFormat()
|
val format = MediaFormat()
|
||||||
format.setString(MediaFormat.KEY_MIME, MediaFormat.MIMETYPE_AUDIO_OPUS)
|
format.setString(MediaFormat.KEY_MIME, MediaFormat.MIMETYPE_AUDIO_OPUS)
|
||||||
format.setInteger(MediaFormat.KEY_SAMPLE_RATE, SAMPLE_RATE)
|
// ВАЖНО: c2.android.opus.decoder (Android 16) выводит только 48 кГц
|
||||||
|
// (kRate=48000); KEY_SAMPLE_RATE=8000 вызывает конфликт конфига
|
||||||
|
// («We have a failed config») и фатальную ошибку кодера.
|
||||||
|
format.setInteger(MediaFormat.KEY_SAMPLE_RATE, OUT_SAMPLE_RATE)
|
||||||
format.setInteger(MediaFormat.KEY_CHANNEL_COUNT, CHANNELS)
|
format.setInteger(MediaFormat.KEY_CHANNEL_COUNT, CHANNELS)
|
||||||
format.setInteger(MediaFormat.KEY_MAX_INPUT_SIZE, 8192)
|
// Android 16: c2.android.opus.decoder читает конфиг (OpusHead + codec
|
||||||
// Android 16: c2.android.opus.decoder ждёт 3 конфиг-буфера:
|
// delay + seek preroll) ТОЛЬКО из первых входных буферов
|
||||||
// csd-0 OpusHead, csd-1 CodecDelay (int64 LE нс), csd-2 SeekPreRoll (int64 LE нс).
|
// (см. queueDecoderConfig); csd-ключи MediaFormat он игнорирует, и без
|
||||||
// Без csd-1/2 декодер берёт мусорные значения из пакетов и молча
|
// конфига первый же аудио-кадр ломает декодер (C2_CORRUPTED).
|
||||||
// выкидывает весь вывод (mSamplesToDiscard).
|
if (!startDecoderCodec(format)) return
|
||||||
format.setByteBuffer("csd-0", ByteBuffer.wrap(opusHead()))
|
Log.d(TAG, "decoder started, config=${configBuffers.size}B")
|
||||||
// Прескип 312 сэмплов при 8 кГц = 39 мс = 39_000_000 нс (перекодируется в 48 кГц внутри)
|
|
||||||
format.setByteBuffer("csd-1", ByteBuffer.wrap(longBytes(39_000_000L)))
|
|
||||||
format.setByteBuffer("csd-2", ByteBuffer.wrap(longBytes(0L)))
|
|
||||||
decoder = try {
|
|
||||||
MediaCodec.createDecoderByType(MediaFormat.MIMETYPE_AUDIO_OPUS).also {
|
|
||||||
it.configure(format, null, null, 0)
|
|
||||||
it.start()
|
|
||||||
}
|
|
||||||
} catch (e: Exception) {
|
|
||||||
Log.e(TAG, "createDecoder failed: ${e.message}")
|
|
||||||
null
|
|
||||||
}
|
|
||||||
if (decoder == null) return
|
|
||||||
val minBuf = AudioTrack.getMinBufferSize(
|
val minBuf = AudioTrack.getMinBufferSize(
|
||||||
OUT_SAMPLE_RATE,
|
OUT_SAMPLE_RATE,
|
||||||
AudioFormat.CHANNEL_OUT_MONO,
|
AudioFormat.CHANNEL_OUT_MONO,
|
||||||
@@ -92,89 +126,323 @@ class OpusEngine(
|
|||||||
OUT_SAMPLE_RATE,
|
OUT_SAMPLE_RATE,
|
||||||
AudioFormat.CHANNEL_OUT_MONO,
|
AudioFormat.CHANNEL_OUT_MONO,
|
||||||
AudioFormat.ENCODING_PCM_16BIT,
|
AudioFormat.ENCODING_PCM_16BIT,
|
||||||
maxOf(minBuf, FRAME_SIZE * 2 * 8),
|
maxOf(minBuf, rxBufferMs * 96), // 96 байт/мс при 48 кГц моно 16 бит
|
||||||
AudioTrack.MODE_STREAM
|
AudioTrack.MODE_STREAM
|
||||||
).also { it.play() }
|
) // play() включаем на первом выходном кадре — буфер успевает накопиться
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
Log.e(TAG, "AudioTrack create failed: ${e.message}")
|
Log.e(TAG, "AudioTrack create failed: ${e.message}")
|
||||||
null
|
null
|
||||||
}
|
}
|
||||||
headSent = true // csd уходит через формат, не через буферы
|
concealLogs = 0
|
||||||
drainThread = Thread({ drainLoop() }, "opus-out").also { it.start() }
|
dbgOut = 0
|
||||||
|
ptsCounter = 20_000L // первый кадр: pts!=0, иначе декодер повторно сбросит codecDelay
|
||||||
Log.d(TAG, "decoder started")
|
Log.d(TAG, "decoder started")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Создать и запустить только декодер (плеер не трогаем). */
|
||||||
|
private fun startDecoderCodec(format: MediaFormat): Boolean {
|
||||||
|
val dec = try {
|
||||||
|
MediaCodec.createDecoderByType(MediaFormat.MIMETYPE_AUDIO_OPUS).also {
|
||||||
|
it.setCallback(decoderCallback)
|
||||||
|
it.configure(format, null, null, 0)
|
||||||
|
queueDecoderConfig() // готовим конфиг ДО start: колбэки уйдут после
|
||||||
|
}
|
||||||
|
} catch (e: Exception) {
|
||||||
|
Log.e(TAG, "createDecoder failed: ${e.message}")
|
||||||
|
null
|
||||||
|
}
|
||||||
|
if (dec == null) return false
|
||||||
|
// decoder назначаем ДО start(): колбэки нового кодека сразу проходят
|
||||||
|
// проверку codec !== decoder, иначе первый конфиг-колбэк отбрасывается
|
||||||
|
// и декодер навсегда остаётся без конфига
|
||||||
|
decoder = dec
|
||||||
|
freeInputs.clear()
|
||||||
|
rxQueue.clear()
|
||||||
|
receivedAny = false
|
||||||
|
playStarted = false
|
||||||
|
gateStart = 0L
|
||||||
|
try {
|
||||||
|
dec.start()
|
||||||
|
} catch (e: Exception) {
|
||||||
|
Log.e(TAG, "decoder start failed: ${e.message}")
|
||||||
|
decoder = null
|
||||||
|
try {
|
||||||
|
dec.release()
|
||||||
|
} catch (_: Exception) {
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Асинхронные колбэки кодера: подача входных кадров + слив вывода. */
|
||||||
|
private val decoderCallback = object : MediaCodec.Callback() {
|
||||||
|
override fun onError(codec: MediaCodec, e: MediaCodec.CodecException) {
|
||||||
|
if (codec !== decoder) return // колбэк от уже пересозданного декодера
|
||||||
|
Log.e(TAG, "decoder error: ${e.message} code=${e.errorCode} transient=${e.isTransient}")
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onInputBufferAvailable(codec: MediaCodec, index: Int) {
|
||||||
|
if (codec !== decoder) return // колбэк от уже пересозданного декодера
|
||||||
|
// Конфиг (csd) первыми входными буферами — в async-режиме нельзя
|
||||||
|
// использовать dequeueInputBuffer, только колбэки
|
||||||
|
if (configIdx < configBuffers.size) {
|
||||||
|
val data = configBuffers[configIdx++]
|
||||||
|
try {
|
||||||
|
val buf = codec.getInputBuffer(index) ?: return
|
||||||
|
buf.clear()
|
||||||
|
buf.put(data)
|
||||||
|
codec.queueInputBuffer(index, 0, data.size, 0, MediaCodec.BUFFER_FLAG_CODEC_CONFIG)
|
||||||
|
Log.d(TAG, "cfg ${data.size}B")
|
||||||
|
} catch (e: Exception) {
|
||||||
|
Log.e(TAG, "cfg error: ${e.message}")
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
val pkt = rxQueue.poll()
|
||||||
|
when {
|
||||||
|
// Джиттер-гейт: пока не накопили jitterTarget кадров (или не
|
||||||
|
// вышло 80 мс с первого пакета) — не кормим декодер, чтобы
|
||||||
|
// буфер AudioTrack успел заполниться до старта воспроизведения
|
||||||
|
pkt != null && gateOpen() -> feedDecoder(codec, index, pkt)
|
||||||
|
pkt != null -> {
|
||||||
|
rxQueue.add(pkt)
|
||||||
|
freeInputs.add(index)
|
||||||
|
}
|
||||||
|
receivedAny -> {
|
||||||
|
if (concealLogs < 3) {
|
||||||
|
Log.d(TAG, "conceal (no packet)")
|
||||||
|
concealLogs++
|
||||||
|
}
|
||||||
|
feedDecoder(codec, index, silenceFrame()) // скрытие потерь
|
||||||
|
}
|
||||||
|
else -> freeInputs.add(index) // ждём первый пакет
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onOutputBufferAvailable(codec: MediaCodec, index: Int, info: MediaCodec.BufferInfo) {
|
||||||
|
if (codec !== decoder) return // колбэк от уже пересозданного декодера
|
||||||
|
try {
|
||||||
|
if (info.size > 0) {
|
||||||
|
val outBuf = ByteBuffer.allocate(info.size)
|
||||||
|
outBuf.order(ByteOrder.LITTLE_ENDIAN)
|
||||||
|
codec.getOutputBuffer(index)?.also { src ->
|
||||||
|
src.position(info.offset)
|
||||||
|
src.limit(info.offset + info.size)
|
||||||
|
outBuf.put(src)
|
||||||
|
}
|
||||||
|
val pcm = outBuf.array()
|
||||||
|
if (!playStarted) {
|
||||||
|
playStarted = true
|
||||||
|
Log.d(TAG, "play start")
|
||||||
|
try {
|
||||||
|
player?.play()
|
||||||
|
} catch (e: Exception) {
|
||||||
|
Log.e(TAG, "play error: ${e.message}")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
player?.write(pcm, 0, pcm.size)
|
||||||
|
// Уровень показываем только для реальных пакетов: во время
|
||||||
|
// скрытия потерь (conceal) шкала должна быть в нуле
|
||||||
|
val real = System.currentTimeMillis() - lastRealPacketTime < 400
|
||||||
|
rxTap?.invoke(pcm, real)
|
||||||
|
val lvl = if (real) pcmLevel(pcm) else 0f
|
||||||
|
// Порог тишины: шум декодера и паузы речи — в ноль
|
||||||
|
onLevel(SRC_SPEAKER, if (lvl < 0.02f) 0f else lvl)
|
||||||
|
if (dbgOut < 5) {
|
||||||
|
Log.d(TAG, "out ${pcm.size}B")
|
||||||
|
dbgOut++
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (e: Exception) {
|
||||||
|
Log.e(TAG, "out error: ${e.message}")
|
||||||
|
} finally {
|
||||||
|
try {
|
||||||
|
codec.releaseOutputBuffer(index, false)
|
||||||
|
} catch (_: Exception) {
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onOutputFormatChanged(codec: MediaCodec, format: MediaFormat) {
|
||||||
|
if (codec !== decoder) return // колбэк от уже пересозданного декодера
|
||||||
|
Log.d(TAG, "dec out format: sr=${format.getInteger(MediaFormat.KEY_SAMPLE_RATE)} " +
|
||||||
|
"ch=${format.getInteger(MediaFormat.KEY_CHANNEL_COUNT)}")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun feedDecoder(codec: MediaCodec, index: Int, pkt: ByteArray) {
|
||||||
|
try {
|
||||||
|
val buf = codec.getInputBuffer(index) ?: return
|
||||||
|
buf.clear()
|
||||||
|
buf.put(pkt)
|
||||||
|
codec.queueInputBuffer(index, 0, pkt.size, ptsCounter, 0)
|
||||||
|
ptsCounter += 20_000L // 20 мс кадра
|
||||||
|
if (concealLogs < 3 && rxQueue.isEmpty() && pkt === silenceFrame()) {
|
||||||
|
Log.d(TAG, "conceal (no packet)")
|
||||||
|
concealLogs++
|
||||||
|
}
|
||||||
|
} catch (e: Exception) {
|
||||||
|
Log.e(TAG, "feed error: ${e.message}")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Android 16: c2.android.opus.decoder читает конфиг из первых входных
|
||||||
|
* буферов. Единый CSD-блоб (формат AOSP WriteOpusHeaders): OpusHead (19
|
||||||
|
* байт) + codecDelay (int64 LE нс) + seekPreroll (int64 LE нс) — БЕЗ
|
||||||
|
* u32-префиксов длины. После него декодер уже сконфигурирован; лишние
|
||||||
|
* конфиг-буферы игнорируются как повторный CSD, поэтому шлём и их.
|
||||||
|
*/
|
||||||
|
private fun queueDecoderConfig() {
|
||||||
|
configBuffers.clear()
|
||||||
|
try {
|
||||||
|
val head = opusHead()
|
||||||
|
val delay = longBytes(39_000_000L) // прескип 312 сэмплов при 8 кГц = 39 мс
|
||||||
|
val preroll = longBytes(0L)
|
||||||
|
val w = java.io.ByteArrayOutputStream()
|
||||||
|
w.write(head)
|
||||||
|
w.write(delay)
|
||||||
|
w.write(preroll)
|
||||||
|
configBuffers.add(w.toByteArray())
|
||||||
|
configBuffers.add(delay)
|
||||||
|
configBuffers.add(preroll)
|
||||||
|
configIdx = 0
|
||||||
|
} catch (_: Exception) {
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/** int64 в little-endian. */
|
/** int64 в little-endian. */
|
||||||
private fun longBytes(v: Long): ByteArray =
|
private fun longBytes(v: Long): ByteArray =
|
||||||
ByteBuffer.allocate(8).order(ByteOrder.LITTLE_ENDIAN).putLong(v).array()
|
ByteBuffer.allocate(8).order(ByteOrder.LITTLE_ENDIAN).putLong(v).array()
|
||||||
|
|
||||||
/** Отдельный поток: голова + входная очередь + слив вывода. */
|
/** Подача одного Opus-пакета на декодер (с UDP-потока). */
|
||||||
private fun drainLoop() {
|
fun onAudioPacket(packet: ByteArray, seq: Int) {
|
||||||
val dec = decoder ?: return
|
updateRxStats(seq)
|
||||||
var dbg = 0
|
lastRealPacketTime = System.currentTimeMillis()
|
||||||
while (decoder != null && decoder === dec) {
|
rxQueue.add(packet)
|
||||||
try {
|
receivedAny = true
|
||||||
// Монотонный pts обязателен: при pts==0 c2.opus.decoder
|
if (gateStart == 0L) gateStart = System.currentTimeMillis()
|
||||||
// считает каждый кадр «перемоткой в ноль» и выбрасывает
|
if (!gateOpen()) return
|
||||||
// mCodecDelay сэмплов (C2SoftOpusDec.cpp, "When seeking to zero").
|
val idx = freeInputs.poll() ?: return // если слот свободен — кормим сразу
|
||||||
var pts = ptsCounter
|
decoder?.let { feedDecoder(it, idx, rxQueue.poll() ?: packet) }
|
||||||
while (true) {
|
|
||||||
val pkt = rxQueue.poll() ?: break
|
|
||||||
val inIdx = dec.dequeueInputBuffer(5000)
|
|
||||||
if (inIdx < 0) { rxQueue.add(pkt); break }
|
|
||||||
val buf = dec.getInputBuffer(inIdx) ?: break
|
|
||||||
buf.clear()
|
|
||||||
buf.put(pkt)
|
|
||||||
dec.queueInputBuffer(inIdx, 0, pkt.size, pts, 0)
|
|
||||||
pts += 20_000L // 20 мс кадра
|
|
||||||
ptsCounter = pts
|
|
||||||
if (dbg < 5) { Log.d(TAG, "queued ${pkt.size}B"); dbg++ }
|
|
||||||
}
|
|
||||||
var outIdx = dec.dequeueOutputBuffer(decodeBufferInfo, 1000)
|
|
||||||
while (outIdx >= 0) {
|
|
||||||
if (outIdx == MediaCodec.INFO_OUTPUT_FORMAT_CHANGED) {
|
|
||||||
val f = dec.outputFormat
|
|
||||||
Log.d(TAG, "dec out format: sr=${f.getInteger(MediaFormat.KEY_SAMPLE_RATE)} " +
|
|
||||||
"ch=${f.getInteger(MediaFormat.KEY_CHANNEL_COUNT)}")
|
|
||||||
} else {
|
|
||||||
if (decodeBufferInfo.size > 0) {
|
|
||||||
val outBuf = ByteBuffer.allocate(decodeBufferInfo.size)
|
|
||||||
outBuf.order(ByteOrder.LITTLE_ENDIAN)
|
|
||||||
dec.getOutputBuffer(outIdx)?.also { src ->
|
|
||||||
src.position(decodeBufferInfo.offset)
|
|
||||||
src.limit(decodeBufferInfo.offset + decodeBufferInfo.size)
|
|
||||||
outBuf.put(src)
|
|
||||||
}
|
|
||||||
val pcm = outBuf.array()
|
|
||||||
player?.write(pcm, 0, pcm.size)
|
|
||||||
onLevel(SRC_SPEAKER, pcmLevel(pcm))
|
|
||||||
if (dbg < 5) { Log.d(TAG, "out ${pcm.size}B"); dbg++ }
|
|
||||||
}
|
|
||||||
dec.releaseOutputBuffer(outIdx, false)
|
|
||||||
}
|
|
||||||
outIdx = dec.dequeueOutputBuffer(decodeBufferInfo, 0)
|
|
||||||
}
|
|
||||||
} catch (e: Exception) {
|
|
||||||
Log.e(TAG, "drain error: ${e.message}")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Подача одного Opus-пакета на декодер. */
|
/**
|
||||||
fun onAudioPacket(packet: ByteArray) {
|
* Статистика приёма (потери по seq, джиттер по интервалам пакетов).
|
||||||
rxQueue.add(packet)
|
* Раз в 5 секунд корректирует autoKbps: плохо — ниже, стабильно — выше.
|
||||||
|
*/
|
||||||
|
private fun updateRxStats(seq: Int) {
|
||||||
|
val now = System.currentTimeMillis()
|
||||||
|
if (lastSeq >= 0) {
|
||||||
|
val dt = now - lastPktTime
|
||||||
|
// seq — счётчик ГОВОРЯЩЕГО: при повторах кадров он может
|
||||||
|
// повторяться или идти назад — это не потери. Пауза > 200 мс
|
||||||
|
// между пакетами — смена реплики/говорящего, тоже не потери.
|
||||||
|
if (dt <= 200) {
|
||||||
|
val gap = (seq - lastSeq - 1).toLong()
|
||||||
|
if (gap in 1..50000) lossCount += gap
|
||||||
|
}
|
||||||
|
pktCount++
|
||||||
|
val j = abs(dt - 20).toDouble()
|
||||||
|
if (j < 100) {
|
||||||
|
jitterAccum += j
|
||||||
|
jitterN++
|
||||||
|
}
|
||||||
|
}
|
||||||
|
lastSeq = seq
|
||||||
|
lastPktTime = now
|
||||||
|
if (lastEvalTime == 0L) {
|
||||||
|
lastEvalTime = now
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if (now - lastEvalTime < 5000 || pktCount < 30) return
|
||||||
|
val lossPct = lossCount * 100.0 / pktCount
|
||||||
|
val jitterMs = if (jitterN > 0) jitterAccum / jitterN else 0.0
|
||||||
|
Log.d(TAG, "stats window: pkt=$pktCount loss=$lossCount pct=$lossPct j=$jitterMs lastSeq=$lastSeq")
|
||||||
|
if (lossPct > 3.0 || jitterMs > 60.0) {
|
||||||
|
if (autoKbps > AUTO_BITRATE_MIN) {
|
||||||
|
autoKbps -= AUTO_BITRATE_STEP
|
||||||
|
Log.d(TAG, "auto bitrate down: ${autoKbps}kbps (loss=${"%.1f".format(lossPct)}% jitter=${"%.0f".format(jitterMs)}ms)")
|
||||||
|
}
|
||||||
|
goodWindows = 0
|
||||||
|
} else if (lossPct < 0.5 && jitterMs < 25.0) {
|
||||||
|
goodWindows++
|
||||||
|
if (goodWindows >= 2 && autoKbps < AUTO_BITRATE_MAX) {
|
||||||
|
autoKbps += AUTO_BITRATE_STEP
|
||||||
|
Log.d(TAG, "auto bitrate up: ${autoKbps}kbps")
|
||||||
|
goodWindows = 0
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
goodWindows = 0
|
||||||
|
}
|
||||||
|
lossCount = 0
|
||||||
|
pktCount = 0
|
||||||
|
jitterAccum = 0.0
|
||||||
|
jitterN = 0
|
||||||
|
lastEvalTime = now
|
||||||
|
onRxStats?.invoke(lossPct, jitterMs)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Джиттер-гейт открыт: накопили кадры или вышло 300 мс с первого пакета. */
|
||||||
|
private fun gateOpen(): Boolean {
|
||||||
|
if (playStarted) return true
|
||||||
|
if (rxQueue.size >= jitterFrames) return true
|
||||||
|
return gateStart != 0L && System.currentTimeMillis() - gateStart >= 300
|
||||||
}
|
}
|
||||||
|
|
||||||
fun onAudioFlush() {
|
fun onAudioFlush() {
|
||||||
try {
|
try {
|
||||||
decoder?.flush()
|
// MediaCodec.flush() возвращает входные буферы, но уже выданные индексы
|
||||||
|
// остаются у нас в freeInputs и дублируются колбэками «повторной выдачи» —
|
||||||
|
// queueInputBuffer падает (index not owned by client) и кадры теряются.
|
||||||
|
// Надёжнее пересоздать декодер: колбэки старого отсекаются проверкой
|
||||||
|
// codec !== decoder.
|
||||||
player?.flush()
|
player?.flush()
|
||||||
rxQueue.clear()
|
rxQueue.clear()
|
||||||
|
receivedAny = false
|
||||||
|
playStarted = false
|
||||||
|
gateStart = 0L
|
||||||
onLevel(SRC_SPEAKER, 0f)
|
onLevel(SRC_SPEAKER, 0f)
|
||||||
|
restartDecoder()
|
||||||
} catch (_: Exception) {
|
} catch (_: Exception) {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Пересоздать только декодер (плеер и джиттер-буфер сохраняем). */
|
||||||
|
private fun restartDecoder() {
|
||||||
|
val dec = decoder
|
||||||
|
decoder = null
|
||||||
|
if (dec != null) {
|
||||||
|
try {
|
||||||
|
dec.stop()
|
||||||
|
} catch (_: Exception) {
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
dec.release()
|
||||||
|
} catch (_: Exception) {
|
||||||
|
}
|
||||||
|
}
|
||||||
|
val format = MediaFormat()
|
||||||
|
format.setString(MediaFormat.KEY_MIME, MediaFormat.MIMETYPE_AUDIO_OPUS)
|
||||||
|
format.setInteger(MediaFormat.KEY_SAMPLE_RATE, OUT_SAMPLE_RATE)
|
||||||
|
format.setInteger(MediaFormat.KEY_CHANNEL_COUNT, CHANNELS)
|
||||||
|
if (startDecoderCodec(format)) {
|
||||||
|
concealLogs = 0
|
||||||
|
dbgOut = 0
|
||||||
|
ptsCounter = 20_000L
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Один кадр тишины (20 мс) для скрытия потерь вместо паузы в звуке.
|
||||||
|
* Сгенерирован opuslib: 8 кГц, моно, 20 кбит/с, нули PCM.
|
||||||
|
*/
|
||||||
|
private fun silenceFrame(): ByteArray = byteArrayOf(
|
||||||
|
0x08.toByte(), 0x0B.toByte(), 0xE4.toByte(), 0xB9.toByte(),
|
||||||
|
0xA0.toByte(), 0xBC.toByte(), 0x84.toByte()
|
||||||
|
)
|
||||||
|
|
||||||
/** Заголовок OpusHead (csd-0) для декодера: Opus, 1 канал, 8 кГц, прескип 312. */
|
/** Заголовок OpusHead (csd-0) для декодера: Opus, 1 канал, 8 кГц, прескип 312. */
|
||||||
private fun opusHead(): ByteArray {
|
private fun opusHead(): ByteArray {
|
||||||
val head = "OpusHead".toByteArray(Charsets.US_ASCII)
|
val head = "OpusHead".toByteArray(Charsets.US_ASCII)
|
||||||
@@ -197,8 +465,12 @@ class OpusEngine(
|
|||||||
/** Остановить декодер и плеер (при отключении). */
|
/** Остановить декодер и плеер (при отключении). */
|
||||||
fun stopDecoder() {
|
fun stopDecoder() {
|
||||||
val dec = decoder
|
val dec = decoder
|
||||||
decoder = null // поток разбора выйдет из цикла до release
|
decoder = null
|
||||||
rxQueue.clear()
|
rxQueue.clear()
|
||||||
|
freeInputs.clear()
|
||||||
|
receivedAny = false
|
||||||
|
playStarted = false
|
||||||
|
gateStart = 0L
|
||||||
if (dec != null) {
|
if (dec != null) {
|
||||||
try {
|
try {
|
||||||
dec.stop()
|
dec.stop()
|
||||||
@@ -224,7 +496,7 @@ class OpusEngine(
|
|||||||
// ---------- Захват (TX) ----------
|
// ---------- Захват (TX) ----------
|
||||||
|
|
||||||
/** Начать PTT: запустить запись и кодирование. */
|
/** Начать PTT: запустить запись и кодирование. */
|
||||||
fun startCapture(onPacket: (ByteArray) -> Unit) {
|
fun startCapture(micGain: Float = 1.0f, onPacket: (ByteArray) -> Unit) {
|
||||||
if (encoding) return
|
if (encoding) return
|
||||||
val enc = createEncoder()
|
val enc = createEncoder()
|
||||||
encoder = enc
|
encoder = enc
|
||||||
@@ -247,7 +519,7 @@ class OpusEngine(
|
|||||||
rec.startRecording()
|
rec.startRecording()
|
||||||
encoding = true
|
encoding = true
|
||||||
val t = Thread({
|
val t = Thread({
|
||||||
captureLoop(enc, rec, onPacket)
|
captureLoop(enc, rec, micGain, onPacket)
|
||||||
}, "svx-capture")
|
}, "svx-capture")
|
||||||
t.isDaemon = true
|
t.isDaemon = true
|
||||||
recThread = t
|
recThread = t
|
||||||
@@ -260,18 +532,19 @@ class OpusEngine(
|
|||||||
fmt.setString(MediaFormat.KEY_MIME, MediaFormat.MIMETYPE_AUDIO_OPUS)
|
fmt.setString(MediaFormat.KEY_MIME, MediaFormat.MIMETYPE_AUDIO_OPUS)
|
||||||
fmt.setInteger(MediaFormat.KEY_SAMPLE_RATE, SAMPLE_RATE)
|
fmt.setInteger(MediaFormat.KEY_SAMPLE_RATE, SAMPLE_RATE)
|
||||||
fmt.setInteger(MediaFormat.KEY_CHANNEL_COUNT, CHANNELS)
|
fmt.setInteger(MediaFormat.KEY_CHANNEL_COUNT, CHANNELS)
|
||||||
fmt.setInteger(MediaFormat.KEY_BIT_RATE, BIT_RATE)
|
fmt.setInteger(MediaFormat.KEY_BIT_RATE, effectiveBitrate())
|
||||||
fmt.setInteger(MediaFormat.KEY_MAX_INPUT_SIZE, FRAME_SIZE * 2)
|
fmt.setInteger(MediaFormat.KEY_MAX_INPUT_SIZE, FRAME_SIZE * 2)
|
||||||
val codec = MediaCodec.createEncoderByType(MediaFormat.MIMETYPE_AUDIO_OPUS)
|
val codec = MediaCodec.createEncoderByType(MediaFormat.MIMETYPE_AUDIO_OPUS)
|
||||||
codec.configure(fmt, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE)
|
codec.configure(fmt, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE)
|
||||||
codec.start()
|
codec.start()
|
||||||
|
Log.d(TAG, "encoder started, bitrate=${effectiveBitrate() / 1000}kbps")
|
||||||
codec
|
codec
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
null
|
null
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun captureLoop(enc: MediaCodec, rec: AudioRecord, onPacket: (ByteArray) -> Unit) {
|
private fun captureLoop(enc: MediaCodec, rec: AudioRecord, micGain: Float, onPacket: (ByteArray) -> Unit) {
|
||||||
val pcmBuf = ByteBuffer.allocateDirect(FRAME_SIZE * 2).order(ByteOrder.LITTLE_ENDIAN)
|
val pcmBuf = ByteBuffer.allocateDirect(FRAME_SIZE * 2).order(ByteOrder.LITTLE_ENDIAN)
|
||||||
val micLevel = FloatArray(1)
|
val micLevel = FloatArray(1)
|
||||||
while (encoding) {
|
while (encoding) {
|
||||||
@@ -281,6 +554,14 @@ class OpusEngine(
|
|||||||
pcmBuf.limit(n)
|
pcmBuf.limit(n)
|
||||||
val pcm = ByteArray(n)
|
val pcm = ByteArray(n)
|
||||||
pcmBuf.get(pcm)
|
pcmBuf.get(pcm)
|
||||||
|
if (micGain != 1.0f) {
|
||||||
|
for (i in 0 until n step 2) {
|
||||||
|
val s = ((pcm[i + 1].toInt() shl 8) or (pcm[i].toInt() and 0xFF)).toShort()
|
||||||
|
val g = (s * micGain).toInt().coerceIn(-32768, 32767)
|
||||||
|
pcm[i] = (g and 0xFF).toByte()
|
||||||
|
pcm[i + 1] = ((g shr 8) and 0xFF).toByte()
|
||||||
|
}
|
||||||
|
}
|
||||||
micLevel[0] = pcmLevel(pcm)
|
micLevel[0] = pcmLevel(pcm)
|
||||||
onLevel(SRC_MIC, micLevel[0])
|
onLevel(SRC_MIC, micLevel[0])
|
||||||
try {
|
try {
|
||||||
@@ -308,14 +589,43 @@ class OpusEngine(
|
|||||||
} catch (_: Exception) {
|
} catch (_: Exception) {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
// Дренаж: отдаём пакеты, оставшиеся в кодере после остановки записи
|
||||||
|
try {
|
||||||
|
var outIdx = enc.dequeueOutputBuffer(encodeBufferInfo, 0)
|
||||||
|
while (outIdx >= 0) {
|
||||||
|
if (encodeBufferInfo.size > 0) {
|
||||||
|
val outBuf = ByteBuffer.allocate(encodeBufferInfo.size)
|
||||||
|
enc.getOutputBuffer(outIdx)?.also { src ->
|
||||||
|
src.position(encodeBufferInfo.offset)
|
||||||
|
src.limit(encodeBufferInfo.offset + encodeBufferInfo.size)
|
||||||
|
outBuf.put(src)
|
||||||
|
}
|
||||||
|
onPacket(outBuf.array())
|
||||||
|
}
|
||||||
|
enc.releaseOutputBuffer(outIdx, false)
|
||||||
|
outIdx = enc.dequeueOutputBuffer(encodeBufferInfo, 0)
|
||||||
|
}
|
||||||
|
} catch (_: Exception) {
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fun stopCapture() {
|
fun stopCapture() {
|
||||||
|
if (!encoding && recThread == null) return
|
||||||
encoding = false
|
encoding = false
|
||||||
try {
|
try {
|
||||||
recorder?.stop()
|
recorder?.stop()
|
||||||
} catch (_: Exception) {
|
} catch (_: Exception) {
|
||||||
}
|
}
|
||||||
|
// Ждём завершения потока захвата: он должен отправить последние пакеты,
|
||||||
|
// чтобы flush (окончание передачи) ушёл после всего аудио
|
||||||
|
val t = recThread
|
||||||
|
recThread = null
|
||||||
|
if (t != null && t.isAlive) {
|
||||||
|
try {
|
||||||
|
t.join(1000)
|
||||||
|
} catch (_: InterruptedException) {
|
||||||
|
}
|
||||||
|
}
|
||||||
try {
|
try {
|
||||||
recorder?.release()
|
recorder?.release()
|
||||||
} catch (_: Exception) {
|
} catch (_: Exception) {
|
||||||
@@ -330,8 +640,6 @@ class OpusEngine(
|
|||||||
} catch (_: Exception) {
|
} catch (_: Exception) {
|
||||||
}
|
}
|
||||||
encoder = null
|
encoder = null
|
||||||
recThread?.interrupt()
|
|
||||||
recThread = null
|
|
||||||
onLevel(SRC_MIC, 0f)
|
onLevel(SRC_MIC, 0f)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
183
app/src/main/java/ru/ua1zbe/svxremote/audio/RxRecorder.kt
Normal file
183
app/src/main/java/ru/ua1zbe/svxremote/audio/RxRecorder.kt
Normal file
@@ -0,0 +1,183 @@
|
|||||||
|
package ru.ua1zbe.svxremote.audio
|
||||||
|
|
||||||
|
import android.media.MediaCodec
|
||||||
|
import android.media.MediaCodecInfo
|
||||||
|
import android.media.MediaFormat
|
||||||
|
import android.media.MediaMuxer
|
||||||
|
import android.util.Log
|
||||||
|
import java.io.File
|
||||||
|
import java.nio.ByteBuffer
|
||||||
|
import java.time.LocalDateTime
|
||||||
|
import java.time.format.DateTimeFormatter
|
||||||
|
import java.util.concurrent.LinkedBlockingQueue
|
||||||
|
import java.util.concurrent.atomic.AtomicBoolean
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Запись декодированного RX-аудио (PCM 48 кГц моно 16 бит) в OGG/Opus.
|
||||||
|
* Тишина (отсутствие приёма) не пишется: во время пауз pts не продвигается,
|
||||||
|
* поэтому речь в файле склеивается без пропусков/пустых участков.
|
||||||
|
*/
|
||||||
|
class RxRecorder {
|
||||||
|
|
||||||
|
companion object {
|
||||||
|
const val TAG = "SVXRemote"
|
||||||
|
const val SAMPLE_RATE = 48000
|
||||||
|
const val CHANNELS = 1
|
||||||
|
}
|
||||||
|
|
||||||
|
@Volatile
|
||||||
|
private var muxer: MediaMuxer? = null
|
||||||
|
@Volatile
|
||||||
|
private var encoder: MediaCodec? = null
|
||||||
|
private val recording = AtomicBoolean(false)
|
||||||
|
private val queue = LinkedBlockingQueue<ByteArray>()
|
||||||
|
private var worker: Thread? = null
|
||||||
|
private var filePath = ""
|
||||||
|
// Накопленный pts (мкс). Растёт только при подаче реального аудио (без тишины).
|
||||||
|
private var ptsUs = 0L
|
||||||
|
private var trackIndex = -1
|
||||||
|
private var muxStarted = false
|
||||||
|
private var wroteAny = false
|
||||||
|
private val info = MediaCodec.BufferInfo()
|
||||||
|
|
||||||
|
fun isRecording(): Boolean = recording.get()
|
||||||
|
|
||||||
|
fun getFilePath(): String = filePath
|
||||||
|
|
||||||
|
/** Начать запись. dir — базовая директория (используется подкаталог recordings). */
|
||||||
|
fun start(dir: File): Boolean {
|
||||||
|
if (recording.get()) return true
|
||||||
|
val outDir = File(dir, "recordings")
|
||||||
|
if (!outDir.exists()) outDir.mkdirs()
|
||||||
|
val ts = LocalDateTime.now()
|
||||||
|
.format(DateTimeFormatter.ofPattern("yyyy-MM-dd_HH-mm-ss"))
|
||||||
|
val f = File(outDir, "rec_$ts.ogg")
|
||||||
|
filePath = f.absolutePath
|
||||||
|
val mux = try {
|
||||||
|
MediaMuxer(filePath, MediaMuxer.OutputFormat.MUXER_OUTPUT_OGG)
|
||||||
|
} catch (e: Exception) {
|
||||||
|
Log.e(TAG, "recorder muxer create failed: ${e.message}")
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
val fmt = MediaFormat()
|
||||||
|
fmt.setString(MediaFormat.KEY_MIME, MediaFormat.MIMETYPE_AUDIO_OPUS)
|
||||||
|
fmt.setInteger(MediaFormat.KEY_SAMPLE_RATE, SAMPLE_RATE)
|
||||||
|
fmt.setInteger(MediaFormat.KEY_CHANNEL_COUNT, CHANNELS)
|
||||||
|
fmt.setInteger(MediaFormat.KEY_BIT_RATE, 32000)
|
||||||
|
fmt.setInteger(MediaFormat.KEY_MAX_INPUT_SIZE, 1920)
|
||||||
|
val enc = try {
|
||||||
|
MediaCodec.createEncoderByType(MediaFormat.MIMETYPE_AUDIO_OPUS).also {
|
||||||
|
it.configure(fmt, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE)
|
||||||
|
it.start()
|
||||||
|
}
|
||||||
|
} catch (e: Exception) {
|
||||||
|
Log.e(TAG, "recorder encoder create failed: ${e.message}")
|
||||||
|
try { mux.release() } catch (_: Exception) {}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
muxer = mux
|
||||||
|
encoder = enc
|
||||||
|
trackIndex = -1
|
||||||
|
muxStarted = false
|
||||||
|
ptsUs = 0L
|
||||||
|
queue.clear()
|
||||||
|
recording.set(true)
|
||||||
|
worker = Thread({ workerLoop() }, "rx-recorder").also { it.isDaemon = true; it.start() }
|
||||||
|
Log.d(TAG, "recorder started -> $filePath")
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Подача декодированного PCM. isReal == false (тишина/скрытие потерь) — не пишем. */
|
||||||
|
fun feed(pcm: ByteArray, isReal: Boolean) {
|
||||||
|
if (!recording.get() || !isReal) return
|
||||||
|
queue.offer(pcm)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun workerLoop() {
|
||||||
|
val enc = encoder ?: return
|
||||||
|
val mux = muxer ?: return
|
||||||
|
val timeout = 1000L
|
||||||
|
try {
|
||||||
|
while (recording.get() || queue.isNotEmpty()) {
|
||||||
|
val pcm = queue.poll()
|
||||||
|
if (pcm != null) {
|
||||||
|
var inIdx = enc.dequeueInputBuffer(timeout)
|
||||||
|
if (inIdx >= 0) {
|
||||||
|
val buf = enc.getInputBuffer(inIdx) ?: continue
|
||||||
|
buf.clear()
|
||||||
|
buf.put(pcm)
|
||||||
|
val pts = ptsUs
|
||||||
|
enc.queueInputBuffer(inIdx, 0, pcm.size, pts, 0)
|
||||||
|
// Продвигаем pts только для реального аудио (без тишины)
|
||||||
|
ptsUs += (pcm.size / 2) * 1_000_000L / SAMPLE_RATE
|
||||||
|
} else {
|
||||||
|
queue.offer(pcm)
|
||||||
|
Thread.sleep(2)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
drainEncoder(enc, mux, false)
|
||||||
|
if (!recording.get() && queue.isEmpty()) break
|
||||||
|
}
|
||||||
|
} catch (e: Exception) {
|
||||||
|
Log.e(TAG, "recorder worker error: ${e.message}")
|
||||||
|
} finally {
|
||||||
|
// Дренаж остатков после остановки
|
||||||
|
try {
|
||||||
|
drainEncoder(enc, mux, true)
|
||||||
|
} catch (_: Exception) {
|
||||||
|
}
|
||||||
|
try { enc.stop() } catch (_: Exception) {}
|
||||||
|
try { enc.release() } catch (_: Exception) {}
|
||||||
|
if (muxStarted) {
|
||||||
|
try { mux.stop() } catch (_: Exception) {}
|
||||||
|
}
|
||||||
|
try { mux.release() } catch (_: Exception) {}
|
||||||
|
encoder = null
|
||||||
|
muxer = null
|
||||||
|
Log.d(TAG, "recorder stopped -> $filePath")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun drainEncoder(enc: MediaCodec, mux: MediaMuxer, drainAll: Boolean) {
|
||||||
|
val timeout = if (drainAll) 0L else 1000L
|
||||||
|
var outIdx = enc.dequeueOutputBuffer(info, timeout)
|
||||||
|
while (outIdx >= 0) {
|
||||||
|
if (info.size > 0) {
|
||||||
|
if (trackIndex < 0) {
|
||||||
|
trackIndex = mux.addTrack(enc.outputFormat)
|
||||||
|
mux.start()
|
||||||
|
muxStarted = true
|
||||||
|
Log.d(TAG, "recorder muxer track added, started")
|
||||||
|
}
|
||||||
|
val outBuf = enc.getOutputBuffer(outIdx) ?: run {
|
||||||
|
enc.releaseOutputBuffer(outIdx, false)
|
||||||
|
outIdx = enc.dequeueOutputBuffer(info, timeout)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
outBuf.position(info.offset)
|
||||||
|
outBuf.limit(info.offset + info.size)
|
||||||
|
mux.writeSampleData(trackIndex, outBuf, info)
|
||||||
|
wroteAny = true
|
||||||
|
}
|
||||||
|
enc.releaseOutputBuffer(outIdx, false)
|
||||||
|
outIdx = enc.dequeueOutputBuffer(info, timeout)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun stop() {
|
||||||
|
if (!recording.get()) return
|
||||||
|
recording.set(false)
|
||||||
|
val w = worker
|
||||||
|
if (w != null && w.isAlive) {
|
||||||
|
try { w.join(4000) } catch (_: InterruptedException) {}
|
||||||
|
}
|
||||||
|
worker = null
|
||||||
|
// Если ни одного кадра не записалось (весь сеанс — тишина) — удаляем пустой файл.
|
||||||
|
if (!wroteAny) {
|
||||||
|
try {
|
||||||
|
val f = File(filePath)
|
||||||
|
if (f.exists()) f.delete()
|
||||||
|
} catch (_: Exception) {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -8,31 +8,174 @@ data class ConnectionSettings(
|
|||||||
val port: Int,
|
val port: Int,
|
||||||
val callsign: String,
|
val callsign: String,
|
||||||
val authKey: String,
|
val authKey: String,
|
||||||
val talkGroup: Long
|
val talkGroup: Long,
|
||||||
|
val groups: List<Long> = emptyList()
|
||||||
|
)
|
||||||
|
|
||||||
|
/** Профиль настроек: имя + параметры подключения. */
|
||||||
|
data class Profile(
|
||||||
|
val name: String,
|
||||||
|
val settings: ConnectionSettings
|
||||||
)
|
)
|
||||||
|
|
||||||
object Prefs {
|
object Prefs {
|
||||||
private const val PREFS_NAME = "svxremote"
|
private const val PREFS_NAME = "svxremote"
|
||||||
|
const val PROFILE_COUNT = 5
|
||||||
|
|
||||||
fun load(context: Context): ConnectionSettings {
|
private fun sp(context: Context): SharedPreferences =
|
||||||
val sp = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)
|
context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)
|
||||||
return ConnectionSettings(
|
|
||||||
host = sp.getString("host", "") ?: "",
|
/** Индекс активного профиля (0..PROFILE_COUNT-1). */
|
||||||
port = sp.getInt("port", 5300),
|
fun activeProfileIndex(context: Context): Int =
|
||||||
callsign = sp.getString("callsign", "") ?: "",
|
sp(context).getInt("active_profile", 0).coerceIn(0, PROFILE_COUNT - 1)
|
||||||
authKey = sp.getString("auth_key", "") ?: "",
|
|
||||||
talkGroup = sp.getLong("tg", 11)
|
fun setActiveProfile(context: Context, index: Int) {
|
||||||
|
sp(context).edit().putInt("active_profile", index.coerceIn(0, PROFILE_COUNT - 1)).apply()
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Настройки активного профиля. */
|
||||||
|
fun load(context: Context): ConnectionSettings =
|
||||||
|
loadProfile(context, activeProfileIndex(context)).settings
|
||||||
|
|
||||||
|
/** Сохранить в активный профиль. */
|
||||||
|
fun save(context: Context, s: ConnectionSettings) {
|
||||||
|
val index = activeProfileIndex(context)
|
||||||
|
val profile = loadProfile(context, index)
|
||||||
|
saveProfile(context, index, Profile(profile.name, s))
|
||||||
|
}
|
||||||
|
|
||||||
|
fun loadProfile(context: Context, index: Int): Profile =
|
||||||
|
loadProfile(sp(context), index.coerceIn(0, PROFILE_COUNT - 1))
|
||||||
|
|
||||||
|
fun saveProfile(context: Context, index: Int, profile: Profile) {
|
||||||
|
val profiles = loadProfiles(context)
|
||||||
|
profiles[index.coerceIn(0, PROFILE_COUNT - 1)] = profile
|
||||||
|
saveProfiles(context, profiles)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Все профили (5 слотов). */
|
||||||
|
fun loadProfiles(context: Context): MutableList<Profile> {
|
||||||
|
val prefs = sp(context)
|
||||||
|
migrateIfNeeded(context, prefs)
|
||||||
|
return (0 until PROFILE_COUNT).map { loadProfile(prefs, it) }.toMutableList()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun loadProfile(prefs: SharedPreferences, i: Int): Profile {
|
||||||
|
val host = prefs.getString("p${i}_host", null)
|
||||||
|
if (host == null) {
|
||||||
|
return Profile("Профиль ${i + 1}", ConnectionSettings("", 5300, "", "", 11))
|
||||||
|
}
|
||||||
|
return Profile(
|
||||||
|
name = prefs.getString("p${i}_name", null) ?: "Профиль ${i + 1}",
|
||||||
|
settings = ConnectionSettings(
|
||||||
|
host = host,
|
||||||
|
port = prefs.getInt("p${i}_port", 5300),
|
||||||
|
callsign = prefs.getString("p${i}_callsign", "") ?: "",
|
||||||
|
authKey = prefs.getString("p${i}_auth", "") ?: "",
|
||||||
|
talkGroup = prefs.getLong("p${i}_tg", 11),
|
||||||
|
groups = (prefs.getString("p${i}_groups", "") ?: "")
|
||||||
|
.split(',')
|
||||||
|
.mapNotNull { it.trim().toLongOrNull() }
|
||||||
|
.distinct()
|
||||||
|
)
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
fun save(context: Context, s: ConnectionSettings) {
|
private fun saveProfiles(context: Context, profiles: List<Profile>) {
|
||||||
val sp: SharedPreferences = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)
|
val e = sp(context).edit()
|
||||||
sp.edit()
|
profiles.forEachIndexed { i, p ->
|
||||||
.putString("host", s.host.trim())
|
e.putString("p${i}_name", p.name)
|
||||||
.putInt("port", s.port)
|
.putString("p${i}_host", p.settings.host.trim())
|
||||||
.putString("callsign", s.callsign.trim())
|
.putInt("p${i}_port", p.settings.port)
|
||||||
.putString("auth_key", s.authKey)
|
.putString("p${i}_callsign", p.settings.callsign.trim())
|
||||||
.putLong("tg", s.talkGroup)
|
.putString("p${i}_auth", p.settings.authKey)
|
||||||
.apply()
|
.putLong("p${i}_tg", p.settings.talkGroup)
|
||||||
|
.putString("p${i}_groups", p.settings.groups.distinct().joinToString(","))
|
||||||
|
}
|
||||||
|
e.apply()
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Перенос старых настроек (до v1.0.6) в профиль 1 — один раз. */
|
||||||
|
private fun migrateIfNeeded(context: Context, prefs: SharedPreferences) {
|
||||||
|
if (prefs.getBoolean("migrated_v106", false)) return
|
||||||
|
val host = prefs.getString("host", null)
|
||||||
|
if (host != null) {
|
||||||
|
val legacy = ConnectionSettings(
|
||||||
|
host = host,
|
||||||
|
port = prefs.getInt("port", 5300),
|
||||||
|
callsign = prefs.getString("callsign", "") ?: "",
|
||||||
|
authKey = prefs.getString("auth_key", "") ?: "",
|
||||||
|
talkGroup = prefs.getLong("tg", 11),
|
||||||
|
groups = (prefs.getString("groups", "") ?: "")
|
||||||
|
.split(',')
|
||||||
|
.mapNotNull { it.trim().toLongOrNull() }
|
||||||
|
.distinct()
|
||||||
|
.ifEmpty { listOf(9L, 11L, 12L, 13L) }
|
||||||
|
)
|
||||||
|
val profiles = (0 until PROFILE_COUNT).map { loadProfile(prefs, it) }.toMutableList()
|
||||||
|
profiles[0] = Profile("Профиль 1", legacy)
|
||||||
|
saveProfiles(context, profiles)
|
||||||
|
}
|
||||||
|
prefs.edit().putBoolean("migrated_v106", true).apply()
|
||||||
|
}
|
||||||
|
|
||||||
|
fun nodeToastsEnabled(context: Context): Boolean {
|
||||||
|
return sp(context).getBoolean("node_toasts", true)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun setNodeToastsEnabled(context: Context, enabled: Boolean) {
|
||||||
|
sp(context).edit().putBoolean("node_toasts", enabled).apply()
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- APRS метеостанции (экспериментально) ----------
|
||||||
|
|
||||||
|
/** Координаты "lat,lon" (пусто = функция выключена). */
|
||||||
|
fun aprsCoords(context: Context): String =
|
||||||
|
sp(context).getString("aprs_coords", "") ?: ""
|
||||||
|
|
||||||
|
fun setAprsCoords(context: Context, coords: String) {
|
||||||
|
sp(context).edit().putString("aprs_coords", coords.trim()).apply()
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Усиление микрофона (1.0 = без усиления). */
|
||||||
|
fun micGain(context: Context): Float =
|
||||||
|
sp(context).getFloat("mic_gain", 1.0f)
|
||||||
|
|
||||||
|
fun setMicGain(context: Context, gain: Float) {
|
||||||
|
sp(context).edit().putFloat("mic_gain", gain.coerceIn(0.5f, 5.0f)).apply()
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- Скрытые настройки звука (AudioSettingsActivity) ----------
|
||||||
|
|
||||||
|
/** Буфер воспроизведения RX, мс. */
|
||||||
|
fun rxBufferMs(context: Context): Int =
|
||||||
|
sp(context).getInt("rx_buffer_ms", 417)
|
||||||
|
|
||||||
|
fun setRxBufferMs(context: Context, ms: Int) {
|
||||||
|
sp(context).edit().putInt("rx_buffer_ms", ms.coerceIn(100, 600)).apply()
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Накопление перед стартом воспроизведения, мс (кратно 20). */
|
||||||
|
fun rxJitterMs(context: Context): Int =
|
||||||
|
sp(context).getInt("rx_jitter_ms", 200)
|
||||||
|
|
||||||
|
fun setRxJitterMs(context: Context, ms: Int) {
|
||||||
|
sp(context).edit().putInt("rx_jitter_ms", ms.coerceIn(0, 400)).apply()
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Скорость передачи Opus, кбит/с. 0 = Авто (адаптация под интернет). */
|
||||||
|
fun txBitrateKbps(context: Context): Int =
|
||||||
|
sp(context).getInt("tx_bitrate_kbps", 0)
|
||||||
|
|
||||||
|
fun setTxBitrateKbps(context: Context, kbps: Int) {
|
||||||
|
sp(context).edit().putInt("tx_bitrate_kbps", kbps.coerceIn(0, 32)).apply()
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Показывать строку статистики приёма (потери/джиттер) на главном экране. */
|
||||||
|
fun rxStatsEnabled(context: Context): Boolean =
|
||||||
|
sp(context).getBoolean("rx_stats_enabled", true)
|
||||||
|
|
||||||
|
fun setRxStatsEnabled(context: Context, enabled: Boolean) {
|
||||||
|
sp(context).edit().putBoolean("rx_stats_enabled", enabled).apply()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,5 +1,6 @@
|
|||||||
package ru.ua1zbe.svxremote.proto
|
package ru.ua1zbe.svxremote.proto
|
||||||
|
|
||||||
|
import android.util.Log
|
||||||
import java.net.DatagramPacket
|
import java.net.DatagramPacket
|
||||||
import java.net.DatagramSocket
|
import java.net.DatagramSocket
|
||||||
import java.net.InetAddress
|
import java.net.InetAddress
|
||||||
@@ -7,7 +8,7 @@ import java.net.InetSocketAddress
|
|||||||
import java.net.Socket
|
import java.net.Socket
|
||||||
import java.net.SocketTimeoutException
|
import java.net.SocketTimeoutException
|
||||||
import java.util.concurrent.atomic.AtomicBoolean
|
import java.util.concurrent.atomic.AtomicBoolean
|
||||||
import android.util.Log
|
import ru.ua1zbe.svxremote.BuildConfig
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Клиент рефлектора SVXLink (протокол v2, авторизация AUTH_KEY, аудио Opus по UDP).
|
* Клиент рефлектора SVXLink (протокол v2, авторизация AUTH_KEY, аудио Opus по UDP).
|
||||||
@@ -23,8 +24,8 @@ class ReflectorClient(
|
|||||||
fun onServerInfo(info: MsgParser.ServerInfo)
|
fun onServerInfo(info: MsgParser.ServerInfo)
|
||||||
fun onTalkerStart(tg: Long, callsign: String)
|
fun onTalkerStart(tg: Long, callsign: String)
|
||||||
fun onTalkerStop(tg: Long, callsign: String)
|
fun onTalkerStop(tg: Long, callsign: String)
|
||||||
fun onNodeJoined(callsign: String)
|
fun onNodeJoined(callsign: String, tg: Long?)
|
||||||
fun onNodeLeft(callsign: String)
|
fun onNodeLeft(callsign: String, tg: Long?)
|
||||||
/** Входящий аудиопакет Opus. */
|
/** Входящий аудиопакет Opus. */
|
||||||
fun onAudioPacket(packet: ByteArray, seq: Int)
|
fun onAudioPacket(packet: ByteArray, seq: Int)
|
||||||
fun onAudioFlush()
|
fun onAudioFlush()
|
||||||
@@ -50,7 +51,9 @@ class ReflectorClient(
|
|||||||
const val RECONNECT_DELAY_MS = 5000L
|
const val RECONNECT_DELAY_MS = 5000L
|
||||||
|
|
||||||
const val CLIENT_SW_INFO = "SVXHomyak"
|
const val CLIENT_SW_INFO = "SVXHomyak"
|
||||||
const val CLIENT_SW_VERSION = "1.0.0"
|
// Версия ПО передаётся на сервер для дашборда; берём из BuildConfig,
|
||||||
|
// чтобы не расходилась с versionName в build.gradle.kts
|
||||||
|
val CLIENT_SW_VERSION = BuildConfig.VERSION_NAME
|
||||||
}
|
}
|
||||||
|
|
||||||
data class Settings(
|
data class Settings(
|
||||||
@@ -58,7 +61,9 @@ class ReflectorClient(
|
|||||||
val port: Int,
|
val port: Int,
|
||||||
val callsign: String,
|
val callsign: String,
|
||||||
val authKey: String,
|
val authKey: String,
|
||||||
val talkGroup: Long
|
val talkGroup: Long,
|
||||||
|
/** Список групп для мониторинга; null = обычный режим (своя группа). */
|
||||||
|
val monitorTgs: List<Long>? = null
|
||||||
)
|
)
|
||||||
|
|
||||||
@Volatile
|
@Volatile
|
||||||
@@ -99,10 +104,15 @@ class ReflectorClient(
|
|||||||
|
|
||||||
@Synchronized
|
@Synchronized
|
||||||
fun connect(settings: Settings) {
|
fun connect(settings: Settings) {
|
||||||
if (running.get()) return
|
|
||||||
this.settings = settings
|
this.settings = settings
|
||||||
manualDisconnect.set(false)
|
manualDisconnect.set(false)
|
||||||
fatal = false
|
fatal = false
|
||||||
|
if (running.get()) {
|
||||||
|
// Перезапуск с новыми настройками (например, смена профиля)
|
||||||
|
running.set(false)
|
||||||
|
synchronized(stopEvent) { stopEvent.notifyAll() }
|
||||||
|
abortSockets()
|
||||||
|
}
|
||||||
running.set(true)
|
running.set(true)
|
||||||
state = STATE_DISCONNECTED
|
state = STATE_DISCONNECTED
|
||||||
seqCounter = 0
|
seqCounter = 0
|
||||||
@@ -151,12 +161,46 @@ class ReflectorClient(
|
|||||||
udpSend(sock, s, data)
|
udpSend(sock, s, data)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Переключить принимаемую группу на живом соединении. */
|
||||||
|
fun selectGroup(tg: Long) {
|
||||||
|
val sock = tcpSocket
|
||||||
|
if (sock == null || !running.get()) {
|
||||||
|
Log.d(TAG, "selectGroup tg=$tg skipped (sock=${sock != null} running=${running.get()})")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
Log.d(TAG, "selectGroup tg=$tg")
|
||||||
|
sendTcp(sock, MsgBuilder.selectTg(tg))
|
||||||
|
} catch (e: Exception) {
|
||||||
|
Log.w(TAG, "selectGroup send failed: ${e.javaClass.simpleName}: ${e.message}")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Переключить группы мониторинга на живом соединении. */
|
||||||
|
fun setMonitorTgs(tgs: List<Long>) {
|
||||||
|
val sock = tcpSocket
|
||||||
|
if (sock == null || !running.get()) {
|
||||||
|
Log.d(TAG, "setMonitorTgs $tgs skipped (sock=${sock != null} running=${running.get()})")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
Log.d(TAG, "setMonitorTgs $tgs")
|
||||||
|
sendTcp(sock, MsgBuilder.tgMonitor(tgs))
|
||||||
|
} catch (e: Exception) {
|
||||||
|
Log.w(TAG, "setMonitorTgs failed: ${e.javaClass.simpleName}: ${e.message}")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/** Конец передачи. */
|
/** Конец передачи. */
|
||||||
fun sendAudioFlush() {
|
fun sendAudioFlush() {
|
||||||
val sock = udpSocket
|
val sock = udpSocket
|
||||||
val s = settings
|
val s = settings
|
||||||
val id = clientId
|
val id = clientId
|
||||||
if (sock == null || s == null || id == 0) return
|
if (sock == null || s == null || id == 0) {
|
||||||
|
Log.w(TAG, "sendAudioFlush skipped (sock=${sock != null} s=${s != null} id=$id)")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
Log.d(TAG, "sendAudioFlush")
|
||||||
udpSend(sock, s, MsgBuilder.udpFlush(id, nextSeq()))
|
udpSend(sock, s, MsgBuilder.udpFlush(id, nextSeq()))
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -361,19 +405,28 @@ class ReflectorClient(
|
|||||||
// (иначе сервер не шлёт аудио группы и не показывает
|
// (иначе сервер не шлёт аудио группы и не показывает
|
||||||
// подписку в статусе: monitoredTGs остаётся пустым).
|
// подписку в статусе: monitoredTGs остаётся пустым).
|
||||||
sendTcp(socket, MsgBuilder.nodeInfo(CLIENT_SW_INFO, CLIENT_SW_VERSION))
|
sendTcp(socket, MsgBuilder.nodeInfo(CLIENT_SW_INFO, CLIENT_SW_VERSION))
|
||||||
|
val monitor = s.monitorTgs
|
||||||
|
if (monitor.isNullOrEmpty()) {
|
||||||
sendTcp(socket, MsgBuilder.selectTg(s.talkGroup))
|
sendTcp(socket, MsgBuilder.selectTg(s.talkGroup))
|
||||||
sendTcp(socket, MsgBuilder.tgMonitor(listOf(s.talkGroup)))
|
sendTcp(socket, MsgBuilder.tgMonitor(listOf(s.talkGroup)))
|
||||||
|
} else {
|
||||||
|
// Мониторинг: сидим на базовой группе и слушаем
|
||||||
|
// уведомления обо всех группах (аудио идёт только
|
||||||
|
// с выбранной, поэтому переключение — в MainActivity).
|
||||||
|
sendTcp(socket, MsgBuilder.selectTg(s.talkGroup))
|
||||||
|
sendTcp(socket, MsgBuilder.tgMonitor(monitor))
|
||||||
|
}
|
||||||
openUdp(s)
|
openUdp(s)
|
||||||
}
|
}
|
||||||
|
|
||||||
ReflectorProtocol.MSG_NODE_JOINED -> {
|
ReflectorProtocol.MSG_NODE_JOINED -> {
|
||||||
val cs = parseSimpleString(msg.fields)
|
val (cs, tg) = parseNodeEvent(msg.fields)
|
||||||
callbacks.onNodeJoined(cs)
|
callbacks.onNodeJoined(cs, tg)
|
||||||
}
|
}
|
||||||
|
|
||||||
ReflectorProtocol.MSG_NODE_LEFT -> {
|
ReflectorProtocol.MSG_NODE_LEFT -> {
|
||||||
val cs = parseSimpleString(msg.fields)
|
val (cs, tg) = parseNodeEvent(msg.fields)
|
||||||
callbacks.onNodeLeft(cs)
|
callbacks.onNodeLeft(cs, tg)
|
||||||
}
|
}
|
||||||
|
|
||||||
ReflectorProtocol.MSG_TALKER_START -> {
|
ReflectorProtocol.MSG_TALKER_START -> {
|
||||||
@@ -388,6 +441,7 @@ class ReflectorClient(
|
|||||||
|
|
||||||
ReflectorProtocol.MSG_ERROR -> {
|
ReflectorProtocol.MSG_ERROR -> {
|
||||||
val err = MsgParser.errorMessage(msg.fields)
|
val err = MsgParser.errorMessage(msg.fields)
|
||||||
|
Log.w(TAG, "MSG_ERROR: $err")
|
||||||
if (state < STATE_READY) {
|
if (state < STATE_READY) {
|
||||||
stopFatal(err.ifEmpty { "Access denied" })
|
stopFatal(err.ifEmpty { "Access denied" })
|
||||||
return false
|
return false
|
||||||
@@ -404,6 +458,17 @@ class ReflectorClient(
|
|||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private fun parseNodeEvent(fields: ByteArray): Pair<String, Long?> {
|
||||||
|
return try {
|
||||||
|
val r = BinReader(fields)
|
||||||
|
val cs = r.str().ifEmpty { "?" }
|
||||||
|
val tg = try { r.str().toLongOrNull() } catch (_: Exception) { null }
|
||||||
|
cs to tg
|
||||||
|
} catch (_: Exception) {
|
||||||
|
"?" to null
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private fun parseSimpleString(fields: ByteArray): String {
|
private fun parseSimpleString(fields: ByteArray): String {
|
||||||
return try {
|
return try {
|
||||||
BinReader(fields).str().ifEmpty { "?" }
|
BinReader(fields).str().ifEmpty { "?" }
|
||||||
@@ -436,6 +501,7 @@ class ReflectorClient(
|
|||||||
stopUdp()
|
stopUdp()
|
||||||
val ds = DatagramSocket()
|
val ds = DatagramSocket()
|
||||||
udpSocket = ds
|
udpSocket = ds
|
||||||
|
Log.d(TAG, "UDP bound port=${ds.localPort}")
|
||||||
// Первый пакет регистрирует наш UDP-адрес у сервера
|
// Первый пакет регистрирует наш UDP-адрес у сервера
|
||||||
val addr = resolvedAddr ?: InetAddress.getByName(s.host)
|
val addr = resolvedAddr ?: InetAddress.getByName(s.host)
|
||||||
sendRawUdp(ds, addr, s.port, MsgBuilder.udpHeartbeat(clientId, nextSeq()))
|
sendRawUdp(ds, addr, s.port, MsgBuilder.udpHeartbeat(clientId, nextSeq()))
|
||||||
@@ -475,15 +541,15 @@ class ReflectorClient(
|
|||||||
if (data.size < 6) return
|
if (data.size < 6) return
|
||||||
val r = BinReader(data)
|
val r = BinReader(data)
|
||||||
val type = r.u16()
|
val type = r.u16()
|
||||||
r.u16() // client id
|
val cid = r.u16() // client id
|
||||||
val seq = r.u16()
|
val seq = r.u16()
|
||||||
val payload = data.copyOfRange(6, data.size)
|
val payload = data.copyOfRange(6, data.size)
|
||||||
when (type) {
|
when (type) {
|
||||||
ReflectorProtocol.MSG_UDP_HEARTBEAT -> Unit
|
ReflectorProtocol.MSG_UDP_HEARTBEAT -> Log.d(TAG, "UDP RX heartbeat")
|
||||||
ReflectorProtocol.MSG_UDP_AUDIO -> {
|
ReflectorProtocol.MSG_UDP_AUDIO -> {
|
||||||
val audio = MsgParser.udpAudio(payload)
|
val audio = MsgParser.udpAudio(payload)
|
||||||
if (audio != null && audio.isNotEmpty()) {
|
if (audio != null && audio.isNotEmpty()) {
|
||||||
Log.d(TAG, "UDP RX audio seq=$seq len=${audio.size}")
|
Log.d(TAG, "UDP RX audio seq=$seq cid=$cid len=${audio.size}")
|
||||||
callbacks.onAudioPacket(audio, seq)
|
callbacks.onAudioPacket(audio, seq)
|
||||||
} else {
|
} else {
|
||||||
Log.w(TAG, "UDP RX audio empty/null len=${payload.size}")
|
Log.w(TAG, "UDP RX audio empty/null len=${payload.size}")
|
||||||
@@ -493,7 +559,7 @@ class ReflectorClient(
|
|||||||
Log.d(TAG, "UDP RX flush")
|
Log.d(TAG, "UDP RX flush")
|
||||||
callbacks.onAudioFlush()
|
callbacks.onAudioFlush()
|
||||||
}
|
}
|
||||||
ReflectorProtocol.MSG_UDP_ALL_SAMPLES_FLUSHED -> Unit
|
ReflectorProtocol.MSG_UDP_ALL_SAMPLES_FLUSHED -> Log.d(TAG, "UDP RX all-flushed seq=$seq")
|
||||||
else -> Log.d(TAG, "UDP RX type=$type len=${data.size}")
|
else -> Log.d(TAG, "UDP RX type=$type len=${data.size}")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -517,10 +583,16 @@ class ReflectorClient(
|
|||||||
}
|
}
|
||||||
|
|
||||||
private fun sendRawUdp(sock: DatagramSocket, addr: InetAddress, port: Int, data: ByteArray) {
|
private fun sendRawUdp(sock: DatagramSocket, addr: InetAddress, port: Int, data: ByteArray) {
|
||||||
if (sock.isClosed) return
|
if (sock.isClosed) {
|
||||||
|
Log.w(TAG, "UDP TX skipped: socket closed")
|
||||||
|
return
|
||||||
|
}
|
||||||
try {
|
try {
|
||||||
sock.send(DatagramPacket(data, data.size, addr, port))
|
sock.send(DatagramPacket(data, data.size, addr, port))
|
||||||
|
val typ = if (data.size >= 2) ((data[0].toInt() shl 8) or (data[1].toInt() and 0xFF)) else -1
|
||||||
|
Log.d(TAG, "UDP TX type=$typ len=${data.size}")
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
|
Log.e(TAG, "UDP send error: ${e.message}", e)
|
||||||
callbacks.onError("UDP send: ${e.message}")
|
callbacks.onError("UDP send: ${e.message}")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -195,9 +195,11 @@ object MsgBuilder {
|
|||||||
return RcMessage(ReflectorProtocol.MSG_TG_MONITOR, w.toByteArray())
|
return RcMessage(ReflectorProtocol.MSG_TG_MONITOR, w.toByteArray())
|
||||||
}
|
}
|
||||||
|
|
||||||
/** MsgNodeInfo v2: JSON-строка с данными клиента (версия ПО и пр.). */
|
/** MsgNodeInfo v2: JSON-строка с данными клиента (версия ПО и пр.).
|
||||||
|
* Рефлектор вливает JSON в статус узла, дашборд показывает поле
|
||||||
|
* «swVer» (как у svxlink-узлов). */
|
||||||
fun nodeInfo(swInfo: String, swVersion: String): RcMessage {
|
fun nodeInfo(swInfo: String, swVersion: String): RcMessage {
|
||||||
val json = "{\"swInfo\":\"$swInfo\",\"swVersion\":\"$swVersion\"}"
|
val json = "{\"swInfo\":\"$swInfo\",\"swVer\":\"$swVersion\"}"
|
||||||
return RcMessage(ReflectorProtocol.MSG_NODE_INFO, BinWriter().str(json).toByteArray())
|
return RcMessage(ReflectorProtocol.MSG_NODE_INFO, BinWriter().str(json).toByteArray())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -3,15 +3,18 @@ package ru.ua1zbe.svxremote.ui
|
|||||||
import android.content.Context
|
import android.content.Context
|
||||||
import android.graphics.Canvas
|
import android.graphics.Canvas
|
||||||
import android.graphics.Color
|
import android.graphics.Color
|
||||||
|
import android.graphics.LinearGradient
|
||||||
import android.graphics.Paint
|
import android.graphics.Paint
|
||||||
import android.graphics.Path
|
import android.graphics.Path
|
||||||
|
import android.graphics.Shader
|
||||||
import android.util.AttributeSet
|
import android.util.AttributeSet
|
||||||
import android.view.MotionEvent
|
import android.view.MotionEvent
|
||||||
import android.view.View
|
import android.view.View
|
||||||
import ru.ua1zbe.svxremote.R
|
import ru.ua1zbe.svxremote.R
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Большая круглая кнопка PTT. Удерживание — передача.
|
* Большая круглая кнопка PTT в стиле Zello: градиентная заливка с глянцем,
|
||||||
|
* мягкая тень (плавающая кнопка) и тонкий ободок.
|
||||||
* Состояния: idle (синяя), нажата (красная), отключена (серая).
|
* Состояния: idle (синяя), нажата (красная), отключена (серая).
|
||||||
*/
|
*/
|
||||||
class PttButton @JvmOverloads constructor(
|
class PttButton @JvmOverloads constructor(
|
||||||
@@ -19,8 +22,11 @@ class PttButton @JvmOverloads constructor(
|
|||||||
attrs: AttributeSet? = null
|
attrs: AttributeSet? = null
|
||||||
) : View(context, attrs) {
|
) : View(context, attrs) {
|
||||||
|
|
||||||
private val paint = Paint(Paint.ANTI_ALIAS_FLAG)
|
private val fillPaint = Paint(Paint.ANTI_ALIAS_FLAG)
|
||||||
private val ringPaint = Paint(Paint.ANTI_ALIAS_FLAG)
|
private val ringPaint = Paint(Paint.ANTI_ALIAS_FLAG)
|
||||||
|
private val glossPaint = Paint(Paint.ANTI_ALIAS_FLAG)
|
||||||
|
private val micPaint = Paint(Paint.ANTI_ALIAS_FLAG)
|
||||||
|
private val clip = Path()
|
||||||
|
|
||||||
private var radius = 0f
|
private var radius = 0f
|
||||||
private var centerX = 0f
|
private var centerX = 0f
|
||||||
@@ -31,7 +37,6 @@ class PttButton @JvmOverloads constructor(
|
|||||||
set(value) {
|
set(value) {
|
||||||
field = value
|
field = value
|
||||||
if (!value) setPressed(false)
|
if (!value) setPressed(false)
|
||||||
refreshColors()
|
|
||||||
invalidate()
|
invalidate()
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -50,22 +55,28 @@ class PttButton @JvmOverloads constructor(
|
|||||||
}
|
}
|
||||||
|
|
||||||
init {
|
init {
|
||||||
|
fillPaint.style = Paint.Style.FILL
|
||||||
|
fillPaint.setShadowLayer(dp(8).toFloat(), 0f, dp(4).toFloat(), Color.argb(80, 0, 0, 0))
|
||||||
ringPaint.style = Paint.Style.STROKE
|
ringPaint.style = Paint.Style.STROKE
|
||||||
ringPaint.strokeWidth = dp(3).toFloat()
|
ringPaint.strokeWidth = dp(2).toFloat()
|
||||||
ringPaint.color = Color.parseColor("#3D444D")
|
glossPaint.style = Paint.Style.FILL
|
||||||
paint.style = Paint.Style.FILL
|
micPaint.style = Paint.Style.FILL
|
||||||
refreshColors()
|
micPaint.color = Color.WHITE
|
||||||
isClickable = true
|
isClickable = true
|
||||||
isFocusable = true
|
isFocusable = true
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun refreshColors() {
|
/** (верхний цвет, нижний цвет) градиента заливки. */
|
||||||
paint.color = when {
|
private fun fillColors(): Pair<Int, Int> = when {
|
||||||
!enabled2 -> Color.parseColor("#484F58")
|
!enabled2 -> 0x565E68 to 0x3C424B
|
||||||
isPressed -> Color.parseColor("#F85149")
|
isPressed -> 0xFF8A80 to 0xDB3A30
|
||||||
else -> Color.parseColor("#1F6FEB")
|
else -> 0x4A9BFF to 0x1561D6
|
||||||
}
|
}
|
||||||
invalidate()
|
|
||||||
|
private fun ringColor(): Int = when {
|
||||||
|
!enabled2 -> 0x6B727B
|
||||||
|
isPressed -> 0xFFA79F
|
||||||
|
else -> 0x6FB0FF
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun dp(v: Int): Int = (v * resources.displayMetrics.density).toInt()
|
private fun dp(v: Int): Int = (v * resources.displayMetrics.density).toInt()
|
||||||
@@ -74,32 +85,51 @@ class PttButton @JvmOverloads constructor(
|
|||||||
super.onSizeChanged(w, h, oldw, oldh)
|
super.onSizeChanged(w, h, oldw, oldh)
|
||||||
centerX = w / 2f
|
centerX = w / 2f
|
||||||
centerY = h / 2f
|
centerY = h / 2f
|
||||||
radius = minOf(w, h) / 2f - dp(16)
|
radius = minOf(w, h) / 2f - dp(18)
|
||||||
refreshColors()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
override fun onDraw(canvas: Canvas) {
|
override fun onDraw(canvas: Canvas) {
|
||||||
super.onDraw(canvas)
|
super.onDraw(canvas)
|
||||||
val r = radius / (1f + if (isPressed) 0.06f else 0f)
|
val r = radius / (1f + if (isPressed) 0.06f else 0f)
|
||||||
canvas.drawCircle(centerX, centerY, r, paint)
|
val cx = centerX
|
||||||
canvas.drawCircle(centerX, centerY, r, ringPaint)
|
val cy = centerY
|
||||||
|
val (top, bottom) = fillColors()
|
||||||
|
|
||||||
// Иконка микрофона (как icons8: капсула + чашка + ножка + основание)
|
// Заливка с вертикальным градиентом (глянец)
|
||||||
val micPaint = Paint(Paint.ANTI_ALIAS_FLAG)
|
fillPaint.shader = LinearGradient(
|
||||||
micPaint.color = Color.WHITE
|
cx, cy - r, cx, cy + r, top, bottom, Shader.TileMode.CLAMP
|
||||||
micPaint.style = Paint.Style.FILL
|
)
|
||||||
|
canvas.drawCircle(cx, cy, r, fillPaint)
|
||||||
|
|
||||||
val x = centerX
|
// Тонкий ободок по краю
|
||||||
val y = centerY
|
ringPaint.color = ringColor()
|
||||||
val s = r * 0.5f
|
canvas.drawCircle(cx, cy, r - dp(1).toFloat(), ringPaint)
|
||||||
|
|
||||||
|
// Верхний глянец (белое затухание сверху)
|
||||||
|
glossPaint.shader = LinearGradient(
|
||||||
|
cx, cy - r, cx, cy + r * 0.18f,
|
||||||
|
Color.argb(70, 255, 255, 255), Color.TRANSPARENT, Shader.TileMode.CLAMP
|
||||||
|
)
|
||||||
|
clip.reset()
|
||||||
|
clip.addCircle(cx, cy, r, Path.Direction.CW)
|
||||||
|
canvas.save()
|
||||||
|
canvas.clipPath(clip)
|
||||||
|
canvas.drawRect(cx - r, cy - r, cx + r, cy + r, glossPaint)
|
||||||
|
canvas.restore()
|
||||||
|
glossPaint.shader = null
|
||||||
|
|
||||||
|
drawMic(canvas, cx, cy, r * 0.5f)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Иконка микрофона (капсула + держатель + ножка + основание). */
|
||||||
|
private fun drawMic(canvas: Canvas, x: Float, y: Float, s: Float) {
|
||||||
// корпус-капсула
|
// корпус-капсула
|
||||||
val halfW = s * 0.34f
|
val halfW = s * 0.34f
|
||||||
canvas.drawRoundRect(
|
canvas.drawRoundRect(
|
||||||
x - halfW, y - s * 0.85f, x + halfW, y + s * 0.10f,
|
x - halfW, y - s * 0.85f, x + halfW, y + s * 0.10f,
|
||||||
halfW, halfW, micPaint
|
halfW, halfW, micPaint
|
||||||
)
|
)
|
||||||
// чашка-держатель (U-образная, заполненная)
|
// чашка-держатель (U-образная)
|
||||||
val cup = Path()
|
val cup = Path()
|
||||||
cup.fillType = Path.FillType.EVEN_ODD
|
cup.fillType = Path.FillType.EVEN_ODD
|
||||||
cup.moveTo(x - s * 0.52f, y + s * 0.06f)
|
cup.moveTo(x - s * 0.52f, y + s * 0.06f)
|
||||||
|
|||||||
128
app/src/main/java/ru/ua1zbe/svxremote/ui/SMeterView.kt
Normal file
128
app/src/main/java/ru/ua1zbe/svxremote/ui/SMeterView.kt
Normal file
@@ -0,0 +1,128 @@
|
|||||||
|
package ru.ua1zbe.svxremote.ui
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import android.graphics.Canvas
|
||||||
|
import android.graphics.Paint
|
||||||
|
import android.os.Handler
|
||||||
|
import android.os.Looper
|
||||||
|
import android.util.AttributeSet
|
||||||
|
import android.view.View
|
||||||
|
import kotlin.math.roundToInt
|
||||||
|
|
||||||
|
/**
|
||||||
|
* S-метр: полоса со шкалой S1–S9, +20…+60, заливкой уровня, белой пик-меткой
|
||||||
|
* (peak-hold) и цифрой текущего уровня справа («S9», «+43» или «---»).
|
||||||
|
* Уровень 0..1; S9 = 55% пути, +60 = 88%.
|
||||||
|
*/
|
||||||
|
class SMeterView @JvmOverloads constructor(
|
||||||
|
context: Context,
|
||||||
|
attrs: AttributeSet? = null
|
||||||
|
) : View(context, attrs) {
|
||||||
|
|
||||||
|
private var fillColor = 0xFF58A6FF.toInt()
|
||||||
|
private val track = Paint().apply { color = 0xFF21262D.toInt() }
|
||||||
|
private val fill = Paint().apply { color = fillColor }
|
||||||
|
private val tick = Paint().apply { color = 0xFF8B949E.toInt(); strokeWidth = dp(1f) }
|
||||||
|
private val tickMajor = Paint().apply { color = 0xFF8B949E.toInt(); strokeWidth = dp(1.5f) }
|
||||||
|
private val peakPaint = Paint().apply { color = 0xFFFFFFFF.toInt(); strokeWidth = dp(2f) }
|
||||||
|
private val label = Paint(Paint.ANTI_ALIAS_FLAG).apply {
|
||||||
|
color = 0xFF8B949E.toInt()
|
||||||
|
textSize = sp(9)
|
||||||
|
}
|
||||||
|
private val valuePaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
|
||||||
|
color = 0xFFE6EDF3.toInt()
|
||||||
|
textSize = sp(12)
|
||||||
|
textAlign = Paint.Align.RIGHT
|
||||||
|
}
|
||||||
|
private val idlePaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
|
||||||
|
color = 0xFF8B949E.toInt()
|
||||||
|
textSize = sp(12)
|
||||||
|
textAlign = Paint.Align.RIGHT
|
||||||
|
}
|
||||||
|
|
||||||
|
@Volatile
|
||||||
|
private var target = 0f
|
||||||
|
private var shown = 0f
|
||||||
|
private var peak = 0f
|
||||||
|
private var lastActive = 0L
|
||||||
|
|
||||||
|
private val handler = Handler(Looper.getMainLooper())
|
||||||
|
private val ticker = object : Runnable {
|
||||||
|
override fun run() {
|
||||||
|
// Гарантированный сброс: если сигнала не было 600 мс — в ноль
|
||||||
|
if (System.currentTimeMillis() - lastActive > 600 && target != 0f) target = 0f
|
||||||
|
// Сглаживание уровня и медленный спад пика
|
||||||
|
shown += (target - shown) * 0.35f
|
||||||
|
if (Math.abs(target - shown) < 0.002f) shown = target
|
||||||
|
peak = maxOf(peak * 0.985f, shown)
|
||||||
|
if (peak < 0.003f) peak = 0f
|
||||||
|
invalidate()
|
||||||
|
handler.postDelayed(this, 100)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun setColor(color: Int) {
|
||||||
|
fillColor = color
|
||||||
|
fill.color = color
|
||||||
|
}
|
||||||
|
|
||||||
|
fun setLevel(level: Float) {
|
||||||
|
if (level > 0.01f) lastActive = System.currentTimeMillis()
|
||||||
|
target = level.coerceIn(0f, 1f)
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onAttachedToWindow() {
|
||||||
|
super.onAttachedToWindow()
|
||||||
|
handler.post(ticker)
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onDetachedFromWindow() {
|
||||||
|
handler.removeCallbacksAndMessages(null)
|
||||||
|
super.onDetachedFromWindow()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun dp(v: Float): Float = v * resources.displayMetrics.density
|
||||||
|
private fun sp(v: Int): Float = v * resources.displayMetrics.scaledDensity
|
||||||
|
|
||||||
|
private fun levelText(level: Float): String = when {
|
||||||
|
level < 0.005f -> "---"
|
||||||
|
level < 0.55f -> "S${(level / 0.55f * 9f).roundToInt().coerceIn(1, 9)}"
|
||||||
|
else -> "+${(((level - 0.55f) / 0.45f) * 60f).roundToInt().coerceIn(1, 99)}"
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onDraw(canvas: Canvas) {
|
||||||
|
val w = width.toFloat()
|
||||||
|
val h = height.toFloat()
|
||||||
|
val left = dp(2f)
|
||||||
|
val right = w - dp(2f)
|
||||||
|
val bandTop = dp(4f)
|
||||||
|
val bandH = dp(14f)
|
||||||
|
|
||||||
|
// полоса
|
||||||
|
canvas.drawRect(left, bandTop, right, bandTop + bandH, track)
|
||||||
|
val lvl = shown.coerceIn(0f, 1f)
|
||||||
|
if (lvl > 0.002f) {
|
||||||
|
canvas.drawRect(left, bandTop, left + lvl * (right - left), bandTop + bandH, fill)
|
||||||
|
}
|
||||||
|
|
||||||
|
// деления: S1..S9, +20..+60
|
||||||
|
val marks = listOf("S1" to 0.11f, "S3" to 0.22f, "S5" to 0.33f, "S7" to 0.44f,
|
||||||
|
"S9" to 0.55f, "+20" to 0.66f, "+40" to 0.77f, "+60" to 0.88f)
|
||||||
|
for ((text, pos) in marks) {
|
||||||
|
val mx = left + pos * (right - left)
|
||||||
|
val major = pos == 0.55f || pos == 0.88f
|
||||||
|
canvas.drawLine(mx, bandTop, mx, bandTop + bandH, if (major) tickMajor else tick)
|
||||||
|
canvas.drawText(text, mx - dp(8f), bandTop + bandH + dp(11f), label)
|
||||||
|
}
|
||||||
|
|
||||||
|
// пик-метка
|
||||||
|
if (peak > 0.003f) {
|
||||||
|
val px = left + peak.coerceIn(0f, 1f) * (right - left)
|
||||||
|
canvas.drawLine(px, bandTop - dp(3f), px, bandTop + bandH + dp(3f), peakPaint)
|
||||||
|
}
|
||||||
|
|
||||||
|
// цифра уровня справа от полосы (и чуть выше делений)
|
||||||
|
val p = if (target < 0.005f) idlePaint else valuePaint
|
||||||
|
canvas.drawText(levelText(target), right, bandTop + bandH - dp(3f), p)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,156 @@
|
|||||||
|
package ru.ua1zbe.svxremote.ui
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import android.graphics.Canvas
|
||||||
|
import android.graphics.Color
|
||||||
|
import android.graphics.Paint
|
||||||
|
import android.graphics.RectF
|
||||||
|
import android.os.Handler
|
||||||
|
import android.os.Looper
|
||||||
|
import android.util.AttributeSet
|
||||||
|
import android.view.View
|
||||||
|
import kotlin.random.Random
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Временное демо-окно с примерами индикаторов звука (S-метр, клиппинг,
|
||||||
|
* джиттер/потери). Открывается удержанием на надписи «На связи».
|
||||||
|
* Уровни симулируются, чтобы было видно, как индикаторы работают.
|
||||||
|
*/
|
||||||
|
class SoundMeterPreviewView @JvmOverloads constructor(
|
||||||
|
context: Context,
|
||||||
|
attrs: AttributeSet? = null
|
||||||
|
) : View(context, attrs) {
|
||||||
|
|
||||||
|
private val bg = Paint().apply { color = 0xFF0D1117.toInt() }
|
||||||
|
private val track = Paint().apply { color = 0xFF21262D.toInt() }
|
||||||
|
private val fill = Paint().apply { color = 0xFF58A6FF.toInt() }
|
||||||
|
private val fillHot = Paint().apply { color = 0xFFF85149.toInt() }
|
||||||
|
private val peakPaint = Paint().apply { color = 0xFFFFFFFF.toInt(); strokeWidth = dp(2) }
|
||||||
|
private val tick = Paint().apply { color = 0xFF8B949E.toInt(); strokeWidth = dp(1) }
|
||||||
|
private val label = Paint(Paint.ANTI_ALIAS_FLAG).apply {
|
||||||
|
color = 0xFF8B949E.toInt()
|
||||||
|
textSize = sp(11)
|
||||||
|
}
|
||||||
|
private val labelSmall = Paint(Paint.ANTI_ALIAS_FLAG).apply {
|
||||||
|
color = 0xFF8B949E.toInt()
|
||||||
|
textSize = sp(9)
|
||||||
|
}
|
||||||
|
private val clipDot = Paint(Paint.ANTI_ALIAS_FLAG).apply {
|
||||||
|
color = 0xFFF85149.toInt()
|
||||||
|
}
|
||||||
|
private val clipDotOff = Paint(Paint.ANTI_ALIAS_FLAG).apply {
|
||||||
|
color = 0xFF30363D.toInt()
|
||||||
|
}
|
||||||
|
|
||||||
|
private val handler = Handler(Looper.getMainLooper())
|
||||||
|
private var simLevel = 0.0f
|
||||||
|
private var simPeak = 0.0f
|
||||||
|
private var simJitter = 30.0f
|
||||||
|
private var simLoss = 0.1f
|
||||||
|
private var t = 0.0
|
||||||
|
|
||||||
|
private val anim = object : Runnable {
|
||||||
|
override fun run() {
|
||||||
|
t += 0.08
|
||||||
|
val wave = ((Math.sin(t) + Math.sin(t * 2.3)) / 2 + 1) / 2
|
||||||
|
simLevel = (wave * 0.62 + Random.nextFloat() * 0.12).toFloat()
|
||||||
|
// Периодически «перегруз» — клиппинг и пики
|
||||||
|
if (Random.nextFloat() > 0.92f) simLevel = 0.98f
|
||||||
|
simPeak = maxOf(simLevel, simPeak - 0.02f)
|
||||||
|
simJitter = 25 + Random.nextFloat() * 120
|
||||||
|
simLoss = (Random.nextFloat() * 0.5f).coerceAtLeast(0.03f)
|
||||||
|
invalidate()
|
||||||
|
handler.postDelayed(this, 50)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onAttachedToWindow() {
|
||||||
|
super.onAttachedToWindow()
|
||||||
|
handler.post(anim)
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onDetachedFromWindow() {
|
||||||
|
handler.removeCallbacksAndMessages(null)
|
||||||
|
super.onDetachedFromWindow()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun dp(v: Int): Float = v * resources.displayMetrics.density
|
||||||
|
private fun sp(v: Int): Float = v * resources.displayMetrics.scaledDensity
|
||||||
|
|
||||||
|
override fun onDraw(canvas: Canvas) {
|
||||||
|
val w = width.toFloat()
|
||||||
|
val h = height.toFloat()
|
||||||
|
canvas.drawRect(0f, 0f, w, h, bg)
|
||||||
|
|
||||||
|
// --- S-метр ---
|
||||||
|
var y = dp(18)
|
||||||
|
canvas.drawText("S-метр (peak-hold)", dp(16), y, label)
|
||||||
|
y += dp(8)
|
||||||
|
drawSMeter(canvas, w, y)
|
||||||
|
|
||||||
|
// --- Уровень + клиппинг ---
|
||||||
|
y += dp(58)
|
||||||
|
canvas.drawText("Уровень + клиппинг", dp(16), y, label)
|
||||||
|
y += dp(8)
|
||||||
|
drawVUMeter(canvas, w, y)
|
||||||
|
|
||||||
|
// --- Джиттер / потери ---
|
||||||
|
y += dp(58)
|
||||||
|
canvas.drawText("Джиттер и потери пакетов", dp(16), y, label)
|
||||||
|
y += dp(18)
|
||||||
|
canvas.drawText(
|
||||||
|
"джиттер %d мс · потери %.1f%%".format(simJitter.toInt(), simLoss),
|
||||||
|
dp(16), y, label
|
||||||
|
)
|
||||||
|
val bar = RectF(dp(16), y + dp(6), w - dp(16), y + dp(16))
|
||||||
|
canvas.drawRect(bar, track)
|
||||||
|
val jw = (simJitter / 250f).coerceIn(0f, 1f) * bar.width()
|
||||||
|
canvas.drawRect(bar.left, bar.top, bar.left + jw, bar.bottom, fill)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** S-метр: полоса со шкалой S1..S9, +20..+60 и пик-меткой. */
|
||||||
|
private fun drawSMeter(canvas: Canvas, w: Float, top: Float) {
|
||||||
|
val left = dp(16)
|
||||||
|
val right = w - dp(16)
|
||||||
|
val bandTop = top + dp(2)
|
||||||
|
val bandH = dp(14)
|
||||||
|
canvas.drawRect(left, bandTop, right, bandTop + bandH, track)
|
||||||
|
val level = (simLevel).coerceIn(0f, 1f)
|
||||||
|
val fw = level * (right - left)
|
||||||
|
canvas.drawRect(left, bandTop, left + fw, bandTop + bandH, if (level > 0.85f) fillHot else fill)
|
||||||
|
// пик-метка
|
||||||
|
val px = left + simPeak.coerceIn(0f, 1f) * (right - left)
|
||||||
|
canvas.drawLine(px, bandTop - dp(3), px, bandTop + bandH + dp(3), peakPaint)
|
||||||
|
// деления и шкала
|
||||||
|
val marks = listOf("S1" to 0.11f, "S3" to 0.22f, "S5" to 0.33f, "S7" to 0.44f,
|
||||||
|
"S9" to 0.55f, "+20" to 0.66f, "+40" to 0.77f, "+60" to 0.88f)
|
||||||
|
for ((text, pos) in marks) {
|
||||||
|
val mx = left + pos * (right - left)
|
||||||
|
canvas.drawLine(mx, bandTop, mx, bandTop + bandH, tick)
|
||||||
|
canvas.drawText(text, mx - dp(10), bandTop + bandH + dp(12), labelSmall)
|
||||||
|
}
|
||||||
|
canvas.drawText("+%.0f".format(level * 60), left, bandTop - dp(4), labelSmall)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** VU-полоса с зоной перегрузки и красной точкой клиппинга. */
|
||||||
|
private fun drawVUMeter(canvas: Canvas, w: Float, top: Float) {
|
||||||
|
val left = dp(16)
|
||||||
|
val right = w - dp(52)
|
||||||
|
val bandTop = top + dp(2)
|
||||||
|
val bandH = dp(14)
|
||||||
|
canvas.drawRect(left, bandTop, right, bandTop + bandH, track)
|
||||||
|
val level = simLevel.coerceIn(0f, 1f)
|
||||||
|
val fw = level * (right - left)
|
||||||
|
canvas.drawRect(left, bandTop, left + fw, bandTop + bandH, fill)
|
||||||
|
// красная зона последних 15%
|
||||||
|
canvas.drawRect(
|
||||||
|
right - (right - left) * 0.15f, bandTop, right, bandTop + bandH,
|
||||||
|
if (level > 0.85f) fillHot else track
|
||||||
|
)
|
||||||
|
// клиппинг-точка
|
||||||
|
val cxp = w - dp(24)
|
||||||
|
val cyp = bandTop + bandH / 2
|
||||||
|
canvas.drawCircle(cxp, cyp, dp(7), if (level > 0.92f) clipDot else clipDotOff)
|
||||||
|
canvas.drawText("CLIP", cxp - dp(20), cyp + dp(10), labelSmall)
|
||||||
|
}
|
||||||
|
}
|
||||||
BIN
app/src/main/res/drawable-nodpi/ic_launcher_fg.png
Normal file
BIN
app/src/main/res/drawable-nodpi/ic_launcher_fg.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 43 KiB |
5
app/src/main/res/drawable/bg_monitor_on.xml
Normal file
5
app/src/main/res/drawable/bg_monitor_on.xml
Normal file
@@ -0,0 +1,5 @@
|
|||||||
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<shape xmlns:android="http://schemas.android.com/apk/res/android"
|
||||||
|
android:shape="oval">
|
||||||
|
<solid android:color="#3358A6FF" />
|
||||||
|
</shape>
|
||||||
7
app/src/main/res/drawable/bg_node_toast.xml
Normal file
7
app/src/main/res/drawable/bg_node_toast.xml
Normal file
@@ -0,0 +1,7 @@
|
|||||||
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<shape xmlns:android="http://schemas.android.com/apk/res/android"
|
||||||
|
android:shape="rectangle">
|
||||||
|
<solid android:color="#E61B222A" />
|
||||||
|
<corners android:radius="24dp" />
|
||||||
|
<stroke android:width="1dp" android:color="#40FFFFFF" />
|
||||||
|
</shape>
|
||||||
6
app/src/main/res/drawable/bg_section.xml
Normal file
6
app/src/main/res/drawable/bg_section.xml
Normal file
@@ -0,0 +1,6 @@
|
|||||||
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
|
||||||
|
<solid android:color="@color/surface" />
|
||||||
|
<corners android:radius="14dp" />
|
||||||
|
<stroke android:width="1dp" android:color="@color/surface_light" />
|
||||||
|
</shape>
|
||||||
9
app/src/main/res/drawable/ic_delete.xml
Normal file
9
app/src/main/res/drawable/ic_delete.xml
Normal file
@@ -0,0 +1,9 @@
|
|||||||
|
<vector xmlns:android="http://schemas.android.com/apk/res/android"
|
||||||
|
android:width="24dp"
|
||||||
|
android:height="24dp"
|
||||||
|
android:viewportWidth="24"
|
||||||
|
android:viewportHeight="24">
|
||||||
|
<path
|
||||||
|
android:fillColor="#FFFFFF"
|
||||||
|
android:pathData="M6,7h12v12a1,1 0,0 1,-1 1H7a1,1 0,0 1,-1 -1V7zM9,9v9h1V9H9zM14,9v9h1V9h-1zM4,5h16v2H4V5z" />
|
||||||
|
</vector>
|
||||||
10
app/src/main/res/drawable/ic_headset.xml
Normal file
10
app/src/main/res/drawable/ic_headset.xml
Normal file
@@ -0,0 +1,10 @@
|
|||||||
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<vector xmlns:android="http://schemas.android.com/apk/res/android"
|
||||||
|
android:width="24dp"
|
||||||
|
android:height="24dp"
|
||||||
|
android:viewportWidth="24"
|
||||||
|
android:viewportHeight="24">
|
||||||
|
<path
|
||||||
|
android:fillColor="#8B949E"
|
||||||
|
android:pathData="M12,1c-4.97,0 -9,4.03 -9,9v7c0,1.66 1.34,3 3,3h3v-8L5,12v-2c0,-3.87 3.13,-7 7,-7s7,3.13 7,7v2h-4v8h3c1.66,0 3,-1.34 3,-3v-7c0,-4.97 -4.03,-9 -9,-9z" />
|
||||||
|
</vector>
|
||||||
@@ -1,16 +0,0 @@
|
|||||||
<?xml version="1.0" encoding="utf-8"?>
|
|
||||||
<vector xmlns:android="http://schemas.android.com/apk/res/android"
|
|
||||||
android:width="108dp"
|
|
||||||
android:height="108dp"
|
|
||||||
android:viewportWidth="108"
|
|
||||||
android:viewportHeight="108">
|
|
||||||
<group
|
|
||||||
android:translateX="30"
|
|
||||||
android:translateY="30"
|
|
||||||
android:scaleX="1.5"
|
|
||||||
android:scaleY="1.5">
|
|
||||||
<path
|
|
||||||
android:fillColor="#FFFFFF"
|
|
||||||
android:pathData="M12,14c1.66,0 2.99,-1.34 2.99,-3L15,5c0,-1.66 -1.34,-3 -3,-3S9,3.34 9,5v6c0,1.66 1.34,3 3,3zM17.3,11c0,3 -2.54,5.1 -5.3,5.1S6.7,14 6.7,11L5,11c0,3.41 2.72,6.23 6,6.72L11,21h2v-3.28c3.28,-0.48 6,-3.3 6,-6.72h-1.7z" />
|
|
||||||
</group>
|
|
||||||
</vector>
|
|
||||||
9
app/src/main/res/drawable/ic_play.xml
Normal file
9
app/src/main/res/drawable/ic_play.xml
Normal file
@@ -0,0 +1,9 @@
|
|||||||
|
<vector xmlns:android="http://schemas.android.com/apk/res/android"
|
||||||
|
android:width="24dp"
|
||||||
|
android:height="24dp"
|
||||||
|
android:viewportWidth="24"
|
||||||
|
android:viewportHeight="24">
|
||||||
|
<path
|
||||||
|
android:fillColor="#FFFFFF"
|
||||||
|
android:pathData="M8,5v14l11,-7z" />
|
||||||
|
</vector>
|
||||||
10
app/src/main/res/drawable/ic_power.xml
Normal file
10
app/src/main/res/drawable/ic_power.xml
Normal file
@@ -0,0 +1,10 @@
|
|||||||
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<vector xmlns:android="http://schemas.android.com/apk/res/android"
|
||||||
|
android:width="24dp"
|
||||||
|
android:height="24dp"
|
||||||
|
android:viewportWidth="24"
|
||||||
|
android:viewportHeight="24">
|
||||||
|
<path
|
||||||
|
android:fillColor="#8B949E"
|
||||||
|
android:pathData="M13,3h-2v10h2L13,3zM17.83,5.17l-1.42,1.42C17.99,7.86 19,9.81 19,12c0,3.87 -3.13,7 -7,7s-7,-3.13 -7,-7c0,-2.19 1.01,-4.14 2.58,-5.41L6.17,5.17C4.23,6.82 3,9.26 3,12c0,4.97 4.03,9 9,9s9,-4.03 9,-9C21,9.26 19.77,6.82 17.83,5.17z" />
|
||||||
|
</vector>
|
||||||
9
app/src/main/res/drawable/ic_record.xml
Normal file
9
app/src/main/res/drawable/ic_record.xml
Normal file
@@ -0,0 +1,9 @@
|
|||||||
|
<vector xmlns:android="http://schemas.android.com/apk/res/android"
|
||||||
|
android:width="24dp"
|
||||||
|
android:height="24dp"
|
||||||
|
android:viewportWidth="24"
|
||||||
|
android:viewportHeight="24">
|
||||||
|
<path
|
||||||
|
android:fillColor="#8B949E"
|
||||||
|
android:pathData="M12,12m-7,0a7,7 0,1 1,14 0a7,7 0,1 1,-14 0" />
|
||||||
|
</vector>
|
||||||
9
app/src/main/res/drawable/ic_stop.xml
Normal file
9
app/src/main/res/drawable/ic_stop.xml
Normal file
@@ -0,0 +1,9 @@
|
|||||||
|
<vector xmlns:android="http://schemas.android.com/apk/res/android"
|
||||||
|
android:width="24dp"
|
||||||
|
android:height="24dp"
|
||||||
|
android:viewportWidth="24"
|
||||||
|
android:viewportHeight="24">
|
||||||
|
<path
|
||||||
|
android:fillColor="#FFFFFF"
|
||||||
|
android:pathData="M7,7h10v10h-10z" />
|
||||||
|
</vector>
|
||||||
157
app/src/main/res/layout/activity_audio_settings.xml
Normal file
157
app/src/main/res/layout/activity_audio_settings.xml
Normal file
@@ -0,0 +1,157 @@
|
|||||||
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
|
||||||
|
android:layout_width="match_parent"
|
||||||
|
android:layout_height="match_parent"
|
||||||
|
android:background="@color/bg">
|
||||||
|
|
||||||
|
<LinearLayout
|
||||||
|
android:layout_width="match_parent"
|
||||||
|
android:layout_height="wrap_content"
|
||||||
|
android:orientation="vertical"
|
||||||
|
android:padding="20dp">
|
||||||
|
|
||||||
|
<TextView
|
||||||
|
android:layout_width="match_parent"
|
||||||
|
android:layout_height="wrap_content"
|
||||||
|
android:text="@string/audio_settings_title"
|
||||||
|
android:textColor="@color/text_primary"
|
||||||
|
android:textSize="20sp"
|
||||||
|
android:textStyle="bold"
|
||||||
|
android:layout_marginBottom="4dp" />
|
||||||
|
|
||||||
|
<TextView
|
||||||
|
android:layout_width="match_parent"
|
||||||
|
android:layout_height="wrap_content"
|
||||||
|
android:text="@string/audio_settings_hint"
|
||||||
|
android:textColor="@color/text_secondary"
|
||||||
|
android:textSize="13sp"
|
||||||
|
android:layout_marginBottom="20dp" />
|
||||||
|
|
||||||
|
<LinearLayout
|
||||||
|
android:layout_width="match_parent"
|
||||||
|
android:layout_height="wrap_content"
|
||||||
|
android:orientation="horizontal"
|
||||||
|
android:gravity="center_vertical">
|
||||||
|
|
||||||
|
<TextView
|
||||||
|
android:layout_width="0dp"
|
||||||
|
android:layout_height="wrap_content"
|
||||||
|
android:layout_weight="1"
|
||||||
|
android:text="@string/audio_mic_gain"
|
||||||
|
android:textColor="@color/text_primary"
|
||||||
|
android:textSize="15sp" />
|
||||||
|
|
||||||
|
<TextView
|
||||||
|
android:id="@+id/lbl_mic_gain_value"
|
||||||
|
android:layout_width="wrap_content"
|
||||||
|
android:layout_height="wrap_content"
|
||||||
|
android:textColor="@color/text_secondary"
|
||||||
|
android:textSize="14sp" />
|
||||||
|
</LinearLayout>
|
||||||
|
|
||||||
|
<SeekBar
|
||||||
|
android:id="@+id/seek_mic_gain"
|
||||||
|
android:layout_width="match_parent"
|
||||||
|
android:layout_height="wrap_content"
|
||||||
|
android:max="40"
|
||||||
|
android:layout_marginBottom="20dp" />
|
||||||
|
|
||||||
|
<LinearLayout
|
||||||
|
android:layout_width="match_parent"
|
||||||
|
android:layout_height="wrap_content"
|
||||||
|
android:orientation="horizontal"
|
||||||
|
android:gravity="center_vertical">
|
||||||
|
|
||||||
|
<TextView
|
||||||
|
android:layout_width="0dp"
|
||||||
|
android:layout_height="wrap_content"
|
||||||
|
android:layout_weight="1"
|
||||||
|
android:text="@string/audio_rx_buffer"
|
||||||
|
android:textColor="@color/text_primary"
|
||||||
|
android:textSize="15sp" />
|
||||||
|
|
||||||
|
<TextView
|
||||||
|
android:id="@+id/lbl_rx_buffer_value"
|
||||||
|
android:layout_width="wrap_content"
|
||||||
|
android:layout_height="wrap_content"
|
||||||
|
android:textColor="@color/text_secondary"
|
||||||
|
android:textSize="14sp" />
|
||||||
|
</LinearLayout>
|
||||||
|
|
||||||
|
<SeekBar
|
||||||
|
android:id="@+id/seek_rx_buffer"
|
||||||
|
android:layout_width="match_parent"
|
||||||
|
android:layout_height="wrap_content"
|
||||||
|
android:max="25"
|
||||||
|
android:layout_marginBottom="20dp" />
|
||||||
|
|
||||||
|
<LinearLayout
|
||||||
|
android:layout_width="match_parent"
|
||||||
|
android:layout_height="wrap_content"
|
||||||
|
android:orientation="horizontal"
|
||||||
|
android:gravity="center_vertical">
|
||||||
|
|
||||||
|
<TextView
|
||||||
|
android:layout_width="0dp"
|
||||||
|
android:layout_height="wrap_content"
|
||||||
|
android:layout_weight="1"
|
||||||
|
android:text="@string/audio_jitter"
|
||||||
|
android:textColor="@color/text_primary"
|
||||||
|
android:textSize="15sp" />
|
||||||
|
|
||||||
|
<TextView
|
||||||
|
android:id="@+id/lbl_jitter_value"
|
||||||
|
android:layout_width="wrap_content"
|
||||||
|
android:layout_height="wrap_content"
|
||||||
|
android:textColor="@color/text_secondary"
|
||||||
|
android:textSize="14sp" />
|
||||||
|
</LinearLayout>
|
||||||
|
|
||||||
|
<SeekBar
|
||||||
|
android:id="@+id/seek_jitter"
|
||||||
|
android:layout_width="match_parent"
|
||||||
|
android:layout_height="wrap_content"
|
||||||
|
android:max="20"
|
||||||
|
android:layout_marginBottom="20dp" />
|
||||||
|
|
||||||
|
<LinearLayout
|
||||||
|
android:layout_width="match_parent"
|
||||||
|
android:layout_height="wrap_content"
|
||||||
|
android:orientation="horizontal"
|
||||||
|
android:gravity="center_vertical">
|
||||||
|
|
||||||
|
<TextView
|
||||||
|
android:layout_width="0dp"
|
||||||
|
android:layout_height="wrap_content"
|
||||||
|
android:layout_weight="1"
|
||||||
|
android:text="@string/audio_tx_bitrate"
|
||||||
|
android:textColor="@color/text_primary"
|
||||||
|
android:textSize="15sp" />
|
||||||
|
</LinearLayout>
|
||||||
|
|
||||||
|
<Spinner
|
||||||
|
android:id="@+id/spin_tx_bitrate"
|
||||||
|
android:layout_width="match_parent"
|
||||||
|
android:layout_height="wrap_content"
|
||||||
|
android:layout_marginBottom="24dp" />
|
||||||
|
|
||||||
|
<CheckBox
|
||||||
|
android:id="@+id/chk_rx_stats"
|
||||||
|
android:layout_width="match_parent"
|
||||||
|
android:layout_height="wrap_content"
|
||||||
|
android:layout_marginBottom="24dp"
|
||||||
|
android:text="@string/audio_rx_stats"
|
||||||
|
android:textColor="@color/text_primary"
|
||||||
|
android:textSize="15sp" />
|
||||||
|
|
||||||
|
<Button
|
||||||
|
android:id="@+id/btn_audio_save"
|
||||||
|
android:layout_width="match_parent"
|
||||||
|
android:layout_height="52dp"
|
||||||
|
android:text="@string/btn_save"
|
||||||
|
android:textColor="#0D1117"
|
||||||
|
android:background="@drawable/bg_primary_btn"
|
||||||
|
android:textSize="16sp"
|
||||||
|
android:textStyle="bold" />
|
||||||
|
</LinearLayout>
|
||||||
|
</ScrollView>
|
||||||
@@ -14,12 +14,22 @@
|
|||||||
android:orientation="horizontal"
|
android:orientation="horizontal"
|
||||||
android:gravity="center_vertical">
|
android:gravity="center_vertical">
|
||||||
|
|
||||||
|
<ImageButton
|
||||||
|
android:id="@+id/btn_power"
|
||||||
|
android:layout_width="48dp"
|
||||||
|
android:layout_height="48dp"
|
||||||
|
android:src="@drawable/ic_power"
|
||||||
|
android:background="?android:attr/selectableItemBackgroundBorderless"
|
||||||
|
android:contentDescription="@string/btn_power"
|
||||||
|
android:scaleType="centerInside" />
|
||||||
|
|
||||||
<Space
|
<Space
|
||||||
android:layout_width="0dp"
|
android:layout_width="0dp"
|
||||||
android:layout_height="1dp"
|
android:layout_height="1dp"
|
||||||
android:layout_weight="1" />
|
android:layout_weight="1" />
|
||||||
|
|
||||||
<TextView
|
<TextView
|
||||||
|
android:id="@+id/lbl_app_title"
|
||||||
android:layout_width="wrap_content"
|
android:layout_width="wrap_content"
|
||||||
android:layout_height="wrap_content"
|
android:layout_height="wrap_content"
|
||||||
android:text="@string/app_title"
|
android:text="@string/app_title"
|
||||||
@@ -56,97 +66,139 @@
|
|||||||
android:layout_weight="1"
|
android:layout_weight="1"
|
||||||
android:orientation="vertical">
|
android:orientation="vertical">
|
||||||
|
|
||||||
<TextView
|
|
||||||
android:id="@+id/lbl_callsign"
|
|
||||||
android:layout_width="wrap_content"
|
|
||||||
android:layout_height="wrap_content"
|
|
||||||
android:fontFamily="monospace"
|
|
||||||
android:textColor="@color/text_primary"
|
|
||||||
android:textSize="28sp"
|
|
||||||
android:textStyle="bold"
|
|
||||||
android:singleLine="true"
|
|
||||||
android:ellipsize="end"
|
|
||||||
android:text="@string/settings_not_configured" />
|
|
||||||
|
|
||||||
<TextView
|
|
||||||
android:id="@+id/lbl_subtitle"
|
|
||||||
android:layout_width="wrap_content"
|
|
||||||
android:layout_height="wrap_content"
|
|
||||||
android:layout_marginTop="4dp"
|
|
||||||
android:textColor="@color/text_secondary"
|
|
||||||
android:textSize="14sp"
|
|
||||||
android:singleLine="true"
|
|
||||||
android:ellipsize="end" />
|
|
||||||
</LinearLayout>
|
|
||||||
|
|
||||||
<TextView
|
|
||||||
android:id="@+id/lbl_tg"
|
|
||||||
android:layout_width="wrap_content"
|
|
||||||
android:layout_height="wrap_content"
|
|
||||||
android:layout_marginStart="12dp"
|
|
||||||
android:textColor="@color/warn"
|
|
||||||
android:textSize="16sp"
|
|
||||||
android:textStyle="bold"
|
|
||||||
android:fontFamily="monospace" />
|
|
||||||
</LinearLayout>
|
|
||||||
|
|
||||||
<!-- Статус соединения -->
|
|
||||||
<TextView
|
|
||||||
android:id="@+id/status_chip"
|
|
||||||
android:layout_width="match_parent"
|
|
||||||
android:layout_height="wrap_content"
|
|
||||||
android:layout_marginTop="20dp"
|
|
||||||
android:gravity="center"
|
|
||||||
android:textColor="@color/danger"
|
|
||||||
android:textSize="18sp"
|
|
||||||
android:textStyle="bold"
|
|
||||||
android:text="@string/status_disconnected" />
|
|
||||||
|
|
||||||
<!-- S-метры -->
|
|
||||||
<LinearLayout
|
|
||||||
android:layout_width="match_parent"
|
|
||||||
android:layout_height="wrap_content"
|
|
||||||
android:layout_marginTop="28dp"
|
|
||||||
android:orientation="vertical">
|
|
||||||
|
|
||||||
<LinearLayout
|
<LinearLayout
|
||||||
android:layout_width="match_parent"
|
android:layout_width="match_parent"
|
||||||
android:layout_height="wrap_content"
|
android:layout_height="wrap_content"
|
||||||
android:orientation="horizontal"
|
android:orientation="horizontal"
|
||||||
android:gravity="center_vertical">
|
android:gravity="center_vertical">
|
||||||
|
|
||||||
|
<TextView
|
||||||
|
android:id="@+id/lbl_callsign"
|
||||||
|
android:layout_width="0dp"
|
||||||
|
android:layout_weight="1"
|
||||||
|
android:layout_height="wrap_content"
|
||||||
|
android:fontFamily="monospace"
|
||||||
|
android:textColor="@color/text_primary"
|
||||||
|
android:textSize="22sp"
|
||||||
|
android:textStyle="bold"
|
||||||
|
android:singleLine="true"
|
||||||
|
android:ellipsize="end"
|
||||||
|
android:text="@string/settings_not_configured" />
|
||||||
|
|
||||||
|
<ImageButton
|
||||||
|
android:id="@+id/btn_record"
|
||||||
|
android:layout_width="44dp"
|
||||||
|
android:layout_height="44dp"
|
||||||
|
android:layout_marginStart="8dp"
|
||||||
|
android:src="@drawable/ic_record"
|
||||||
|
android:background="?android:attr/selectableItemBackgroundBorderless"
|
||||||
|
android:contentDescription="@string/btn_record"
|
||||||
|
android:scaleType="centerInside"
|
||||||
|
android:tint="@color/text_secondary" />
|
||||||
|
|
||||||
|
<ImageButton
|
||||||
|
android:id="@+id/btn_monitor"
|
||||||
|
android:layout_width="44dp"
|
||||||
|
android:layout_height="44dp"
|
||||||
|
android:layout_marginStart="8dp"
|
||||||
|
android:src="@drawable/ic_headset"
|
||||||
|
android:background="?android:attr/selectableItemBackgroundBorderless"
|
||||||
|
android:contentDescription="@string/btn_monitor"
|
||||||
|
android:scaleType="centerInside" />
|
||||||
|
|
||||||
|
<TextView
|
||||||
|
android:id="@+id/lbl_tg"
|
||||||
|
android:layout_width="wrap_content"
|
||||||
|
android:layout_height="wrap_content"
|
||||||
|
android:layout_marginStart="14dp"
|
||||||
|
android:textColor="@color/warn"
|
||||||
|
android:textSize="22sp"
|
||||||
|
android:textStyle="bold"
|
||||||
|
android:fontFamily="monospace" />
|
||||||
|
</LinearLayout>
|
||||||
|
</LinearLayout>
|
||||||
|
</LinearLayout>
|
||||||
|
|
||||||
|
<!-- Секция: APRS/подключение + статус -->
|
||||||
|
<LinearLayout
|
||||||
|
android:layout_width="match_parent"
|
||||||
|
android:layout_height="wrap_content"
|
||||||
|
android:layout_marginTop="12dp"
|
||||||
|
android:orientation="vertical"
|
||||||
|
android:background="@drawable/bg_section"
|
||||||
|
android:paddingStart="14dp"
|
||||||
|
android:paddingEnd="14dp"
|
||||||
|
android:paddingTop="10dp"
|
||||||
|
android:paddingBottom="10dp">
|
||||||
|
|
||||||
|
<TextView
|
||||||
|
android:id="@+id/lbl_subtitle"
|
||||||
|
android:layout_width="match_parent"
|
||||||
|
android:layout_height="wrap_content"
|
||||||
|
android:gravity="center"
|
||||||
|
android:textColor="@color/text_secondary"
|
||||||
|
android:textSize="14sp"
|
||||||
|
android:singleLine="true"
|
||||||
|
android:ellipsize="end" />
|
||||||
|
|
||||||
|
<!-- Статус соединения -->
|
||||||
|
<TextView
|
||||||
|
android:id="@+id/status_chip"
|
||||||
|
android:layout_width="match_parent"
|
||||||
|
android:layout_height="wrap_content"
|
||||||
|
android:layout_marginTop="8dp"
|
||||||
|
android:gravity="center"
|
||||||
|
android:textColor="@color/danger"
|
||||||
|
android:textSize="18sp"
|
||||||
|
android:textStyle="bold"
|
||||||
|
android:text="@string/status_disconnected" />
|
||||||
|
</LinearLayout>
|
||||||
|
|
||||||
|
<!-- Говорящий (единая строка): «Говорит …» при приёме, иначе позывной+TG -->
|
||||||
|
<TextView
|
||||||
|
android:id="@+id/lbl_talker"
|
||||||
|
android:layout_width="match_parent"
|
||||||
|
android:layout_height="wrap_content"
|
||||||
|
android:layout_marginTop="14dp"
|
||||||
|
android:gravity="center"
|
||||||
|
android:textColor="@color/accent"
|
||||||
|
android:textSize="22sp"
|
||||||
|
android:textStyle="bold"
|
||||||
|
android:singleLine="true"
|
||||||
|
android:ellipsize="end" />
|
||||||
|
|
||||||
|
<!-- S-метры -->
|
||||||
|
<LinearLayout
|
||||||
|
android:layout_width="match_parent"
|
||||||
|
android:layout_height="wrap_content"
|
||||||
|
android:layout_marginTop="16dp"
|
||||||
|
android:orientation="vertical"
|
||||||
|
android:background="@drawable/bg_section"
|
||||||
|
android:paddingStart="14dp"
|
||||||
|
android:paddingEnd="14dp"
|
||||||
|
android:paddingTop="12dp"
|
||||||
|
android:paddingBottom="12dp">
|
||||||
|
|
||||||
|
<LinearLayout
|
||||||
|
android:layout_width="match_parent"
|
||||||
|
android:layout_height="wrap_content"
|
||||||
|
android:orientation="horizontal"
|
||||||
|
android:gravity="top">
|
||||||
|
|
||||||
<TextView
|
<TextView
|
||||||
android:layout_width="34dp"
|
android:layout_width="34dp"
|
||||||
android:layout_height="wrap_content"
|
android:layout_height="wrap_content"
|
||||||
|
android:layout_marginTop="6dp"
|
||||||
android:text="@string/meter_rx"
|
android:text="@string/meter_rx"
|
||||||
android:textColor="@color/text_secondary"
|
android:textColor="@color/text_secondary"
|
||||||
android:textSize="13sp"
|
android:textSize="13sp"
|
||||||
android:textStyle="bold" />
|
android:textStyle="bold" />
|
||||||
|
|
||||||
<FrameLayout
|
<ru.ua1zbe.svxremote.ui.SMeterView
|
||||||
|
android:id="@+id/rx_meter"
|
||||||
android:layout_width="0dp"
|
android:layout_width="0dp"
|
||||||
android:layout_height="16dp"
|
android:layout_height="52dp"
|
||||||
android:layout_weight="1"
|
android:layout_weight="1" />
|
||||||
android:background="@drawable/bg_meter">
|
|
||||||
|
|
||||||
<View
|
|
||||||
android:id="@+id/rx_bar_fill"
|
|
||||||
android:layout_width="match_parent"
|
|
||||||
android:layout_height="match_parent"
|
|
||||||
android:background="@drawable/bg_meter_fill_rx"
|
|
||||||
android:pivotX="0"
|
|
||||||
android:scaleX="0" />
|
|
||||||
</FrameLayout>
|
|
||||||
|
|
||||||
<TextView
|
|
||||||
android:id="@+id/rx_db"
|
|
||||||
android:layout_width="64dp"
|
|
||||||
android:layout_height="wrap_content"
|
|
||||||
android:gravity="end"
|
|
||||||
android:fontFamily="monospace"
|
|
||||||
android:text="@string/meter_idle"
|
|
||||||
android:textColor="@color/text_primary"
|
|
||||||
android:textSize="13sp" />
|
|
||||||
</LinearLayout>
|
</LinearLayout>
|
||||||
|
|
||||||
<LinearLayout
|
<LinearLayout
|
||||||
@@ -154,64 +206,46 @@
|
|||||||
android:layout_height="wrap_content"
|
android:layout_height="wrap_content"
|
||||||
android:layout_marginTop="10dp"
|
android:layout_marginTop="10dp"
|
||||||
android:orientation="horizontal"
|
android:orientation="horizontal"
|
||||||
android:gravity="center_vertical">
|
android:gravity="top">
|
||||||
|
|
||||||
<TextView
|
<TextView
|
||||||
android:layout_width="34dp"
|
android:layout_width="34dp"
|
||||||
android:layout_height="wrap_content"
|
android:layout_height="wrap_content"
|
||||||
|
android:layout_marginTop="6dp"
|
||||||
android:text="@string/meter_mic"
|
android:text="@string/meter_mic"
|
||||||
android:textColor="@color/text_secondary"
|
android:textColor="@color/text_secondary"
|
||||||
android:textSize="13sp"
|
android:textSize="13sp"
|
||||||
android:textStyle="bold" />
|
android:textStyle="bold" />
|
||||||
|
|
||||||
<FrameLayout
|
<ru.ua1zbe.svxremote.ui.SMeterView
|
||||||
|
android:id="@+id/mic_meter"
|
||||||
android:layout_width="0dp"
|
android:layout_width="0dp"
|
||||||
android:layout_height="16dp"
|
android:layout_height="52dp"
|
||||||
android:layout_weight="1"
|
android:layout_weight="1" />
|
||||||
android:background="@drawable/bg_meter">
|
|
||||||
|
|
||||||
<View
|
|
||||||
android:id="@+id/mic_bar_fill"
|
|
||||||
android:layout_width="match_parent"
|
|
||||||
android:layout_height="match_parent"
|
|
||||||
android:background="@drawable/bg_meter_fill_mic"
|
|
||||||
android:pivotX="0"
|
|
||||||
android:scaleX="0" />
|
|
||||||
</FrameLayout>
|
|
||||||
|
|
||||||
<TextView
|
|
||||||
android:id="@+id/mic_db"
|
|
||||||
android:layout_width="64dp"
|
|
||||||
android:layout_height="wrap_content"
|
|
||||||
android:gravity="end"
|
|
||||||
android:fontFamily="monospace"
|
|
||||||
android:text="@string/meter_idle"
|
|
||||||
android:textColor="@color/text_primary"
|
|
||||||
android:textSize="13sp" />
|
|
||||||
</LinearLayout>
|
|
||||||
</LinearLayout>
|
</LinearLayout>
|
||||||
|
|
||||||
<!-- Последний говоривший -->
|
<!-- Статистика приёма (скрытые настройки, по умолчанию выключено) -->
|
||||||
<TextView
|
<TextView
|
||||||
android:id="@+id/lbl_talker_title"
|
android:id="@+id/lbl_rx_stats"
|
||||||
android:layout_width="match_parent"
|
android:layout_width="match_parent"
|
||||||
android:layout_height="wrap_content"
|
android:layout_height="wrap_content"
|
||||||
android:layout_marginTop="24dp"
|
android:layout_marginTop="8dp"
|
||||||
android:gravity="center"
|
android:gravity="center"
|
||||||
android:textColor="@color/text_secondary"
|
android:textColor="@color/text_secondary"
|
||||||
android:textSize="13sp"
|
android:textSize="13sp"
|
||||||
android:text="@string/talker_last_none" />
|
android:visibility="gone" />
|
||||||
|
</LinearLayout>
|
||||||
|
|
||||||
|
<!-- Индикация направления: RX (приём) / TX (передача) -->
|
||||||
<TextView
|
<TextView
|
||||||
android:id="@+id/lbl_talker"
|
android:id="@+id/lbl_duplex"
|
||||||
android:layout_width="match_parent"
|
android:layout_width="wrap_content"
|
||||||
android:layout_height="wrap_content"
|
android:layout_height="wrap_content"
|
||||||
|
android:layout_marginTop="2dp"
|
||||||
android:gravity="center"
|
android:gravity="center"
|
||||||
android:textColor="@color/accent"
|
android:textSize="24sp"
|
||||||
android:textSize="22sp"
|
|
||||||
android:textStyle="bold"
|
android:textStyle="bold"
|
||||||
android:singleLine="true"
|
android:visibility="invisible" />
|
||||||
android:ellipsize="end" />
|
|
||||||
|
|
||||||
<Space
|
<Space
|
||||||
android:layout_width="match_parent"
|
android:layout_width="match_parent"
|
||||||
@@ -221,19 +255,8 @@
|
|||||||
<!-- Кнопка PTT -->
|
<!-- Кнопка PTT -->
|
||||||
<ru.ua1zbe.svxremote.ui.PttButton
|
<ru.ua1zbe.svxremote.ui.PttButton
|
||||||
android:id="@+id/ptt_button"
|
android:id="@+id/ptt_button"
|
||||||
android:layout_width="130dp"
|
android:layout_width="170dp"
|
||||||
android:layout_height="130dp" />
|
android:layout_height="170dp" />
|
||||||
|
|
||||||
<TextView
|
|
||||||
android:id="@+id/lbl_ptt_hint"
|
|
||||||
android:layout_width="wrap_content"
|
|
||||||
android:layout_height="wrap_content"
|
|
||||||
android:layout_marginTop="14dp"
|
|
||||||
android:gravity="center"
|
|
||||||
android:textColor="@color/text_secondary"
|
|
||||||
android:textSize="14sp"
|
|
||||||
android:textStyle="bold"
|
|
||||||
android:text="@string/hold_to_talk" />
|
|
||||||
|
|
||||||
<Space
|
<Space
|
||||||
android:layout_width="match_parent"
|
android:layout_width="match_parent"
|
||||||
|
|||||||
@@ -11,6 +11,23 @@
|
|||||||
android:orientation="vertical"
|
android:orientation="vertical"
|
||||||
android:padding="20dp">
|
android:padding="20dp">
|
||||||
|
|
||||||
|
<TextView
|
||||||
|
android:layout_width="match_parent"
|
||||||
|
android:layout_height="wrap_content"
|
||||||
|
android:text="@string/profiles_label"
|
||||||
|
android:textColor="@color/text_primary"
|
||||||
|
android:textSize="15sp" />
|
||||||
|
|
||||||
|
<Spinner
|
||||||
|
android:id="@+id/spinner_profile"
|
||||||
|
android:layout_width="match_parent"
|
||||||
|
android:layout_height="wrap_content"
|
||||||
|
android:layout_marginBottom="16dp"
|
||||||
|
android:background="@drawable/bg_input"
|
||||||
|
android:padding="12dp"
|
||||||
|
android:spinnerMode="dropdown"
|
||||||
|
android:textColor="@color/text_primary" />
|
||||||
|
|
||||||
<TextView
|
<TextView
|
||||||
android:layout_width="match_parent"
|
android:layout_width="match_parent"
|
||||||
android:layout_height="wrap_content"
|
android:layout_height="wrap_content"
|
||||||
@@ -110,7 +127,7 @@
|
|||||||
android:id="@+id/input_tg"
|
android:id="@+id/input_tg"
|
||||||
android:layout_width="match_parent"
|
android:layout_width="match_parent"
|
||||||
android:layout_height="wrap_content"
|
android:layout_height="wrap_content"
|
||||||
android:layout_marginBottom="24dp"
|
android:layout_marginBottom="16dp"
|
||||||
android:inputType="number"
|
android:inputType="number"
|
||||||
android:textColor="@color/text_primary"
|
android:textColor="@color/text_primary"
|
||||||
android:textColorHint="@color/text_secondary"
|
android:textColorHint="@color/text_secondary"
|
||||||
@@ -119,6 +136,72 @@
|
|||||||
android:padding="12dp"
|
android:padding="12dp"
|
||||||
android:hint="11" />
|
android:hint="11" />
|
||||||
|
|
||||||
|
<TextView
|
||||||
|
android:layout_width="match_parent"
|
||||||
|
android:layout_height="wrap_content"
|
||||||
|
android:text="@string/pref_groups"
|
||||||
|
android:textColor="@color/text_primary"
|
||||||
|
android:textSize="15sp" />
|
||||||
|
|
||||||
|
<EditText
|
||||||
|
android:id="@+id/input_groups"
|
||||||
|
android:layout_width="match_parent"
|
||||||
|
android:layout_height="wrap_content"
|
||||||
|
android:layout_marginBottom="24dp"
|
||||||
|
android:inputType="text"
|
||||||
|
android:textColor="@color/text_primary"
|
||||||
|
android:textColorHint="@color/text_secondary"
|
||||||
|
android:textSize="16sp"
|
||||||
|
android:background="@drawable/bg_input"
|
||||||
|
android:padding="12dp"
|
||||||
|
android:hint="9, 11, 12, 13" />
|
||||||
|
|
||||||
|
<CheckBox
|
||||||
|
android:id="@+id/chk_node_toasts"
|
||||||
|
android:layout_width="match_parent"
|
||||||
|
android:layout_height="wrap_content"
|
||||||
|
android:layout_marginBottom="24dp"
|
||||||
|
android:text="@string/pref_node_toasts"
|
||||||
|
android:textColor="@color/text_primary"
|
||||||
|
android:textSize="15sp" />
|
||||||
|
|
||||||
|
<TextView
|
||||||
|
android:layout_width="match_parent"
|
||||||
|
android:layout_height="wrap_content"
|
||||||
|
android:text="@string/pref_aprs_label"
|
||||||
|
android:textColor="@color/accent"
|
||||||
|
android:textSize="15sp"
|
||||||
|
android:textStyle="bold"
|
||||||
|
android:layout_marginBottom="4dp" />
|
||||||
|
|
||||||
|
<TextView
|
||||||
|
android:layout_width="match_parent"
|
||||||
|
android:layout_height="wrap_content"
|
||||||
|
android:text="@string/pref_aprs_hint"
|
||||||
|
android:textColor="@color/text_secondary"
|
||||||
|
android:textSize="13sp"
|
||||||
|
android:layout_marginBottom="12dp" />
|
||||||
|
|
||||||
|
<TextView
|
||||||
|
android:layout_width="match_parent"
|
||||||
|
android:layout_height="wrap_content"
|
||||||
|
android:text="@string/pref_aprs_coords"
|
||||||
|
android:textColor="@color/text_primary"
|
||||||
|
android:textSize="15sp" />
|
||||||
|
|
||||||
|
<EditText
|
||||||
|
android:id="@+id/input_aprs_coords"
|
||||||
|
android:layout_width="match_parent"
|
||||||
|
android:layout_height="wrap_content"
|
||||||
|
android:layout_marginBottom="24dp"
|
||||||
|
android:inputType="text"
|
||||||
|
android:textColor="@color/text_primary"
|
||||||
|
android:textColorHint="@color/text_secondary"
|
||||||
|
android:textSize="16sp"
|
||||||
|
android:background="@drawable/bg_input"
|
||||||
|
android:padding="12dp"
|
||||||
|
android:hint="@string/pref_aprs_coords_hint" />
|
||||||
|
|
||||||
<Button
|
<Button
|
||||||
android:id="@+id/btn_save"
|
android:id="@+id/btn_save"
|
||||||
android:layout_width="match_parent"
|
android:layout_width="match_parent"
|
||||||
@@ -135,7 +218,6 @@
|
|||||||
android:layout_height="wrap_content"
|
android:layout_height="wrap_content"
|
||||||
android:layout_marginTop="24dp"
|
android:layout_marginTop="24dp"
|
||||||
android:gravity="center"
|
android:gravity="center"
|
||||||
android:text="@string/app_version"
|
|
||||||
android:textColor="@color/text_secondary"
|
android:textColor="@color/text_secondary"
|
||||||
android:textSize="12sp" />
|
android:textSize="12sp" />
|
||||||
</LinearLayout>
|
</LinearLayout>
|
||||||
|
|||||||
41
app/src/main/res/layout/dialog_recording_item.xml
Normal file
41
app/src/main/res/layout/dialog_recording_item.xml
Normal file
@@ -0,0 +1,41 @@
|
|||||||
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
|
||||||
|
android:layout_width="match_parent"
|
||||||
|
android:layout_height="wrap_content"
|
||||||
|
android:orientation="horizontal"
|
||||||
|
android:gravity="center_vertical"
|
||||||
|
android:paddingStart="16dp"
|
||||||
|
android:paddingEnd="8dp"
|
||||||
|
android:paddingTop="10dp"
|
||||||
|
android:paddingBottom="10dp">
|
||||||
|
|
||||||
|
<TextView
|
||||||
|
android:id="@+id/rec_name"
|
||||||
|
android:layout_width="0dp"
|
||||||
|
android:layout_weight="1"
|
||||||
|
android:layout_height="wrap_content"
|
||||||
|
android:textColor="@color/text_primary"
|
||||||
|
android:textSize="14sp"
|
||||||
|
android:singleLine="true"
|
||||||
|
android:ellipsize="middle" />
|
||||||
|
|
||||||
|
<ImageButton
|
||||||
|
android:id="@+id/rec_play"
|
||||||
|
android:layout_width="40dp"
|
||||||
|
android:layout_height="40dp"
|
||||||
|
android:src="@drawable/ic_play"
|
||||||
|
android:tint="@color/accent"
|
||||||
|
android:background="?android:attr/selectableItemBackgroundBorderless"
|
||||||
|
android:scaleType="centerInside"
|
||||||
|
android:contentDescription="Воспроизвести" />
|
||||||
|
|
||||||
|
<ImageButton
|
||||||
|
android:id="@+id/rec_delete"
|
||||||
|
android:layout_width="40dp"
|
||||||
|
android:layout_height="40dp"
|
||||||
|
android:src="@drawable/ic_delete"
|
||||||
|
android:tint="@color/danger"
|
||||||
|
android:background="?android:attr/selectableItemBackgroundBorderless"
|
||||||
|
android:scaleType="centerInside"
|
||||||
|
android:contentDescription="Удалить" />
|
||||||
|
</LinearLayout>
|
||||||
20
app/src/main/res/layout/view_node_toast.xml
Normal file
20
app/src/main/res/layout/view_node_toast.xml
Normal file
@@ -0,0 +1,20 @@
|
|||||||
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
|
||||||
|
android:id="@+id/node_toast_root"
|
||||||
|
android:layout_width="wrap_content"
|
||||||
|
android:layout_height="wrap_content"
|
||||||
|
android:background="@drawable/bg_node_toast"
|
||||||
|
android:paddingLeft="24dp"
|
||||||
|
android:paddingRight="24dp"
|
||||||
|
android:paddingTop="14dp"
|
||||||
|
android:paddingBottom="14dp">
|
||||||
|
|
||||||
|
<TextView
|
||||||
|
android:id="@+id/lbl_node_toast"
|
||||||
|
android:layout_width="wrap_content"
|
||||||
|
android:layout_height="wrap_content"
|
||||||
|
android:gravity="center"
|
||||||
|
android:textColor="#F0F0F0"
|
||||||
|
android:textSize="16sp"
|
||||||
|
android:textStyle="bold" />
|
||||||
|
</FrameLayout>
|
||||||
@@ -9,24 +9,68 @@
|
|||||||
<string name="pref_callsign">Позывной</string>
|
<string name="pref_callsign">Позывной</string>
|
||||||
<string name="pref_auth_key">Пароль (AUTH_KEY)</string>
|
<string name="pref_auth_key">Пароль (AUTH_KEY)</string>
|
||||||
<string name="pref_tg">Группа вещания (TG)</string>
|
<string name="pref_tg">Группа вещания (TG)</string>
|
||||||
|
<string name="pref_groups">Группы для переключения (через запятую)</string>
|
||||||
|
<string name="select_tg">Выбор группы</string>
|
||||||
|
<string name="toast_groups_empty">Добавьте группы в настройках</string>
|
||||||
|
<string name="nodes_title">Узлы в сети (%1$d)</string>
|
||||||
|
<string name="toast_nodes_empty">Нет подключенных узлов</string>
|
||||||
|
<string name="pref_node_toasts">Всплывающее уведомление о подключении/отключении узлов</string>
|
||||||
|
<string name="pref_aprs_label">Метеостанции (APRS)</string>
|
||||||
|
<string name="pref_aprs_hint">Экспериментально: принимает метеостанции в радиусе 250 км. Последняя станция показывается вместо строки сервера на главном экране.</string>
|
||||||
|
<string name="pref_aprs_coords">Координаты (широта, долгота)</string>
|
||||||
|
<string name="pref_aprs_coords_hint">пусто = СПб, напр. 59.95, 30.30</string>
|
||||||
|
<string name="audio_settings_title">Настройки звука</string>
|
||||||
|
<string name="audio_settings_hint">Скрытые настройки: применяются при следующем подключении/передаче.</string>
|
||||||
|
<string name="audio_mic_gain">Усиление микрофона</string>
|
||||||
|
<string name="audio_rx_buffer">Буфер воспроизведения</string>
|
||||||
|
<string name="audio_jitter">Накопление перед стартом</string>
|
||||||
|
<string name="audio_tx_bitrate">Скорость передачи (Opus)</string>
|
||||||
|
<string name="audio_tx_bitrate_auto">Авто</string>
|
||||||
|
<string name="audio_tx_bitrate_fmt">%1$d кбит/с</string>
|
||||||
|
<string name="audio_rx_stats">Показывать статистику приёма (потери/джиттер)</string>
|
||||||
|
<string name="rx_stats_fmt">RX: потери %1$.1f%%, джиттер %2$d мс</string>
|
||||||
|
<string name="toast_node_joined">Подключился: %1$s%2$s</string>
|
||||||
|
<string name="toast_node_left">Отключился: %1$s%2$s</string>
|
||||||
|
<string name="node_tg_suffix"> (группа %1$d)</string>
|
||||||
|
<string name="node_with_tg">%1$s — TG%2$d</string>
|
||||||
<string name="btn_save">Сохранить</string>
|
<string name="btn_save">Сохранить</string>
|
||||||
<string name="app_version">SVXhomyak — v1.0.2</string>
|
<string name="app_version_fmt">SVXhomyak — v%1$s</string>
|
||||||
<string name="saved">Сохранено</string>
|
<string name="saved">Сохранено</string>
|
||||||
<string name="pref_callsign_hint">например UA1ZBE</string>
|
<string name="pref_callsign_hint">например UA1ZBE</string>
|
||||||
|
|
||||||
<string name="status_disconnected">Отключено</string>
|
<string name="status_disconnected">Отключено</string>
|
||||||
<string name="app_title">SVXHomyak</string>
|
<string name="app_title">SVXHomyak</string>
|
||||||
|
<string name="btn_power">Выключить: отключиться и закрыть</string>
|
||||||
|
<string name="btn_record">Запись приёма в файл (нажмите, чтобы начать/остановить)</string>
|
||||||
|
<string name="btn_monitor">Мониторинг групп (нажмите, чтобы включить)</string>
|
||||||
|
<string name="monitoring_dev_warning">Мониторинг выбранных групп!</string>
|
||||||
|
<string name="monitor_off">Обычный режим</string>
|
||||||
|
<string name="btn_monitor_on">Мониторинг групп включен (нажмите, чтобы выключить)</string>
|
||||||
|
<string name="record_started">Запись приёма начата</string>
|
||||||
|
<string name="record_saved">Сохранено: %1$s</string>
|
||||||
|
<string name="record_failed">Не удалось начать запись (формат OGG недоступен)</string>
|
||||||
|
<string name="recordings_title">Записи приёма</string>
|
||||||
|
<string name="record_play_failed">Не удалось воспроизвести запись</string>
|
||||||
|
<string name="record_delete_title">Удалить запись?</string>
|
||||||
|
<string name="record_delete_yes">Удалить</string>
|
||||||
|
<string name="record_deleted">Удалено</string>
|
||||||
|
<string name="status_monitoring">Мониторинг: %1$s</string>
|
||||||
|
<string name="talker_active_fmt">Говорит %1$s TG%2$d</string>
|
||||||
|
<string name="talker_idle_fmt">%1$s TG%2$d</string>
|
||||||
|
<string name="duplex_rx">RX</string>
|
||||||
|
<string name="duplex_tx">TX</string>
|
||||||
<string name="status_big_disconnected">DISCONNECTED</string>
|
<string name="status_big_disconnected">DISCONNECTED</string>
|
||||||
<string name="status_big_connected">CONNECTED</string>
|
<string name="status_big_connected">CONNECTED</string>
|
||||||
<string name="status_big_talking">ПЕРЕДАЧА</string>
|
<string name="status_big_talking">ПЕРЕДАЧА</string>
|
||||||
<string name="hint_connect">Нажмите, чтобы подключиться</string>
|
<string name="hint_connect">Нажмите, чтобы подключиться</string>
|
||||||
<string name="hint_disconnect">Нажмите, чтобы отключиться</string>
|
<string name="hint_disconnect">Нажмите, чтобы отключиться</string>
|
||||||
<string name="hold_to_talk">HOLD TO TALK</string>
|
|
||||||
<string name="meter_rx">RX</string>
|
<string name="meter_rx">RX</string>
|
||||||
<string name="meter_mic">MIC</string>
|
<string name="meter_mic">MIC</string>
|
||||||
<string name="meter_idle">---</string>
|
<string name="meter_idle">---</string>
|
||||||
<string name="meter_db">-%1$d dB</string>
|
<string name="meter_db">+%1$d dB</string>
|
||||||
<string name="tg_badge">TG%1$d</string>
|
<string name="meter_preview_title">Примеры индикаторов звука</string>
|
||||||
|
<string name="meter_preview_hint">Временное демо (уровни симулируются). Скажи, что реализовать по-настоящему.</string>
|
||||||
|
<string name="tg_badge">TG%1$d ▾</string>
|
||||||
<string name="talker_last_none">Последний: —</string>
|
<string name="talker_last_none">Последний: —</string>
|
||||||
<string name="status_connecting">Подключение…</string>
|
<string name="status_connecting">Подключение…</string>
|
||||||
<string name="status_connecting_ssl">Проверка ключа…</string>
|
<string name="status_connecting_ssl">Проверка ключа…</string>
|
||||||
@@ -34,12 +78,13 @@
|
|||||||
<string name="status_auth_failed">Ошибка авторизации</string>
|
<string name="status_auth_failed">Ошибка авторизации</string>
|
||||||
<string name="status_error">Ошибка: %1$s</string>
|
<string name="status_error">Ошибка: %1$s</string>
|
||||||
<string name="notif_connected">Соединение с рефлектором активно</string>
|
<string name="notif_connected">Соединение с рефлектором активно</string>
|
||||||
|
<string name="notif_talking">Говорит: %1$s</string>
|
||||||
|
<string name="notif_last_talker">Последний: %1$s</string>
|
||||||
|
|
||||||
<string name="btn_connect">Подключиться</string>
|
<string name="btn_connect">Подключиться</string>
|
||||||
<string name="btn_disconnect">Отключиться</string>
|
<string name="btn_disconnect">Отключиться</string>
|
||||||
|
|
||||||
<string name="talker_none">—</string>
|
<string name="talker_none">—</string>
|
||||||
<string name="talker_now">Последний: %1$s</string>
|
|
||||||
<string name="talker_on_tg">группа %1$d</string>
|
<string name="talker_on_tg">группа %1$d</string>
|
||||||
|
|
||||||
<string name="ptt_hint">Удерживайте кнопку, чтобы говорить</string>
|
<string name="ptt_hint">Удерживайте кнопку, чтобы говорить</string>
|
||||||
@@ -55,6 +100,16 @@
|
|||||||
<string name="toast_codec_unsupported">Рефлектор требует кодек %1$s — приложение поддерживает только OPUS</string>
|
<string name="toast_codec_unsupported">Рефлектор требует кодек %1$s — приложение поддерживает только OPUS</string>
|
||||||
<string name="toast_settings_empty">Заполните настройки подключения</string>
|
<string name="toast_settings_empty">Заполните настройки подключения</string>
|
||||||
<string name="toast_need_settings">Откройте настройки и укажите сервер и позывной</string>
|
<string name="toast_need_settings">Откройте настройки и укажите сервер и позывной</string>
|
||||||
|
<string name="profiles_label">Профиль настроек</string>
|
||||||
|
<string name="profile_name">Профиль %1$d</string>
|
||||||
|
<string name="profiles_title">Выбор профиля</string>
|
||||||
|
<string name="profile_current"> (текущий)</string>
|
||||||
|
<string name="profile_empty">не настроен</string>
|
||||||
|
<string name="cancel">Отмена</string>
|
||||||
|
<string name="talk_log_title">Последние передачи</string>
|
||||||
|
<string name="talk_log_empty">Журнала передач пока нет</string>
|
||||||
|
<string name="talk_log_entry">%1$s %2$s TG%3$d</string>
|
||||||
|
<string name="close">Закрыть</string>
|
||||||
|
|
||||||
<string name="settings_not_configured">Настройки не заданы</string>
|
<string name="settings_not_configured">Настройки не заданы</string>
|
||||||
<string name="ptt_disabled">Нет связи</string>
|
<string name="ptt_disabled">Нет связи</string>
|
||||||
|
|||||||
Reference in New Issue
Block a user