-
Notifications
You must be signed in to change notification settings - Fork 1
/
digital_output.go
72 lines (64 loc) · 1.88 KB
/
digital_output.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
package unipitt
import (
"log"
"os"
"path"
)
const (
// DoFilename to check for
DoFilename = "do_value"
// DoTrueValue digital output true value to write
DoTrueValue = "1\n"
// DoFalseValue digital output false value to write
DoFalseValue = "0\n"
// DoFolderRegex regular expression used for finding folders which contain digital output
DoFolderRegex = "do_[0-9]_[0-9]{2}"
)
// DigitalOutput represents the digital outputs of the unipi board
type DigitalOutput interface {
Update(bool) error
}
// DigitalOutputWriter implements the digital output specifically for writing outputs to files
type DigitalOutputWriter struct {
Name string
Path string
}
// Update writes the updated value to the digital output
func (d *DigitalOutputWriter) Update(value bool) (err error) {
f, err := os.Create(path.Join(d.Path, DoFilename))
defer f.Close()
if err != nil {
return err
}
if value {
_, err = f.WriteString(DoTrueValue)
} else {
_, err = f.WriteString(DoFalseValue)
}
if err == nil {
log.Printf("Update value of digital output %s to %t\n", d.Name, value)
}
return err
}
// NewDigitalOutputWriter creates a new digital output writer instance from a a given matching folder
func NewDigitalOutputWriter(folder string) (d *DigitalOutputWriter) {
// Read name as the trailing folder path
_, name := path.Split(folder)
return &DigitalOutputWriter{Name: name, Path: folder}
}
// FindDigitalOutputWriters generates the output writes from a given path
func FindDigitalOutputWriters(root string) (writerMap map[string]DigitalOutputWriter, err error) {
paths, err := findPathsByRegex(root, DoFolderRegex)
if err != nil {
log.Println(err)
return
}
log.Printf("Found %d matching digital output paths\n", len(paths))
writerMap = make(map[string]DigitalOutputWriter)
var d *DigitalOutputWriter
for _, path := range paths {
d = NewDigitalOutputWriter(path)
writerMap[d.Name] = *d
}
return
}