Last active
December 7, 2021 14:14
-
-
Save oliverepper/254d991ade6e85752145d401ce65d8c6 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
import Foundation | |
enum OneOff {} | |
enum Sustained {} | |
struct KuandoCommand<Kind>: ExpressibleByArrayLiteral { | |
typealias ArrayLiteralElement = UInt8 | |
private(set) var data = [ArrayLiteralElement](repeating: 0, count: 64) | |
var length: Int { | |
64 | |
} | |
init(arrayLiteral elements: ArrayLiteralElement...) { | |
data.replaceSubrange(0...elements.count - 1, with: elements) | |
checksum() | |
} | |
mutating func checksum() { | |
var checksum: UInt16 = 0 | |
data[59] = 255 | |
data[60] = 255 | |
data[61] = 255 | |
data.prefix(62).forEach { value in | |
checksum += UInt16(value) | |
} | |
data[62] = UInt8(checksum / 256) | |
data[63] = UInt8(checksum % 256) | |
} | |
static func solid(color: UInt8...) -> Self { | |
var cmd = Self.init(arrayLiteral: 0b00010001,1,100,0,0,240,0,0b1000_0000,0b0001_0000) | |
cmd.data[2] = color[0] | |
cmd.data[3] = color[1] | |
cmd.data[4] = color[2] | |
cmd.checksum() | |
return cmd | |
} | |
static func blink(color: UInt8...) -> Self { | |
var cmd = Self.init(arrayLiteral: 0b00010001,1,100,50,0,12,12,0b1011_0111,0b0001_0000) | |
cmd.data[2] = color[0] | |
cmd.data[3] = color[1] | |
cmd.data[4] = color[2] | |
cmd.checksum() | |
return cmd | |
} | |
} | |
extension KuandoCommand where Kind == OneOff { | |
static let reset = KuandoCommand<OneOff>(arrayLiteral: 0b0010_0000,1) | |
static let stop = KuandoCommand<OneOff>(arrayLiteral: 0b0001_0001,1,0,0,0,10,0,0b1000_0000,0b1000_0001) | |
} | |
extension KuandoCommand where Kind == Sustained { | |
static let busy = KuandoCommand<Sustained>.solid(color: 100,0,0) | |
static let ringing = KuandoCommand<Sustained>.blink(color: 100,50,0) | |
} | |
func set(_ cmd: KuandoCommand<Sustained>) { | |
print(cmd.data) | |
} | |
func send(_ cmd: KuandoCommand<OneOff>) { | |
print(cmd.data) | |
} | |
send(.reset) | |
set(.busy) | |
// set(.reset) <- Compiler Error | |
// send(.busy) <- Compiler Error |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment