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
require (
github.com/jacobsa/go-serial v0.0.0-20180131005756-15cf729a72d4
github.com/rjeczalik/notify v0.9.2
)
require github.com/rjeczalik/notify v0.9.2
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/go.mod h1:aErll2f0sUX9PXZnVNyeiObbmTlk5jnMoCa4QEjJeqM=
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 (
"bufio"
"encoding/json"
"errors"
"context"
"fmt"
"io/ioutil"
"log"
"os"
"os/exec"
"path/filepath"
"strconv"
"strings"
"time"
"github.com/jacobsa/go-serial/serial"
"git.godopu.net/lab/etri-smartfarm-poc-controller-serial/puserial"
"github.com/rjeczalik/notify"
)
func readJsonFromSerial(obj map[string]interface{}, decoder *json.Decoder) error {
err := decoder.Decode(&obj)
if err != nil {
return err
}
func Run() {
fmt.Println("Hello world")
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 {
b, _, _ := reader.ReadLine()
recvObj := map[string]interface{}{}
err := json.Unmarshal(b, &recvObj)
// err = readJsonFromSerial(recvObj, decoder)
if err != nil {
if err.Error() == "EOF" {
e, ok := <-ch_discover
if !ok {
fmt.Println("byebye~!")
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)
}
fmt.Println(e)
}
}

View File

@ -1,164 +1,157 @@
package serial
package puserial
import (
"bufio"
"encoding/json"
"errors"
"context"
"fmt"
"io/ioutil"
"log"
"os"
"os/exec"
"path/filepath"
"strconv"
"strings"
"time"
"github.com/jacobsa/go-serial/serial"
"github.com/rjeczalik/notify"
)
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)
func WatchNewDevice(ctx context.Context, ch_discover chan<- notify.EventInfo) error {
defer close(ch_discover)
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 e.Event() == notify.Create {
log.Println("Got event:", e.Path())
return e.Path()
fmt.Println(e.Path())
ch_discover <- e
}
}
}
return ""
}
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 {
// 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 {
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)
}
}
}
// 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 {
// // 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 {
// 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)
// }
// }
// }