-
Notifications
You must be signed in to change notification settings - Fork 1
/
watch.go
79 lines (68 loc) · 1.55 KB
/
watch.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
package core
import (
"github.com/robgonnella/ardi/v2/rpc"
log "github.com/sirupsen/logrus"
)
// WatchCore represents core module for adi go commands
type WatchCore struct {
logger *log.Logger
uploader *UploadCore
compiler *CompileCore
port SerialPort
watcher *FileWatcher
}
// NewWatchCore returns new Project instance
func NewWatchCore(compiler *CompileCore, uploader *UploadCore, logger *log.Logger) *WatchCore {
return &WatchCore{
uploader: uploader,
compiler: compiler,
logger: logger,
}
}
// Watch responds to changes in a given sketch file by automatically
// recompiling and re-uploading.
func (w *WatchCore) Watch(compileOpts rpc.CompileOpts, board *rpc.Board, baud int, port SerialPort) error {
if w.watcher != nil {
w.watcher.Close()
w.watcher = nil
}
watcher, err := NewFileWatcher(compileOpts.SketchPath, w.logger)
if err != nil {
return err
}
w.watcher = watcher
if w.port != nil {
w.port.Stop()
w.port = nil
}
if port == nil {
port = NewArdiSerialPort(board.Port, baud, w.logger)
} else {
port.Stop()
}
w.port = port
watcher.AddListener(func() {
port.Stop()
err := w.compiler.Compile(compileOpts)
if err == nil {
w.logger.Info("Reuploading")
w.uploader.Upload(board, compileOpts.SketchDir)
w.logger.Info("Upload successful")
go port.Watch()
}
})
go port.Watch()
watcher.Watch()
return nil
}
// Stop deletes watcher and unattaches from port
func (w *WatchCore) Stop() {
if w.watcher != nil {
w.watcher.Close()
w.watcher = nil
}
if w.port != nil {
w.port.Stop()
w.port = nil
}
}