-
Notifications
You must be signed in to change notification settings - Fork 9
/
main.go
136 lines (110 loc) · 2.26 KB
/
main.go
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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
package main
import (
"flag"
"fmt"
"os"
"os/signal"
"sync"
"time"
"github.com/kidoman/embd"
_ "github.com/kidoman/embd/host/rpi"
"github.com/carloop/simulator-program/mcp2515"
)
func main() {
flag.Parse()
err := embd.InitSPI()
if err != nil {
panic(err)
}
defer embd.CloseSPI()
const (
device = 0
speed = 1e5
bpw = 8
delay = 0
channel = 0
)
spi := embd.NewSPIBus(embd.SPIMode0, device, int(speed), bpw, delay)
defer spi.Close()
canDevice := mcp2515.New(spi)
err = canDevice.Setup(500000)
if err != nil {
printError(err)
return
}
rxChan := make(mcp2515.MsgChan, 10)
txChan := make(mcp2515.MsgChan, 10)
errChan := make(mcp2515.ErrChan, 10)
var wg sync.WaitGroup
wg.Add(1)
go func() {
defer wg.Done()
mcp2515.RunMessageLoop(canDevice, rxChan, txChan, errChan)
}()
wg.Add(1)
go func() {
defer wg.Done()
printCanMessages(rxChan, txChan, errChan)
}()
wg.Add(1)
go func() {
defer wg.Done()
sendMessages(txChan)
}()
// Wait for all goroutines to be done
wg.Wait()
}
func printCanMessages(rxChan mcp2515.MsgChan, txChan mcp2515.MsgChan,
errChan mcp2515.ErrChan) {
fmt.Println("Starting CAN receiver")
startTime := time.Now()
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt)
for {
select {
case rxMessage := <-rxChan:
printMessage(rxMessage, startTime)
case err := <-errChan:
printError(err)
case <-c:
// Program done
return
}
}
}
func printMessage(message *mcp2515.Message, startTime time.Time) {
timeOffset := message.Time.Sub(startTime).Seconds()
fmt.Printf("%15.6f %03x %d", timeOffset, message.Id, message.Length)
for i := uint8(0); i < message.Length; i++ {
fmt.Printf(" %02x", message.Data[i])
}
fmt.Println("")
}
func printError(err error) {
fmt.Printf("Error occured: %v", err)
fmt.Println("")
}
func sendMessages(txChan mcp2515.MsgChan) {
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt)
i := uint8(0)
for {
var message mcp2515.Message
message.Id = 0x2AA
message.Length = 8
for j := 0; j < 8; j++ {
message.Data[j] = 0xAA
}
i += 1
select {
case txChan <- &message:
// Message added to queue
case <-c:
// Program done
return
default:
// If tx channel is full, ignore
}
time.Sleep(10 * time.Millisecond)
}
}