-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathmain.go
287 lines (258 loc) · 6.51 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
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
// Package chissoku implements main chissoku program
package main
import (
"bufio"
"context"
"fmt"
"io"
"log/slog"
"os"
"os/signal"
"reflect"
"regexp"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/alecthomas/kong"
"go.bug.st/serial"
"github.com/northeye/chissoku/options"
"github.com/northeye/chissoku/output"
"github.com/northeye/chissoku/types"
)
func main() {
var c Chissoku
ctx := kong.Parse(&c,
kong.Name(ProgramName),
kong.Vars{"version": "v" + Version, "outputters": strings.Join(c.registerOutputters(), ",")},
kong.Description(Description),
kong.Bind(&c.Options))
if err := ctx.Run(); err != nil {
slog.Error("chissoku.Run()", "error", err)
os.Exit(1)
}
}
// Chissoku main program
type Chissoku struct {
// Options
Options options.Options `embed:""`
// Stdout output
output.Stdout `prefix:"stdout." group:"Stdout Output:"`
// MQTT output
output.Mqtt `prefix:"mqtt." group:"MQTT Output:"`
// available outputters
outputters map[string]output.Outputter
// active outputters
activeOutputters atomic.Value
// reader channel
rchan chan *types.Data
// deactivate outputter
dechan chan string
// cancel
cancel func()
// serial device
port serial.Port
// serial scanner
scanner *bufio.Scanner
// cleanup
cleanup func()
}
// AfterApply kong hook
func (c *Chissoku) AfterApply(opts *options.Options) error {
var writer io.Writer = os.Stderr
level := slog.LevelInfo
if opts.Debug {
level = slog.LevelDebug
}
if opts.Quiet {
writer = io.Discard
}
slog.SetDefault(slog.New(slog.NewJSONHandler(writer, &slog.HandlerOptions{Level: level})))
c.rchan = make(chan *types.Data)
c.dechan = make(chan string)
ctx := output.ContextWithDeactivateChannel(context.Background(), c.dechan)
ctx = context.WithValue(ctx, options.ContextKeyOptions{}, opts)
ctx, c.cancel = context.WithCancel(ctx)
// initialize and filter outputters
a := make(map[string]output.Outputter, len(opts.Output))
for _, name := range opts.Output {
if o, ok := c.outputters[name]; ok {
if err := o.Initialize(ctx); err != nil {
slog.Error("Initialize outputter", "outputter", o.Name(), "error", err)
continue
}
a[name] = o
}
}
if len(a) == 0 {
return fmt.Errorf("no active outputters are avaiable")
}
c.activeOutputters.Store(a)
c.cleanup = sync.OnceFunc(func() {
// exit the program cleanly
c.cancel()
for _, o := range c.activeOutputters.Load().(map[string]output.Outputter) {
o.Close()
}
if c.port != nil {
slog.Debug("Sending command", "command", CommandSTP)
// nolint: errcheck
c.port.Write([]byte(CommandSTP + "\r\n"))
}
})
return nil
}
const (
// CommandSTP the STP Command
CommandSTP string = `STP`
// CommandID the ID? Command
CommandID string = `ID?`
// CommandSTA the STA Command
CommandSTA string = `STA`
// ResponseOK the OK response
ResponseOK string = `OK`
// ResponseNG the NG response
ResponseNG string = `NG`
)
// Run run the program
func (c *Chissoku) Run() (err error) {
slog.Debug("Start", "name", ProgramName, "version", Version)
opts := &c.Options
if c.port, err = serial.Open(opts.Device, &serial.Mode{
BaudRate: 115200,
DataBits: 8,
StopBits: serial.OneStopBit,
Parity: serial.NoParity,
}); err != nil {
slog.Error("Opening serial", "error", err, "device", opts.Device)
return err
}
c.port.SetReadTimeout(time.Second * 10)
// initialize UD-CO2S
if err := c.prepareDevice(); err != nil {
return err
}
// signalHandler
sigch := make(chan os.Signal, 1)
signal.Notify(sigch, os.Interrupt)
// signal handler
go func() {
<-sigch
c.cleanup()
<-time.After(time.Second)
slog.Error("No response from device")
os.Exit(128)
}()
// main
go c.dispatch()
if err = c.readDevice(); err != nil {
slog.Error("Error on readDevice", "err", err)
}
slog.Debug("Close Serial port")
c.port.Close()
return err
}
// readDevice read data from serial device
func (c *Chissoku) readDevice() error {
re := regexp.MustCompile(`CO2=(\d+),HUM=([0-9\.]+),TMP=([0-9\.-]+)`)
// as main loop
for c.scanner.Scan() {
text := c.scanner.Text()
m := re.FindAllStringSubmatch(text, -1)
if len(m) > 0 {
d := &types.Data{Timestamp: types.ISO8601Time(time.Now()), Tags: c.Options.Tags}
d.CO2, _ = strconv.ParseInt(m[0][1], 10, 64)
d.Humidity, _ = strconv.ParseFloat(m[0][2], 64)
d.Temperature, _ = strconv.ParseFloat(m[0][3], 64)
c.rchan <- d
} else if text[:6] == `OK STP` {
return nil // exit 0
} else {
slog.Warn("Read unmatched string", "str", text)
}
}
if err := c.scanner.Err(); err != nil {
slog.Error("Scanner read error", "error", err)
c.cleanup()
return err
}
return nil
}
func (c *Chissoku) dispatch() {
for {
select {
case deactivate := <-c.dechan:
a := c.activeOutputters.Load().(map[string]output.Outputter)
delete(a, deactivate)
if len(a) == 0 {
slog.Debug("No outputers are alive")
c.cleanup()
return
}
c.activeOutputters.Store(a)
case data, more := <-c.rchan:
if !more {
slog.Debug("Reader channel has ben closed")
return
}
for _, o := range c.activeOutputters.Load().(map[string]output.Outputter) {
o.Output(data)
}
}
}
}
// initialize and prepare the device
func (c *Chissoku) prepareDevice() (err error) {
c.scanner = bufio.NewScanner(c.port)
c.scanner.Split(bufio.ScanLines)
commands := []string{CommandSTP, CommandID, CommandSTA}
do := make([]string, 0, len(commands))
defer func() {
level := slog.LevelInfo
if err != nil {
level = slog.LevelError
}
slog.Log(context.Background(), level, "Prepare UD-CO2S", "commands", do, "error", err)
}()
for _, cmd := range commands {
do = append(do, cmd)
if _, err = c.port.Write([]byte(cmd + "\r\n")); err != nil {
return
}
time.Sleep(time.Millisecond * 100) // wait
for c.scanner.Scan() {
t := c.scanner.Text()
if strings.HasPrefix(t[:2], ResponseOK) {
break
} else if strings.HasPrefix(t[:2], ResponseNG) {
return fmt.Errorf("command `%v` failed", cmd)
}
}
}
return
}
// OutputterNames returns names of impleneted outputter
func (c *Chissoku) registerOutputters() (names []string) {
if c.outputters != nil {
for k := range c.outputters {
names = append(names, k)
}
return names
}
c.outputters = make(map[string]output.Outputter)
rv := reflect.Indirect(reflect.ValueOf(c))
rt := rv.Type()
for i := 0; i < rt.NumField(); i++ {
f := rt.Field(i)
if !f.IsExported() {
continue
}
if value, ok := rv.Field(i).Addr().Interface().(output.Outputter); ok {
name := value.Name()
names = append(names, name)
c.outputters[name] = value
}
}
return names
}