commit 2021-12-09]14:04:50

This commit is contained in:
Godopu 2021-12-09 14:04:56 +09:00
parent 8b8d37d0a1
commit 2d66bc9e49
4 changed files with 156 additions and 318 deletions

5
go.mod
View File

@ -2,9 +2,6 @@ module git.godopu.net/lab/etri-smartfarm-poc-controller-serial
go 1.17 go 1.17
require ( require github.com/rjeczalik/notify v0.9.2
github.com/jacobsa/go-serial v0.0.0-20180131005756-15cf729a72d4
github.com/rjeczalik/notify v0.9.2
)
require golang.org/x/sys v0.0.0-20180926160741-c2ed4eda69e7 // indirect require golang.org/x/sys v0.0.0-20180926160741-c2ed4eda69e7 // indirect

2
go.sum
View File

@ -1,5 +1,3 @@
github.com/jacobsa/go-serial v0.0.0-20180131005756-15cf729a72d4 h1:G2ztCwXov8mRvP0ZfjE6nAlaCX2XbykaeHdbT6KwDz0=
github.com/jacobsa/go-serial v0.0.0-20180131005756-15cf729a72d4/go.mod h1:2RvX5ZjVtsznNZPEt4xwJXNJrM3VTZoQf7V6gk0ysvs=
github.com/rjeczalik/notify v0.9.2 h1:MiTWrPj55mNDHEiIX5YUSKefw/+lCQVoAFmD6oQm5w8= github.com/rjeczalik/notify v0.9.2 h1:MiTWrPj55mNDHEiIX5YUSKefw/+lCQVoAFmD6oQm5w8=
github.com/rjeczalik/notify v0.9.2/go.mod h1:aErll2f0sUX9PXZnVNyeiObbmTlk5jnMoCa4QEjJeqM= github.com/rjeczalik/notify v0.9.2/go.mod h1:aErll2f0sUX9PXZnVNyeiObbmTlk5jnMoCa4QEjJeqM=
golang.org/x/sys v0.0.0-20180926160741-c2ed4eda69e7 h1:bit1t3mgdR35yN0cX0G8orgLtOuyL9Wqxa1mccLB0ig= golang.org/x/sys v0.0.0-20180926160741-c2ed4eda69e7 h1:bit1t3mgdR35yN0cX0G8orgLtOuyL9Wqxa1mccLB0ig=

174
main.go
View File

@ -1,177 +1,27 @@
package main package manager
import ( import (
"bufio" "context"
"encoding/json"
"errors"
"fmt" "fmt"
"io/ioutil"
"log"
"os"
"os/exec"
"path/filepath"
"strconv"
"strings"
"time" "time"
"github.com/jacobsa/go-serial/serial" "git.godopu.net/lab/etri-smartfarm-poc-controller-serial/puserial"
"github.com/rjeczalik/notify" "github.com/rjeczalik/notify"
) )
func readJsonFromSerial(obj map[string]interface{}, decoder *json.Decoder) error { func Run() {
err := decoder.Decode(&obj) fmt.Println("Hello world")
if err != nil {
return err
}
return nil ctx, _ := context.WithTimeout(context.Background(), time.Second*10)
} ch_discover := make(chan notify.EventInfo)
go puserial.WatchNewDevice(ctx, ch_discover)
func msgSender(did string) {
}
func initUSB() (string, error) {
fs, err := ioutil.ReadDir("/dev")
if err != nil {
return "", err
}
for _, f := range fs {
if strings.Contains(f.Name(), "ttyACM") {
return filepath.Join("/dev", f.Name()), nil
}
}
return "", errors.New("USB Not found")
}
func discoverUSB() string {
fmt.Println("Waiting USB")
ch := make(chan notify.EventInfo, 1)
if err := notify.Watch("/dev", ch, notify.Create, notify.Remove); err != nil {
log.Fatalln(err)
}
defer notify.Stop(ch)
for e := range ch {
if strings.Contains(e.Path(), "/dev/ttyACM") {
if e.Event() == notify.Create {
log.Println("Got event:", e.Path())
return e.Path()
}
}
}
return ""
}
func main() {
dev, err := initUSB()
if err != nil {
if err.Error() == "USB Not found" {
dev = discoverUSB()
} else {
log.Fatalln(err.Error())
}
}
fmt.Println("discover: ", dev)
time.Sleep(time.Second)
log.Println("changing the mod of file")
cmd := exec.Command("chmod", "a+rw", dev)
b, _ := cmd.CombinedOutput()
fmt.Println(string(b))
// Set up options.
options := serial.OpenOptions{
PortName: dev,
BaudRate: 9600,
DataBits: 8,
StopBits: 1,
MinimumReadSize: 16,
}
// Open the port.
port, err := serial.Open(options)
if err != nil {
log.Fatalf("serial.Open: %v", err)
}
// Make sure to close it later.
defer port.Close()
// Write 4 bytes to the port.
// b := []byte{0x00, 0x01, 0x02, 0x03}
// n, err := port.Write(b)
// if err != nil {
// log.Fatalf("port.Write: %v", err)
// }
// fmt.Println("Wrote", n, "bytes.")
// var tokenByte string
reader := bufio.NewReader(port)
// decoder := json.NewDecoder(port)
encoder := json.NewEncoder(port)
command := map[string]interface{}{}
command["code"] = 1
command["light"] = 0
var data string
go func() {
for { for {
b, _, _ := reader.ReadLine() e, ok := <-ch_discover
recvObj := map[string]interface{}{} if !ok {
err := json.Unmarshal(b, &recvObj) fmt.Println("byebye~!")
// err = readJsonFromSerial(recvObj, decoder)
if err != nil {
if err.Error() == "EOF" {
return return
} }
fmt.Println(e)
fmt.Println("error: ", string(b))
}
data = string(b)
// fmt.Println("line : ", recvObj)
}
}()
cmdReader := bufio.NewReader(os.Stdin)
for {
fmt.Print("> ")
cmd, _, _ := cmdReader.ReadLine()
cmdTkns := strings.Split(string(cmd), " ")
if cmdTkns[0] == "light" {
command["code"] = 1
if cmdTkns[1] == "on" {
command["light"] = 100
} else {
command["light"] = 0
}
} else if cmdTkns[0] == "fan" {
command["code"] = 2
if cmdTkns[1] == "on" {
command["status"] = 1
} else {
command["status"] = 0
}
} else if cmdTkns[0] == "servo" {
command["code"] = 3
angle, err := strconv.Atoi(cmdTkns[1])
if err != nil {
continue
}
command["angle"] = angle
} else if cmdTkns[0] == "print" {
fmt.Println(data)
}
err := encoder.Encode(command)
if err != nil {
panic(err)
}
} }
} }

