summaryrefslogtreecommitdiff
path: root/software/communication/physical.go
blob: 3f61590e2221074151d696a545921a3a94e3ae68 (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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
package communication

import (
	"fmt"
	"log"

	"go.bug.st/serial"
	"go.bug.st/serial/enumerator"
)

const (
	ST_VID = `0483`
)

type physical struct {
	port serial.Port
	rx   chan byte
}

func newPhysical() (physical, error) {
	p := physical{}

	devices, err := getStSerials()
	if err != nil {
		return p, err
	}

	if len(devices) != 1 {
		return p, fmt.Errorf("Require exactly one serial device from STMicroelectronics but %d attached", len(devices))
	}
	device := devices[0]

	p.port, err = openSerial(device)
	if err != nil {
		return p, err
	}

	p.rx = make(chan byte)

	return p, nil
}

func (p *physical) start() {
	go p.receive()
}

func getStSerials() ([]string, error) {
	retval := make([]string, 0)

	ports, err := enumerator.GetDetailedPortsList()
	if err != nil {
		return retval, err
	}

	for _, port := range ports {
		if port.IsUSB {
			if port.VID == ST_VID {
				retval = append(retval, port.Name)
			}
		}
	}

	return retval, nil
}

func openSerial(device string) (serial.Port, error) {
	var port serial.Port
	mode := &serial.Mode{
		BaudRate: 115200,
	}
	port, err := serial.Open(device, mode)
	if err != nil {
		return port, err
	}
	return port, nil
}

func (p *physical) receive() {
	for {
		buff := make([]byte, 100)
		n, err := p.port.Read(buff)
		if err != nil {
			log.Fatal(err)
		}
		for i := 0; i < n; i++ {
			p.rx <- buff[i]
		}
	}
}