Skip to content

Commit

Permalink
[api]: Improve device event hub
Browse files Browse the repository at this point in the history
  • Loading branch information
tiagohm committed Aug 20, 2024
1 parent 6866473 commit 151b38d
Show file tree
Hide file tree
Showing 2 changed files with 4 additions and 19 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ import nebulosa.api.mounts.MountEventHub
import nebulosa.api.rotators.RotatorEventHub
import nebulosa.api.wheels.WheelEventHub
import nebulosa.indi.device.DeviceConnectionEvent
import nebulosa.indi.device.DeviceDetached
import nebulosa.indi.device.DeviceEvent
import nebulosa.indi.device.DeviceEventHandler
import nebulosa.indi.device.camera.Camera
Expand Down Expand Up @@ -38,13 +37,6 @@ class ConnectionEventHub(
if (device is FilterWheel) wheelEventHub.onConnectionChanged(device)
if (device is Rotator) rotatorEventHub.onConnectionChanged(device)
if (device is GuideOutput) guideOutputEventHub.onConnectionChanged(device)
} else if (event is DeviceDetached<*>) {
if (device is Camera) cameraEventHub.onDeviceDetached(device)
if (device is Mount) mountEventHub.onDeviceDetached(device)
if (device is Focuser) focuserEventHub.onDeviceDetached(device)
if (device is FilterWheel) wheelEventHub.onDeviceDetached(device)
if (device is Rotator) rotatorEventHub.onDeviceDetached(device)
if (device is GuideOutput) guideOutputEventHub.onDeviceDetached(device)
}
}
}
15 changes: 4 additions & 11 deletions api/src/main/kotlin/nebulosa/api/devices/DeviceEventHub.kt
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import java.util.concurrent.TimeUnit

abstract class DeviceEventHub<D : Device, E : DeviceEvent<D>>(deviceType: DeviceType) : Consumer<E>, AutoCloseable {

private val throttlers = HashMap<D, Throttler>(4)
private val throttlers = ConcurrentHashMap<D, Throttler>(4)
private val listenable = ConcurrentHashMap<D, Long>(2)

private val updateEventName = "$deviceType.UPDATED"
Expand All @@ -25,29 +25,22 @@ abstract class DeviceEventHub<D : Device, E : DeviceEvent<D>>(deviceType: Device
}

open fun onAttached(device: D) {
throttlers.computeIfAbsent(device) { Throttler() }
sendMessage(attachedEventName, device)
}

open fun onDetached(device: D) {
sendMessage(detachedEventName, device)
throttlers.remove(device)?.onComplete()
}

open fun onConnectionChanged(device: D) {
sendUpdate(device)
}

open fun onDeviceDetached(device: D) {
synchronized(throttlers) {
throttlers.remove(device)?.onComplete()
}
}

protected open fun onNext(event: E) {
val device = event.device ?: return

synchronized(throttlers) {
throttlers.getOrPut(device, ::Throttler).onNext(event)
}
throttlers[device]?.onNext(event)
}

fun listen(device: D): Boolean {
Expand Down

0 comments on commit 151b38d

Please sign in to comment.