summaryrefslogtreecommitdiff
path: root/software/communication/data_link.go
blob: 82375bff46b746fb2b9ca08397cf09698d33119b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
package communication

import (
	"log"
)

const (
	SLIP_END         = 0xC0
	SLIP_ESC         = 0xDB
	SLIP_ESC_END     = 0xDC
	SLIP_ESC_ESC     = 0xDD
	SLIP_MAX_PAYLOAD = 1500
)

type dataLink struct {
	rx chan []byte
}

func newDataLink() dataLink {
	dl := dataLink{}

	dl.rx = make(chan []byte)

	return dl
}

func (dl *dataLink) start(source chan byte) {
	go dl.receive(source)
}

func (dl *dataLink) receive(source chan byte) {
	for {
		frame := unslip(source)
		dl.rx <- frame
	}
}

func unslip(source chan byte) []byte {
	buffer := make([]byte, 0)

	for {
		octet := <-source
		switch octet {
		case SLIP_ESC:
			escaped := <-source
			switch escaped {
			case SLIP_ESC_END:
				buffer = append(buffer, SLIP_END)
			case SLIP_ESC_ESC:
				buffer = append(buffer, SLIP_ESC)
			default:
				log.Printf("SLIP: Invalid 0x%x followed an escape byte", escaped)
			}
		case SLIP_END:
			return buffer
		default:
			buffer = append(buffer, octet)
		}
	}
}