Added many Eventbus Structs for the Frontend Handling
This commit is contained in:
+44
-8
@@ -2,6 +2,7 @@ package uart
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"log"
|
||||
"time"
|
||||
|
||||
@@ -16,15 +17,26 @@ type Com struct {
|
||||
cancel context.CancelFunc
|
||||
}
|
||||
|
||||
func Connect(bus eventbus.EventBus, portName string, baudrate int) (*Com, error) {
|
||||
func NewCom(bus eventbus.EventBus) (*Com, error) {
|
||||
return &Com{
|
||||
bus: bus,
|
||||
port: nil,
|
||||
cancel: nil,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (c *Com) Connect(portName string, baudrate int) error {
|
||||
if c.port != nil {
|
||||
return fmt.Errorf("Port already connected")
|
||||
}
|
||||
mode := &serial.Mode{BaudRate: baudrate}
|
||||
port, err := serial.Open(portName, mode)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
return err
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
drv := New(bus)
|
||||
drv := New(c.bus)
|
||||
|
||||
go func() {
|
||||
buff := make([]byte, 1024)
|
||||
@@ -48,11 +60,9 @@ func Connect(bus eventbus.EventBus, portName string, baudrate int) (*Com, error)
|
||||
}
|
||||
}()
|
||||
|
||||
return &Com{
|
||||
bus: bus,
|
||||
port: port,
|
||||
cancel: cancel,
|
||||
}, nil
|
||||
c.port = port
|
||||
c.cancel = cancel
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *Com) Close() {
|
||||
@@ -100,3 +110,29 @@ func (c *Com) Send(id byte, payload []byte) error {
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
func (c *Com) EventbusHandler(ctx context.Context) error {
|
||||
UActions := c.bus.Subscribe(api.TopicUartAction)
|
||||
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return nil
|
||||
case msgT := <-UActions:
|
||||
switch msg := msgT.(type) {
|
||||
case api.ActionUartConnect:
|
||||
err := c.Connect(msg.Adapter, msg.Baudrate)
|
||||
c.bus.Publish(api.TopicUartAction, api.ActionUartConnected{
|
||||
Adapter: msg.Adapter,
|
||||
Baudrate: msg.Baudrate,
|
||||
Error: err,
|
||||
})
|
||||
case api.ActionUartDisconnect:
|
||||
c.Close()
|
||||
c.bus.Publish(api.TopicUartAction, api.ActionUartDisconnected{})
|
||||
case api.ActionUartSendMessage:
|
||||
c.Send(msg.MsgId, msg.Data)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user