From 061f526b1f56ec7293ae0f7601d3d93538eef519 Mon Sep 17 00:00:00 2001 From: unknown Date: Thu, 26 Mar 2020 16:12:36 +0800 Subject: [PATCH 1/5] minor changes --- cmd/mock/main.go | 3 ++- mock/device/tf0mock.go | 4 ++-- service/weigh.go | 19 ++++++++----------- 3 files changed, 12 insertions(+), 14 deletions(-) diff --git a/cmd/mock/main.go b/cmd/mock/main.go index aada2a0..9fb87ef 100644 --- a/cmd/mock/main.go +++ b/cmd/mock/main.go @@ -13,7 +13,7 @@ import ( const ( cameraURL = "http://localhost:9090/bar" duration = 5 - desiredStdDev = 0.02 + desiredStdDev = 0.05 ) var data = []float64{9.1, +20.00, 422.97, 124.8209, 984, 89.01, -1.8, .622} @@ -52,6 +52,7 @@ func main() { mck.Send(sample, in) select { case <-timer.C: + //mock truck leaving mck.Send(raw/2, in) time.Sleep(time.Second) mck.Send(raw/4, in) diff --git a/mock/device/tf0mock.go b/mock/device/tf0mock.go index d3987ee..d49f999 100644 --- a/mock/device/tf0mock.go +++ b/mock/device/tf0mock.go @@ -2,7 +2,6 @@ package device import ( "fmt" - "log" "math" "strconv" "strings" @@ -22,7 +21,8 @@ func (t Tf0Mock) Send(data float64, in chan []byte) { return } in <- item - log.Printf("%s\t -> %x\n", formatted, item) + //log.Printf("%s\t -> %x\n", formatted, item) + fmt.Print(formatted + " ") } func (t Tf0Mock) encode(input string) ([]byte, error) { diff --git a/service/weigh.go b/service/weigh.go index c0093df..51205e9 100644 --- a/service/weigh.go +++ b/service/weigh.go @@ -63,11 +63,9 @@ func (w *ScaleReader) Listen(wt chan string, stop chan struct{}) error { log.Println("connected to:", c.Name, "TF=", w.TF) reader := bufio.NewReader(s) - var max, min, final float64 + cdc := protocal.NewCodec(w.TF) timer := time.NewTimer(time.Second * time.Duration(w.Duration)) - readWeight := func() protocal.Weight { - cdc := protocal.NewCodec(w.TF) raw, err := reader.ReadBytes(cdc.GetDelimit()) if err != nil { log.Println("ReadBytes error", err) @@ -79,13 +77,9 @@ func (w *ScaleReader) Listen(wt chan string, stop chan struct{}) error { return w } weight := readWeight() - max = weight.Value - min = weight.Value - final = 0 - + max, min := weight.Value, weight.Value + var final float64 = 0 for { - - //log.Printf("read: %x=>%s", raw, weight.String()) select { case <-timer.C: //after a few seconds of stable time, remember the maximum value ever @@ -93,13 +87,16 @@ func (w *ScaleReader) Listen(wt chan string, stop chan struct{}) error { fmt.Println("set final", final) case <-stop: log.Println("Listen stopped") + reader.Reset(s) return nil default: weight := readWeight() if weight.Value > max { max = weight.Value + fmt.Println("set max=", max) } else if weight.Value < min { min = weight.Value + fmt.Println("set min=", min) } //it seems the truck is leaving when weight drops to 1/3 of the max if final > 0 && weight.Value < final/3 { @@ -113,12 +110,12 @@ func (w *ScaleReader) Listen(wt chan string, stop chan struct{}) error { return nil } //fmt.Println("max", max, "min", min) - if final < 0 && max-min > float64(w.Deviation)/1000 { + if final == 0 && max-min > float64(w.Deviation)/1000 { d := time.Second * time.Duration(w.Duration) timer.Reset(d) max = weight.Value min = weight.Value - fmt.Println("Reset: max", max) + log.Println("Reset: max", max) } } } From f2889c236fc9c1c2a499111e5305383e749ba25b Mon Sep 17 00:00:00 2001 From: unknown Date: Thu, 26 Mar 2020 18:53:36 +0800 Subject: [PATCH 2/5] refactor timeout --- cmd/mock/main.go | 2 +- service/weigh.go | 64 ++++++++++++++++++++++++++---------------------- 2 files changed, 36 insertions(+), 30 deletions(-) diff --git a/cmd/mock/main.go b/cmd/mock/main.go index 9fb87ef..fbacefc 100644 --- a/cmd/mock/main.go +++ b/cmd/mock/main.go @@ -13,7 +13,7 @@ import ( const ( cameraURL = "http://localhost:9090/bar" duration = 5 - desiredStdDev = 0.05 + desiredStdDev = 0.001 ) var data = []float64{9.1, +20.00, 422.97, 124.8209, 984, 89.01, -1.8, .622} diff --git a/service/weigh.go b/service/weigh.go index 51205e9..39707ee 100644 --- a/service/weigh.go +++ b/service/weigh.go @@ -45,58 +45,59 @@ type WeightInfoToSign struct { TimeStamp int64 } -func (w *ScaleReader) Listen(wt chan string, stop chan struct{}) error { +func (w *ScaleReader) Listen(result chan string, stop chan struct{}) error { c := &serial.Config{Name: w.PortName, Baud: w.Baud} s, err := serial.OpenPort(c) if err != nil { return fmt.Errorf("OpenPort failed: %v", err) } + reader := bufio.NewReader(s) defer func() { if s != nil { - if err = s.Close(); err != nil { - fmt.Println("serial port close failed: ", err) - } - fmt.Println("serial port closed") + _ = s.Close() } - fmt.Println("defer", "s == nil") }() log.Println("connected to:", c.Name, "TF=", w.TF) + wCh := make(chan protocal.Weight) - reader := bufio.NewReader(s) - cdc := protocal.NewCodec(w.TF) - timer := time.NewTimer(time.Second * time.Duration(w.Duration)) - readWeight := func() protocal.Weight { - raw, err := reader.ReadBytes(cdc.GetDelimit()) - if err != nil { - log.Println("ReadBytes error", err) - } - w, err := cdc.Decode(raw) - if err != nil { - log.Println("Decode error", err) + go func() { + cdc := protocal.NewCodec(w.TF) + for { + raw, err := reader.ReadBytes(cdc.GetDelimit()) + if err != nil { + log.Println("ReadBytes error", err) + //continue + } + w, err := cdc.Decode(raw) + if err != nil { + log.Println("Decode error", err) + //continue + } + wCh <- w + //fmt.Println("for weight", w) } - return w - } - weight := readWeight() - max, min := weight.Value, weight.Value + }() + weight := <-wCh + fmt.Println("first weight", weight) + maxEver, max, min := weight.Value, weight.Value, weight.Value + timer := time.NewTimer(time.Second * time.Duration(w.Duration)) var final float64 = 0 for { select { case <-timer.C: - //after a few seconds of stable time, remember the maximum value ever + //remember the maximum value during last stable time window final = max fmt.Println("set final", final) case <-stop: - log.Println("Listen stopped") - reader.Reset(s) + log.Println("Listen timeout, will stop. max value ever: ", maxEver) return nil - default: - weight := readWeight() + case weight = <-wCh: if weight.Value > max { max = weight.Value - fmt.Println("set max=", max) + //fmt.Println("set max=", max) } else if weight.Value < min { min = weight.Value - fmt.Println("set min=", min) + //fmt.Println("set min=", min) } //it seems the truck is leaving when weight drops to 1/3 of the max if final > 0 && weight.Value < final/3 { @@ -105,7 +106,7 @@ func (w *ScaleReader) Listen(wt chan string, stop chan struct{}) error { Sign: weight.Sign, Digits: weight.Digits, } - wt <- theWeight.String() + result <- theWeight.String() fmt.Println("weigh success:", theWeight.String()) return nil } @@ -113,10 +114,15 @@ func (w *ScaleReader) Listen(wt chan string, stop chan struct{}) error { if final == 0 && max-min > float64(w.Deviation)/1000 { d := time.Second * time.Duration(w.Duration) timer.Reset(d) + if maxEver < max { + maxEver = max + } max = weight.Value min = weight.Value log.Println("Reset: max", max) } + default: + } } } From 924da20ed3cb842ec334a9f70de546e76edbeae8 Mon Sep 17 00:00:00 2001 From: unknown Date: Fri, 27 Mar 2020 18:56:44 +0800 Subject: [PATCH 3/5] fix access is denied --- cmd/mock/main.go | 19 ++++----- cmd/service/config.toml | 4 +- cmd/service/main.go | 8 ++-- mock/device/device.go | 3 ++ service/weigh.go | 85 ++++++++++++++++++++++++++--------------- 5 files changed, 73 insertions(+), 46 deletions(-) diff --git a/cmd/mock/main.go b/cmd/mock/main.go index fbacefc..1546dac 100644 --- a/cmd/mock/main.go +++ b/cmd/mock/main.go @@ -3,6 +3,7 @@ package main import ( "flag" "fmt" + "log" "math/rand" "net/http" "net/url" @@ -43,22 +44,22 @@ func main() { go device.SerialOut(in, "COM2") rand.Seed(time.Now().UnixNano()) r := rand.Intn(len(data)) - fmt.Println("rand", r) timer := time.NewTimer(time.Second * duration) + timer1 := time.NewTimer(time.Millisecond * time.Duration(duration*1000-500)) raw := data[r] - + total := 0 for { - sample := rand.NormFloat64()*desiredStdDev + raw - mck.Send(sample, in) select { case <-timer.C: - //mock truck leaving - mck.Send(raw/2, in) - time.Sleep(time.Second) - mck.Send(raw/4, in) + mck.Send(data[r]/4, in) + log.Println("total sent", total) return + case <-timer1.C: + //mock truck leaving + raw = data[r] / 2 default: - continue + mck.Send(rand.NormFloat64()*desiredStdDev+raw, in) + total++ } } }() diff --git a/cmd/service/config.toml b/cmd/service/config.toml index 6c5747a..ecd1f07 100644 --- a/cmd/service/config.toml +++ b/cmd/service/config.toml @@ -1,6 +1,6 @@ -ScaleSN = "1" #地磅序列号 -Location = "沙场1" #位置信息 +ScaleSN = "地磅1" #地磅序列号 +SiteSN = "沙场1" #位置信息 PortName = "COM1" #串口名称 Baud = 9600 #波特率 TF = 0 #通讯方式 diff --git a/cmd/service/main.go b/cmd/service/main.go index 6bfb02c..4e044f3 100644 --- a/cmd/service/main.go +++ b/cmd/service/main.go @@ -28,11 +28,10 @@ func barOpen(w http.ResponseWriter, r *http.Request) { stopChan := make(chan struct{}) var msg interface{} go func() { - read := service.ScaleReader{ + sr := service.ScaleReader{ Config: &conf, } - if err := read.Listen(weightChan, stopChan); err != nil { - log.Println("ERROR", err) + if err := sr.Listen(weightChan, stopChan); err != nil { errChan <- err } }() @@ -42,7 +41,7 @@ func barOpen(w http.ResponseWriter, r *http.Request) { Weight: weit, Vehicle: v, ScaleSN: conf.ScaleSN, - Location: conf.Location, + SiteSN: conf.SiteSN, Checkout: checkout, TimeStamp: time.Now().Unix(), } @@ -57,6 +56,7 @@ func barOpen(w http.ResponseWriter, r *http.Request) { if err := service.Post(msg, conf.BackendURL); err != nil { log.Println("ERROR", err) } + //stopChan <- struct{}{} } func main() { diff --git a/mock/device/device.go b/mock/device/device.go index ba6ae7b..dc208ea 100644 --- a/mock/device/device.go +++ b/mock/device/device.go @@ -2,6 +2,7 @@ package device import ( "github.com/tarm/serial" + "time" ) const ( @@ -47,5 +48,7 @@ func SerialOut(inputs chan []byte, portName string) { if _, err = s.Write(item); err != nil { panic(err) } + //paud=9600 + time.Sleep(time.Duration(10) * time.Millisecond) } } diff --git a/service/weigh.go b/service/weigh.go index 39707ee..8c1fabb 100644 --- a/service/weigh.go +++ b/service/weigh.go @@ -15,7 +15,7 @@ var ( type Config struct { ScaleSN string - Location string + SiteSN string PortName string Baud int TF int @@ -40,45 +40,63 @@ type WeightInfoToSign struct { Weight string Vehicle string ScaleSN string - Location string + SiteSN string Checkout bool TimeStamp int64 } func (w *ScaleReader) Listen(result chan string, stop chan struct{}) error { - c := &serial.Config{Name: w.PortName, Baud: w.Baud} - s, err := serial.OpenPort(c) - if err != nil { - return fmt.Errorf("OpenPort failed: %v", err) - } - reader := bufio.NewReader(s) - defer func() { - if s != nil { - _ = s.Close() - } - }() - log.Println("connected to:", c.Name, "TF=", w.TF) - wCh := make(chan protocal.Weight) + wCh := make(chan protocal.Weight) + errCh := make(chan error) + quitCh := make(chan struct{}) go func() { - cdc := protocal.NewCodec(w.TF) - for { - raw, err := reader.ReadBytes(cdc.GetDelimit()) - if err != nil { - log.Println("ReadBytes error", err) - //continue + c := &serial.Config{Name: w.PortName, Baud: w.Baud} + s, err := serial.OpenPort(c) + if err != nil { + errCh <- fmt.Errorf("OpenPort failed: %v", err) + return + } + defer func() { + if s != nil { + err = s.Close() + log.Println("s.Close()),", err) + } else { + + log.Println("s == nil ),", err) } - w, err := cdc.Decode(raw) - if err != nil { - log.Println("Decode error", err) - //continue + }() + log.Println("connected to:", c.Name, "TF=", w.TF) + cdc := protocal.NewCodec(w.TF) + reader := bufio.NewReader(s) + go func() { + for { + raw, err := reader.ReadBytes(cdc.GetDelimit()) + if err != nil { + log.Println("ReadBytes error", err) + //continue + } + w, err := cdc.Decode(raw) + if err != nil { + log.Println("Decode error", err) + //continue + } + //fmt.Println("for weight", w) + wCh <- w } - wCh <- w - //fmt.Println("for weight", w) - } + }() + + <-quitCh + log.Println("loop quit") + return }() - weight := <-wCh - fmt.Println("first weight", weight) + var weight protocal.Weight + select { + case weight = <-wCh: + fmt.Println("first weight", weight) + case err := <-errCh: + return err + } maxEver, max, min := weight.Value, weight.Value, weight.Value timer := time.NewTimer(time.Second * time.Duration(w.Duration)) var final float64 = 0 @@ -89,6 +107,7 @@ func (w *ScaleReader) Listen(result chan string, stop chan struct{}) error { final = max fmt.Println("set final", final) case <-stop: + quitCh <- struct{}{} log.Println("Listen timeout, will stop. max value ever: ", maxEver) return nil case weight = <-wCh: @@ -106,8 +125,12 @@ func (w *ScaleReader) Listen(result chan string, stop chan struct{}) error { Sign: weight.Sign, Digits: weight.Digits, } + log.Println("truck is leaving...") + go func() { + quitCh <- struct{}{} + }() result <- theWeight.String() - fmt.Println("weigh success:", theWeight.String()) + log.Println("weigh success:", theWeight.String()) return nil } //fmt.Println("max", max, "min", min) From 1157580717ff3c78dad5e235d6e20369d6ba13b9 Mon Sep 17 00:00:00 2001 From: unknown Date: Tue, 31 Mar 2020 11:31:35 +0800 Subject: [PATCH 4/5] use context - no leak --- cmd/mock/{main.go => mock.go} | 0 cmd/service/config.toml | 2 +- cmd/service/main.go | 22 +++++-- service/weigh.go | 109 +++++++++++++++++----------------- 4 files changed, 75 insertions(+), 58 deletions(-) rename cmd/mock/{main.go => mock.go} (100%) diff --git a/cmd/mock/main.go b/cmd/mock/mock.go similarity index 100% rename from cmd/mock/main.go rename to cmd/mock/mock.go diff --git a/cmd/service/config.toml b/cmd/service/config.toml index ecd1f07..4c7a709 100644 --- a/cmd/service/config.toml +++ b/cmd/service/config.toml @@ -1,5 +1,5 @@ -ScaleSN = "地磅1" #地磅序列号 +ScaleSN = "地磅1" #地磅序列号 SiteSN = "沙场1" #位置信息 PortName = "COM1" #串口名称 Baud = 9600 #波特率 diff --git a/cmd/service/main.go b/cmd/service/main.go index 4e044f3..4500ffd 100644 --- a/cmd/service/main.go +++ b/cmd/service/main.go @@ -1,9 +1,12 @@ package main import ( + "context" + "fmt" "github.com/BurntSushi/toml" "log" "net/http" + _ "net/http/pprof" "serialdemo/service" "time" ) @@ -25,13 +28,15 @@ func barOpen(w http.ResponseWriter, r *http.Request) { log.Println("truck", v, "checkout", checkout) weightChan := make(chan string) errChan := make(chan error) - stopChan := make(chan struct{}) var msg interface{} + + ctx, cancel := context.WithTimeout(context.Background(), time.Second*time.Duration(conf.Timeout)) + defer cancel() go func() { sr := service.ScaleReader{ Config: &conf, } - if err := sr.Listen(weightChan, stopChan); err != nil { + if err := sr.Listen(ctx, weightChan); err != nil { errChan <- err } }() @@ -48,8 +53,7 @@ func barOpen(w http.ResponseWriter, r *http.Request) { case err := <-errChan: msg = err.Error() log.Println("ERROR", err) - case <-time.After(time.Second * time.Duration(conf.Timeout)): - stopChan <- struct{}{} + case <-ctx.Done(): msg = "ScaleReader timeout" log.Println("ERROR", msg) } @@ -57,9 +61,19 @@ func barOpen(w http.ResponseWriter, r *http.Request) { log.Println("ERROR", err) } //stopChan <- struct{}{} + <-ctx.Done() + msg = "process timeout" + log.Println("ERROR", msg) } func main() { + go func() { + + ip := "0.0.0.0:6060" + if err := http.ListenAndServe(ip, nil); err != nil { + fmt.Printf("start pprof failed on %s\n", ip) + } + }() mux := http.NewServeMux() mux.HandleFunc("/bar", barOpen) url := "0.0.0.0:9090" diff --git a/service/weigh.go b/service/weigh.go index 8c1fabb..f4257b1 100644 --- a/service/weigh.go +++ b/service/weigh.go @@ -2,6 +2,7 @@ package service import ( "bufio" + "context" "fmt" "github.com/tarm/serial" "log" @@ -45,58 +46,31 @@ type WeightInfoToSign struct { TimeStamp int64 } -func (w *ScaleReader) Listen(result chan string, stop chan struct{}) error { - - wCh := make(chan protocal.Weight) - errCh := make(chan error) +func (w *ScaleReader) Listen(ctx context.Context, result chan string) error { quitCh := make(chan struct{}) - go func() { - c := &serial.Config{Name: w.PortName, Baud: w.Baud} - s, err := serial.OpenPort(c) - if err != nil { - errCh <- fmt.Errorf("OpenPort failed: %v", err) - return - } - defer func() { - if s != nil { - err = s.Close() - log.Println("s.Close()),", err) - } else { + wCh := make(chan protocal.Weight, 1) + c := &serial.Config{Name: w.PortName, Baud: w.Baud} + s, err := serial.OpenPort(c) + if err != nil { + return fmt.Errorf("OpenPort failed: %v", err) + } + ctx, cancel := context.WithCancel(ctx) + defer func() { + cancel() + //<-quitCh + _ = s.Close() + log.Println("s.Close()") + }() - log.Println("s == nil ),", err) - } - }() - log.Println("connected to:", c.Name, "TF=", w.TF) - cdc := protocal.NewCodec(w.TF) - reader := bufio.NewReader(s) - go func() { - for { - raw, err := reader.ReadBytes(cdc.GetDelimit()) - if err != nil { - log.Println("ReadBytes error", err) - //continue - } - w, err := cdc.Decode(raw) - if err != nil { - log.Println("Decode error", err) - //continue - } - //fmt.Println("for weight", w) - wCh <- w - } - }() + log.Println("connected to:", c.Name, "TF=", w.TF) + + reader := bufio.NewReader(s) + go readSerial(ctx, wCh, quitCh, w.TF, *reader) - <-quitCh - log.Println("loop quit") - return - }() var weight protocal.Weight - select { - case weight = <-wCh: - fmt.Println("first weight", weight) - case err := <-errCh: - return err - } + weight = <-wCh + fmt.Println("first weight", weight) + maxEver, max, min := weight.Value, weight.Value, weight.Value timer := time.NewTimer(time.Second * time.Duration(w.Duration)) var final float64 = 0 @@ -106,8 +80,7 @@ func (w *ScaleReader) Listen(result chan string, stop chan struct{}) error { //remember the maximum value during last stable time window final = max fmt.Println("set final", final) - case <-stop: - quitCh <- struct{}{} + case <-ctx.Done(): log.Println("Listen timeout, will stop. max value ever: ", maxEver) return nil case weight = <-wCh: @@ -126,10 +99,8 @@ func (w *ScaleReader) Listen(result chan string, stop chan struct{}) error { Digits: weight.Digits, } log.Println("truck is leaving...") - go func() { - quitCh <- struct{}{} - }() result <- theWeight.String() + cancel() log.Println("weigh success:", theWeight.String()) return nil } @@ -149,3 +120,35 @@ func (w *ScaleReader) Listen(result chan string, stop chan struct{}) error { } } } + +func readSerial(ctx context.Context, wCh chan protocal.Weight, quitCh chan struct{}, tf int, reader bufio.Reader) { + //defer func() { + // quitCh <- struct{}{} + //}() + cdc := protocal.NewCodec(tf) + for { + select { + case <-ctx.Done(): + log.Println("loop quit") + return + default: + raw, err := reader.ReadBytes(cdc.GetDelimit()) + if err != nil { + log.Println("ReadBytes error", err) + //continue + } + decoded, err := cdc.Decode(raw) + if err != nil { + log.Println("Decode error", err) + //continue + } + + wCh <- decoded + //select { + //case wCh <- decoded: + //default: + // + //} + } + } +} From 79afbc8497a668d5613ff26d86650b434d1f88e7 Mon Sep 17 00:00:00 2001 From: unknown Date: Tue, 31 Mar 2020 12:38:19 +0800 Subject: [PATCH 5/5] as long live service --- {service => core}/weigh.go | 65 +++++++++++++----------------------- {service => utils}/crypto.go | 0 {service => utils}/http.go | 0 3 files changed, 23 insertions(+), 42 deletions(-) rename {service => core}/weigh.go (69%) rename {service => utils}/crypto.go (100%) rename {service => utils}/http.go (100%) diff --git a/service/weigh.go b/core/weigh.go similarity index 69% rename from service/weigh.go rename to core/weigh.go index f4257b1..0002bfb 100644 --- a/service/weigh.go +++ b/core/weigh.go @@ -10,10 +10,6 @@ import ( "time" ) -var ( - privateKey, _ = loadPrivateKey("private.key") -) - type Config struct { ScaleSN string SiteSN string @@ -26,10 +22,6 @@ type Config struct { BackendURL string } -type ScaleReader struct { - *Config -} - type WeightInfo struct { Error string WeightInfoToSign @@ -46,33 +38,18 @@ type WeightInfoToSign struct { TimeStamp int64 } -func (w *ScaleReader) Listen(ctx context.Context, result chan string) error { - quitCh := make(chan struct{}) - wCh := make(chan protocal.Weight, 1) - c := &serial.Config{Name: w.PortName, Baud: w.Baud} - s, err := serial.OpenPort(c) - if err != nil { - return fmt.Errorf("OpenPort failed: %v", err) - } - ctx, cancel := context.WithCancel(ctx) +func Weigh(ctx context.Context, conf Config, wCh <-chan protocal.Weight, result chan<- string) error { + defer func() { - cancel() - //<-quitCh - _ = s.Close() log.Println("s.Close()") }() - log.Println("connected to:", c.Name, "TF=", w.TF) - - reader := bufio.NewReader(s) - go readSerial(ctx, wCh, quitCh, w.TF, *reader) - var weight protocal.Weight weight = <-wCh fmt.Println("first weight", weight) maxEver, max, min := weight.Value, weight.Value, weight.Value - timer := time.NewTimer(time.Second * time.Duration(w.Duration)) + timer := time.NewTimer(time.Second * time.Duration(conf.Duration)) var final float64 = 0 for { select { @@ -100,13 +77,12 @@ func (w *ScaleReader) Listen(ctx context.Context, result chan string) error { } log.Println("truck is leaving...") result <- theWeight.String() - cancel() log.Println("weigh success:", theWeight.String()) return nil } //fmt.Println("max", max, "min", min) - if final == 0 && max-min > float64(w.Deviation)/1000 { - d := time.Second * time.Duration(w.Duration) + if final == 0 && max-min > float64(conf.Deviation)/1000 { + d := time.Second * time.Duration(conf.Duration) timer.Reset(d) if maxEver < max { maxEver = max @@ -121,16 +97,26 @@ func (w *ScaleReader) Listen(ctx context.Context, result chan string) error { } } -func readSerial(ctx context.Context, wCh chan protocal.Weight, quitCh chan struct{}, tf int, reader bufio.Reader) { - //defer func() { - // quitCh <- struct{}{} - //}() - cdc := protocal.NewCodec(tf) +func ListenWeight(conf Config, wCh chan protocal.Weight, quitCh chan struct{}) error { + c := &serial.Config{Name: conf.PortName, Baud: conf.Baud} + s, err := serial.OpenPort(c) + if err != nil { + return fmt.Errorf("OpenPort failed: %v", err) + } + defer func() { + _ = s.Close() + log.Println("s.Close()") + }() + log.Println("connected to:", c.Name, "TF=", conf.TF) + + reader := bufio.NewReader(s) + cdc := protocal.NewCodec(conf.TF) for { select { - case <-ctx.Done(): - log.Println("loop quit") - return + case <-quitCh: + //reader.Reset(s) + //log.Println("reader.Reset()") + return nil default: raw, err := reader.ReadBytes(cdc.GetDelimit()) if err != nil { @@ -144,11 +130,6 @@ func readSerial(ctx context.Context, wCh chan protocal.Weight, quitCh chan struc } wCh <- decoded - //select { - //case wCh <- decoded: - //default: - // - //} } } } diff --git a/service/crypto.go b/utils/crypto.go similarity index 100% rename from service/crypto.go rename to utils/crypto.go diff --git a/service/http.go b/utils/http.go similarity index 100% rename from service/http.go rename to utils/http.go