mirror of
https://github.com/jwetzell/showbridge-go.git
synced 2026-04-27 05:15:47 +00:00
add SLIP framing
This commit is contained in:
52
internals/framing/slip.go
Normal file
52
internals/framing/slip.go
Normal file
@@ -0,0 +1,52 @@
|
|||||||
|
package framing
|
||||||
|
|
||||||
|
type SlipFramer struct {
|
||||||
|
buffer []byte
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewSlipFramer() *SlipFramer {
|
||||||
|
return &SlipFramer{buffer: []byte{}}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (sf *SlipFramer) Frame(data []byte) [][]byte {
|
||||||
|
messages := [][]byte{}
|
||||||
|
END := byte(0xc0)
|
||||||
|
ESC := byte(0xdb)
|
||||||
|
ESC_END := byte(0xdc)
|
||||||
|
ESC_ESC := byte(0xdd)
|
||||||
|
|
||||||
|
escapeNext := false
|
||||||
|
for _, packetByte := range data {
|
||||||
|
|
||||||
|
if packetByte == ESC {
|
||||||
|
escapeNext = true
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
if escapeNext {
|
||||||
|
if packetByte == ESC_END {
|
||||||
|
sf.buffer = append(sf.buffer, END)
|
||||||
|
} else if packetByte == ESC_ESC {
|
||||||
|
sf.buffer = append(sf.buffer, ESC)
|
||||||
|
}
|
||||||
|
escapeNext = false
|
||||||
|
} else if packetByte == END {
|
||||||
|
if len(sf.buffer) == 0 {
|
||||||
|
// opening END byte, can discard
|
||||||
|
continue
|
||||||
|
} else {
|
||||||
|
message := sf.buffer
|
||||||
|
messages = append(messages, message)
|
||||||
|
}
|
||||||
|
sf.buffer = []byte{}
|
||||||
|
} else {
|
||||||
|
sf.buffer = append(sf.buffer, packetByte)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return messages
|
||||||
|
}
|
||||||
|
|
||||||
|
func (sf *SlipFramer) Clear() {
|
||||||
|
sf.buffer = []byte{}
|
||||||
|
}
|
||||||
@@ -65,6 +65,8 @@ func init() {
|
|||||||
framer = framing.NewByteSeparatorFramer([]byte{'\n'})
|
framer = framing.NewByteSeparatorFramer([]byte{'\n'})
|
||||||
case "CRLF":
|
case "CRLF":
|
||||||
framer = framing.NewByteSeparatorFramer([]byte{'\r', '\n'})
|
framer = framing.NewByteSeparatorFramer([]byte{'\r', '\n'})
|
||||||
|
case "SLIP":
|
||||||
|
framer = framing.NewSlipFramer()
|
||||||
default:
|
default:
|
||||||
return nil, fmt.Errorf("unknown framing method: %s", framingMethodString)
|
return nil, fmt.Errorf("unknown framing method: %s", framingMethodString)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -67,6 +67,8 @@ func (ts TCPServer) HandleClient(ctx context.Context, client net.Conn) {
|
|||||||
framer = framing.NewByteSeparatorFramer([]byte{'\r'})
|
framer = framing.NewByteSeparatorFramer([]byte{'\r'})
|
||||||
case "CRLF":
|
case "CRLF":
|
||||||
framer = framing.NewByteSeparatorFramer([]byte{'\r', '\n'})
|
framer = framing.NewByteSeparatorFramer([]byte{'\r', '\n'})
|
||||||
|
case "SLIP":
|
||||||
|
framer = framing.NewSlipFramer()
|
||||||
}
|
}
|
||||||
|
|
||||||
buffer := make([]byte, 1024)
|
buffer := make([]byte, 1024)
|
||||||
|
|||||||
Reference in New Issue
Block a user