package lc import ( "github.com/jacobsa/go-serial/serial" "github.com/sirupsen/logrus" "lc-smartX/lc/model" "lc-smartX/util" ) func StartRadioEventServer() *RadioServer { s := &RadioServer{Radios: util.Config.Radios, Notifiers: make(map[string]Notifier, 4)} s.start() return s } type RadioServer struct { Radios []model.RadioInfo Notifiers map[string]Notifier //485通道名 } func (s *RadioServer) start() { for _, radio := range s.Radios { go s.OpenSerial(radio.Port) } } func (s *RadioServer) RegisterCallback(branch byte, notifier Notifier) { for _, radio := range s.Radios { //关联主路led屏和支路雷达;关联支路led屏和主路雷达 if branch == 0 && radio.Branch == 1 || branch == 1 && radio.Branch == 0 { s.Notifiers[radio.Port] = notifier } } } func (s *RadioServer) Callback(port string) { notifier, ok := s.Notifiers[port] if !ok { logrus.Errorf("回调函数注册表没有该ip:%s", port) return } notifier.Notify() } func (s *RadioServer) OpenSerial(portName string) { // 配置串口参数 options := serial.OpenOptions{ PortName: portName, // /dev/ttymxc4 6 3 BaudRate: 9600, DataBits: 8, StopBits: 1, MinimumReadSize: 4, } // 打开串口 port, err := serial.Open(options) if err != nil { panic(err.Error()) } // 关闭串口 defer port.Close() for { // 读取数据 buf := make([]byte, 128) n, err := port.Read(buf) if err != nil { break } if n < 8 { continue } result := false if buf[0] == 'x' && (buf[1] > '0' || buf[2] > '0' || buf[3] > '0') { result = true } if result { s.Callback(portName) } } }