Permalink
Cannot retrieve contributors at this time
Name already in use
A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
i2cfun-androidthings/app/src/main/java/com/nilhcem/androidthings/i2cfun/device/components/ArduinoFanI2C.kt
Go to fileThis commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
44 lines (32 sloc)
1.3 KB
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.nilhcem.androidthings.i2cfun.device.components | |
import com.google.android.things.pio.I2cDevice | |
import com.google.android.things.pio.PeripheralManager | |
import com.nilhcem.androidthings.i2cfun.core.ext.toPositiveInt | |
class ArduinoFanI2C(i2cName: String, i2cAddress: Int) : AutoCloseable { | |
companion object { | |
private const val COMMAND_ON_OFF = 0x01 | |
private const val COMMAND_SPEED = 0x02 | |
private const val VALUE_ON = 1.toByte() | |
private const val VALUE_OFF = 0.toByte() | |
} | |
enum class Speed(val i2cValue: Int) { | |
LOW(150), MEDIUM(200), HIGH(250); | |
companion object { | |
fun fromValue(i2cValue: Int) = Speed.values().firstOrNull { it.i2cValue == i2cValue } ?: MEDIUM | |
} | |
} | |
private var device: I2cDevice? = null | |
init { | |
device = PeripheralManager.getInstance().openI2cDevice(i2cName, i2cAddress) | |
} | |
var speed: Speed | |
get() = Speed.fromValue(device?.readRegByte(COMMAND_SPEED)?.toPositiveInt() ?: 0) | |
set(value) { | |
device?.writeRegByte(COMMAND_SPEED, value.i2cValue.toByte()) | |
} | |
override fun close() { | |
device?.close().also { device = null } | |
} | |
fun start() = device?.writeRegByte(COMMAND_ON_OFF, VALUE_ON) | |
fun stop() = device?.writeRegByte(COMMAND_ON_OFF, VALUE_OFF) | |
} |