Created
June 11, 2017 10:44
-
-
Save hoiberg/334b3cbf9c72a8ee896e117b1fc631de to your computer and use it in GitHub Desktop.
A simple communications protocol
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
let START_BYTE: UInt8 = 0x42 // or whatever | |
let ACTION_ON: UInt8 = 0x01 // or whatever | |
let ACTION_SLIDER: UInt8 = 0x02 // same here | |
var state = 0 | |
var code: UInt8 = 0 | |
var expected_count = 0 | |
var data = [UInt8]() | |
func serialDidReceiveBytes(bytes: [UInt8]) { | |
for b in bytes { | |
switch state { | |
case 0: | |
// expect start byte | |
if b == START_BYTE { | |
// yay! a new beginning | |
state += 1 | |
continue | |
} else { | |
// fail. better luck next time | |
continue | |
} | |
case 1: | |
// expect a code byte | |
switch b { | |
case ACTION_ON: | |
// no data bytes needed, perform action and reset | |
do_action_on() | |
reset() | |
continue | |
case ACTION_SLIDER: | |
// two data bytes needed | |
code = ACTION_SLIDER | |
expected_count = 2 | |
state += 1 | |
continue | |
default: | |
// error! reset! | |
reset() | |
continue | |
} | |
case 2: | |
// expect a data byte | |
data.append(b) | |
if data.count == expected_count { | |
// perform action and reset | |
switch code { | |
case ACTION_SLIDER: | |
do_action_slider_with_data(data) | |
default: | |
// error | |
break | |
} | |
reset() | |
} | |
continue | |
} | |
} | |
} | |
func reset() { | |
state = 0 | |
code = 0 | |
expected_count = 0 | |
data = [] | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment