Enable batch processing in Sonos worker

From now on, the Sonos worker dumps the Sonos state before the first
request and restores it only after the last request.
This resolved the issue of often not resuming playback
when more than one query was enqueued.
This commit is contained in:
2020-05-23 22:20:36 +02:00
parent 9b7861fccd
commit bba4e1ca31

View File

@@ -4,7 +4,10 @@ import com.bartlomiejpluta.ttsserver.core.tts.engine.TTSEngine
import com.bartlomiejpluta.ttsserver.core.web.dto.SonosDTO
import com.bartlomiejpluta.ttsserver.service.foreground.ForegroundService
import com.bartlomiejpluta.ttsserver.service.state.ServiceState
import com.vmichalak.sonoscontroller.Snapshot
import com.vmichalak.sonoscontroller.SonosDevice
import com.vmichalak.sonoscontroller.SonosDiscovery
import com.vmichalak.sonoscontroller.model.PlayState
import java.util.concurrent.BlockingQueue
class SonosWorker(
@@ -12,6 +15,7 @@ class SonosWorker(
private val address: String,
private val queue: BlockingQueue<SonosDTO>
) : Runnable {
private var snapshot: Snapshot? = null
override fun run() = try {
while (ForegroundService.state == ServiceState.RUNNING) {
@@ -23,9 +27,36 @@ class SonosWorker(
private fun consume(data: SonosDTO) =
SonosDiscovery.discover().firstOrNull { it.zoneGroupState.name == data.zone }?.let {
val file = tts.createTTSFile(data.text, data.language)
val filename = file.name
val url = "$address/sonos/$filename"
it.clip(url, data.volume, "")
updateSnapshotIfFirst(it)
val url = prepareTTSFile(data)
announce(it, data, url)
restoreSnapshotIfLast()
}
private fun prepareTTSFile(data: SonosDTO): String {
val filename = tts.createTTSFile(data.text, data.language).name
return "$address/sonos/$filename"
}
private fun announce(device: SonosDevice, data: SonosDTO, url: String) {
device.stop()
device.volume = data.volume
device.playUri(url, "")
while (device.playState != PlayState.STOPPED) {
Thread.sleep(500)
}
}
private fun updateSnapshotIfFirst(it: SonosDevice) {
if (snapshot == null) {
snapshot = it.snapshot()
}
}
private fun restoreSnapshotIfLast() {
if (queue.isEmpty()) {
snapshot!!.restore()
snapshot = null
}
}
}