-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.go
50 lines (44 loc) · 917 Bytes
/
client.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
// Client for reading serial device output (e.g. arduino)
package goserial
import (
"bufio"
"fmt"
"github.com/tarm/serial"
)
type Client struct {
port *serial.Port
open bool
}
// Opens device ready to be read
func NewClient(dev string, baud int) (*Client, error) {
c := &serial.Config{Name: "/dev/cu.usbmodem1421", Baud: 9600}
s, err := serial.OpenPort(c)
if err != nil {
return nil, err
}
cl := &Client{
port: s,
open: true,
}
return cl, nil
}
// Reads next line after the first newline encountered
func (c *Client) ReadLine() (string, error) {
if !c.open {
return "", fmt.Errorf("Serial port closed.\n")
}
reader := bufio.NewReader(c.port)
// discard up to first newline
line, err := reader.ReadString('\n')
if err != nil {
return "", err
}
line, err = reader.ReadString('\n')
if err != nil {
return "", err
}
return line, nil
}
func (c *Client) Close() {
c.port.Close()
}