Skip to content

Instantly share code, notes, and snippets.

@tomaszrykala
Created January 20, 2018 23:58
Show Gist options
  • Save tomaszrykala/0266be668fa5f115238febd8f11b48af to your computer and use it in GitHub Desktop.
Save tomaszrykala/0266be668fa5f115238febd8f11b48af to your computer and use it in GitHub Desktop.
LedStripController.kt
class LedStripController(private val supplier: LedStripSupplier) : BaseController {
private val leds = Led.values().filterNot { it == Led.NONE || it == Led.ALL }
private val ledStates = HashMap<Led, Boolean>(supplier.getLength())
fun light(led: Led) {
when (led) {
Led.ALL -> putAll(true)
else -> ledStates.put(led, true)
}
light()
}
fun reset() {
putAll(false)
light()
}
private fun light() {
val colors = IntArray(ledStates.size)
for (led in ledStates.keys) {
colors[led.index] = if (ledStates[led] as Boolean) led.color else TURN_OFF_COLOR
}
supplier.light(colors)
}
private fun putAll(all: Boolean) {
leds.forEach { ledStates.put(it, all) }
}
@Throws(Exception::class)
override fun close() {
supplier.apply {
reset()
close()
}
}
@VisibleForTesting
fun isLitAt(led: Led): Boolean {
return if (led == Led.ALL) {
ledStates.filterValues { !it }.isEmpty()
} else {
ledStates[led] as Boolean
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment