Background:
I have a project where I need to communicate with bytes (serial protocol, using ports) where I wanted to send and receive bytes to & from ports. I’m currently using List Int because it’s easy to send over the js bridge (not sure if I can do that with Bytes)
The communication is a Request/OKResponse/Error protocol where each of them has commands associated. The structure is pretty much like this:
Request = 0x1
OKResponse= 0x2
Error = 0x3
(in reality they have parameters and all, omitted for the post).
where cmd is a byte, so we can correlate response and commands.
For example:
CmdFoo = 0x11
CmdBar = 0x22
So, when I want to request Foo, I would write [Request CmdFoo] in bytes [0x1, 0x11]
and wait until I got a response. If I get [0x2, 0x11], I know that it’s a successful response for foo [OKResponse, CmdFoo].
Questions:
How would you make conversions between those commands and the byte representation? Would you do
type CommandByte = Byte Int
type Command = CmdFoo | CmdBar
commandToCommandByte : Command -> CommandByte
commandToCommandByte cmd = case cmd of
CmdFoo -> 0x11
CmdBar -> 0x22
commandByteToCommand : CommandByte -> Maybe Command
-- same idea, in reverse
or would you maintain
mapping : List (Command, CommandByte)
but you’re forced to write List.filter followed by `List.Maybe for either direction…
let me know, how would you approach this? Would you have used Bytes.Encode? I would’ve used if I knew it existed ( I didn’t know as I’m starting out) and I don’t know if it can be sent over ports…