-
Notifications
You must be signed in to change notification settings - Fork 0
/
xbeeapi.go
119 lines (96 loc) · 1.88 KB
/
xbeeapi.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
package xbeeapi
import (
"errors"
"io"
"log"
"sync"
"time"
)
type XBeeStatusType byte
type ReadCallback func(frame *Frame, status XBeeReadStatus)
const (
XBeeOK XBeeStatusType = iota
XBeeClose
XBeeReadError
XBeeUnknownStatus
)
type XBeeReadStatus struct {
StatusCode XBeeStatusType
Error error
}
type XBeeAPI struct {
fwr *frameReadWriter
readCb ReadCallback
mu *sync.Mutex
running bool
}
func NewXBeeAPI(port io.ReadWriter, readCb ReadCallback) *XBeeAPI {
return &XBeeAPI{
fwr: newFrameReader(port),
readCb: readCb,
mu: &sync.Mutex{},
running: false,
}
}
func (api *XBeeAPI) Start() error {
var err error
api.mu.Lock()
if api.running {
err = errors.New("XBeeAPI already started")
} else {
api.running = true
}
api.mu.Unlock()
if err != nil {
return err
}
api.fwr.init()
go func() {
for {
if !api.Running() {
log.Println("Stopping...")
return
}
err := api.readFrames()
if err != nil {
time.Sleep(200 * time.Millisecond)
log.Println("Reader error:", err)
}
}
}()
return nil
}
func (api *XBeeAPI) SendRawFrames(frame ...*Frame) (int, error) {
n, err := api.fwr.write(frame...)
return n, err
}
func (api *XBeeAPI) SendFrames(frameData ...FrameData) (int, error) {
frames := []*Frame(nil)
for _, fd := range frameData {
frames = append(frames, NewFrame(fd))
}
return api.SendRawFrames(frames...)
}
func (api *XBeeAPI) readFrames() error {
frames, err := api.fwr.read()
if err != nil {
api.readCb(nil, XBeeReadStatus{StatusCode: XBeeReadError, Error: err})
return err
}
for _, frame := range frames {
api.readCb(frame, XBeeReadStatus{StatusCode: XBeeOK, Error: nil})
}
return nil
}
func (api *XBeeAPI) Running() (r bool) {
api.mu.Lock()
r = api.running
api.mu.Unlock()
return
}
func (api *XBeeAPI) Finish() {
api.mu.Lock()
api.running = false
api.fwr.init()
api.mu.Unlock()
}