-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcivkeyer.go
More file actions
125 lines (104 loc) · 2.35 KB
/
Copy pathcivkeyer.go
File metadata and controls
125 lines (104 loc) · 2.35 KB
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
package main
import (
"bytes"
"fmt"
"log"
"time"
"github.com/tarm/serial"
)
var (
// application configuration
config configuration
// civ connection
port *serial.Port
// user specified configuration file
configFile string
)
// readCIVMessageFromPort reads bytes from port and returns CIV message as string
func readCIVMessageFromPort(p *serial.Port) ([]byte, error) {
var buf bytes.Buffer
b := []byte{0}
for {
n, err := p.Read(b)
if err != nil {
log.Printf("%+v", err)
return []byte{}, err
}
if n > 0 {
// accumulate message bytes
buf.Write(b)
// message terminator?
if b[0] == 0xFD {
// return CIV message
return buf.Bytes(), nil
}
} else {
// no data available to read within timeout
return []byte{}, nil
}
}
}
// executeFunction writes the appropriate CIV message associated with function to the configured CIV port
func executeFunction(function int) error {
var err error
// connect to CIV port, if we aren't already
if port == nil {
c := &serial.Config{
Name: config.Connection.Port,
Baud: config.Connection.Baud,
ReadTimeout: time.Second * 10,
}
port, err = serial.OpenPort(c)
if err != nil {
err = fmt.Errorf("%+v Port: %s, Baud: %d", err, c.Name, c.Baud)
log.Printf("%+v", err)
return err
}
}
// write message bytes to port
b := config.Functions[function].Message
_, err = port.Write(b)
if err != nil {
// close the port to force a reconnect next time
port.Close()
port = nil
log.Printf("%+v %X", err, b)
return err
}
// check response from radio
if config.Functions[function].ExpectReply {
for {
r, err := readCIVMessageFromPort(port)
if err != nil {
log.Printf("%+v %X", err, b)
return err
}
// valid responses should be at least 6 bytes
if len(r) < 6 {
err = fmt.Errorf("invalid response from radio")
log.Printf("%+v %X %X", err, b, r)
return err
}
// message for us from radio?
if r[2] == 0xE0 {
// check status returned from radio
if r[4] != 0xFB {
err = fmt.Errorf("error response from radio")
log.Printf("%+v %X %X", err, b, r)
return err
}
break
}
}
}
return nil
}
func main() {
// show file & location, date & time
log.SetFlags(log.Ldate | log.Ltime | log.Lshortfile)
err := civkeyerWindow()
if err != nil {
log.Fatalf("%+v", err)
}
port.Close()
}