View File

@ -1,164 +1,157 @@
package serial package puserial
import ( import (
"bufio" "context"
"encoding/json"
"errors"
"fmt" "fmt"
"io/ioutil"
"log"
"os"
"os/exec"
"path/filepath"
"strconv"
"strings" "strings"
"time"
"github.com/jacobsa/go-serial/serial"
"github.com/rjeczalik/notify" "github.com/rjeczalik/notify"
) )
func DiscoverUSB() string { func WatchNewDevice(ctx context.Context, ch_discover chan<- notify.EventInfo) error {
fmt.Println("Waiting USB") defer close(ch_discover)
ch := make(chan notify.EventInfo, 1)
if err := notify.Watch("/dev", ch, notify.Create, notify.Remove); err != nil {
log.Fatalln(err)
}
defer notify.Stop(ch)
for e := range ch { filter := make(chan notify.EventInfo, 1)
if err := notify.Watch("/dev", filter, notify.Create, notify.Remove); err != nil {
return err
}
defer notify.Stop(filter)
for {
select {
case <-ctx.Done():
fmt.Println("routine bye")
return nil
case e := <-filter:
if strings.Contains(e.Path(), "/dev/ttyACM") { if strings.Contains(e.Path(), "/dev/ttyACM") {
if e.Event() == notify.Create { fmt.Println(e.Path())
log.Println("Got event:", e.Path()) ch_discover <- e
return e.Path() }
} }
} }
} }
return "" // func InitUSB() (string, error) {
} // fs, err := ioutil.ReadDir("/dev")
func InitUSB() (string, error) {
fs, err := ioutil.ReadDir("/dev")
if err != nil {
return "", err
}
for _, f := range fs {
if strings.Contains(f.Name(), "ttyACM") {
return filepath.Join("/dev", f.Name()), nil
}
}
return "", errors.New("USB Not found")
}
func Run() {
dev, err := InitUSB()
if err != nil {
if err.Error() == "USB Not found" {
dev = DiscoverUSB()
} else {
log.Fatalln(err.Error())
}
}
fmt.Println("discover: ", dev)
time.Sleep(time.Second)
log.Println("changing the mod of file")
cmd := exec.Command("chmod", "a+rw", dev)
b, _ := cmd.CombinedOutput()
fmt.Println(string(b))
// Set up options.
options := serial.OpenOptions{
PortName: dev,
BaudRate: 9600,
DataBits: 8,
StopBits: 1,
MinimumReadSize: 16,
}
// Open the port.
port, err := serial.Open(options)
if err != nil {
log.Fatalf("serial.Open: %v", err)
}
// Make sure to close it later.
defer port.Close()
// Write 4 bytes to the port.
// b := []byte{0x00, 0x01, 0x02, 0x03}
// n, err := port.Write(b)
// if err != nil { // if err != nil {
// log.Fatalf("port.Write: %v", err) // return "", err
// } // }
// fmt.Println("Wrote", n, "bytes.") // for _, f := range fs {
// var tokenByte string // if strings.Contains(f.Name(), "ttyACM") {
// return filepath.Join("/dev", f.Name()), nil
// }
// }
reader := bufio.NewReader(port) // return "", errors.New("USB Not found")
// decoder := json.NewDecoder(port) // }
encoder := json.NewEncoder(port)
command := map[string]interface{}{}
command["code"] = 1
command["light"] = 0
var data string // func Run() {
go func() { // dev, err := InitUSB()
for { // if err != nil {
b, _, _ := reader.ReadLine() // if err.Error() == "USB Not found" {
recvObj := map[string]interface{}{} // dev = DiscoverUSB()
err := json.Unmarshal(b, &recvObj) // } else {
// err = readJsonFromSerial(recvObj, decoder) // log.Fatalln(err.Error())
if err != nil { // }
if err.Error() == "EOF" { // }
return
}
fmt.Println("error: ", string(b)) // fmt.Println("discover: ", dev)
} // time.Sleep(time.Second)
data = string(b) // log.Println("changing the mod of file")
// fmt.Println("line : ", recvObj) // cmd := exec.Command("chmod", "a+rw", dev)
} // b, _ := cmd.CombinedOutput()
}() // fmt.Println(string(b))
cmdReader := bufio.NewReader(os.Stdin) // // Set up options.
for { // options := serial.OpenOptions{
fmt.Print("> ") // PortName: dev,
cmd, _, _ := cmdReader.ReadLine() // BaudRate: 9600,
cmdTkns := strings.Split(string(cmd), " ") // DataBits: 8,
// StopBits: 1,
// MinimumReadSize: 16,
// }
if cmdTkns[0] == "light" { // // Open the port.
command["code"] = 1 // port, err := serial.Open(options)
if cmdTkns[1] == "on" { // if err != nil {
command["light"] = 100 // log.Fatalf("serial.Open: %v", err)
} else { // }
command["light"] = 0
} // // Make sure to close it later.
} else if cmdTkns[0] == "fan" { // defer port.Close()
command["code"] = 2
if cmdTkns[1] == "on" { // // Write 4 bytes to the port.
command["status"] = 1 // // b := []byte{0x00, 0x01, 0x02, 0x03}
} else { // // n, err := port.Write(b)
command["status"] = 0 // // if err != nil {
} // // log.Fatalf("port.Write: %v", err)
} else if cmdTkns[0] == "servo" { // // }
command["code"] = 3
angle, err := strconv.Atoi(cmdTkns[1]) // // fmt.Println("Wrote", n, "bytes.")
if err != nil { // // var tokenByte string
continue
} // reader := bufio.NewReader(port)
command["angle"] = angle // // decoder := json.NewDecoder(port)
} else if cmdTkns[0] == "print" { // encoder := json.NewEncoder(port)
fmt.Println(data) // command := map[string]interface{}{}
} // command["code"] = 1
err := encoder.Encode(command) // command["light"] = 0
if err != nil {
panic(err) // var data string
} // go func() {
} // for {
} // b, _, _ := reader.ReadLine()
// recvObj := map[string]interface{}{}
// err := json.Unmarshal(b, &recvObj)
// // err = readJsonFromSerial(recvObj, decoder)
// if err != nil {
// if err.Error() == "EOF" {
// return
// }
// fmt.Println("error: ", string(b))
// }
// data = string(b)
// // fmt.Println("line : ", recvObj)
// }
// }()
// cmdReader := bufio.NewReader(os.Stdin)
// for {
// fmt.Print("> ")
// cmd, _, _ := cmdReader.ReadLine()
// cmdTkns := strings.Split(string(cmd), " ")
// if cmdTkns[0] == "light" {
// command["code"] = 1
// if cmdTkns[1] == "on" {
// command["light"] = 100
// } else {
// command["light"] = 0
// }
// } else if cmdTkns[0] == "fan" {
// command["code"] = 2
// if cmdTkns[1] == "on" {
// command["status"] = 1
// } else {
// command["status"] = 0
// }
// } else if cmdTkns[0] == "servo" {
// command["code"] = 3
// angle, err := strconv.Atoi(cmdTkns[1])
// if err != nil {
// continue
// }
// command["angle"] = angle
// } else if cmdTkns[0] == "print" {
// fmt.Println(data)
// }
// err := encoder.Encode(command)
// if err != nil {
// panic(err)
// }
// }
// }