radio_event.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. package lc
  2. import (
  3. "github.com/jacobsa/go-serial/serial"
  4. "github.com/sirupsen/logrus"
  5. "lc-smartX/lc/model"
  6. "lc-smartX/util"
  7. )
  8. func StartRadioEventServer() *RadioServer {
  9. s := &RadioServer{Radios: util.Config.Radios, Notifiers: make(map[string]Notifier, 4)}
  10. s.start()
  11. return s
  12. }
  13. type RadioServer struct {
  14. Radios []model.RadioInfo
  15. Notifiers map[string]Notifier //485通道名
  16. }
  17. func (s *RadioServer) start() {
  18. for _, radio := range s.Radios {
  19. go s.OpenSerial(radio.Port)
  20. }
  21. }
  22. func (s *RadioServer) RegisterCallback(branch byte, notifier Notifier) {
  23. for _, radio := range s.Radios {
  24. //关联主路led屏和支路雷达;关联支路led屏和主路雷达
  25. if branch == 0 && radio.Branch == 1 || branch == 1 && radio.Branch == 0 {
  26. s.Notifiers[radio.Port] = notifier
  27. }
  28. }
  29. }
  30. func (s *RadioServer) Callback(port string) {
  31. notifier, ok := s.Notifiers[port]
  32. if !ok {
  33. logrus.Errorf("回调函数注册表没有该ip:%s", port)
  34. return
  35. }
  36. notifier.Notify()
  37. }
  38. func (s *RadioServer) OpenSerial(portName string) {
  39. // 配置串口参数
  40. options := serial.OpenOptions{
  41. PortName: portName, // /dev/ttymxc4 6 3
  42. BaudRate: 9600,
  43. DataBits: 8,
  44. StopBits: 1,
  45. MinimumReadSize: 4,
  46. }
  47. // 打开串口
  48. port, err := serial.Open(options)
  49. if err != nil {
  50. panic(err.Error())
  51. }
  52. // 关闭串口
  53. defer port.Close()
  54. for {
  55. // 读取数据
  56. buf := make([]byte, 128)
  57. n, err := port.Read(buf)
  58. if err != nil {
  59. break
  60. }
  61. if n < 8 {
  62. continue
  63. }
  64. result := false
  65. if buf[0] == 'x' && (buf[1] > '0' || buf[2] > '0' || buf[3] > '0') {
  66. result = true
  67. }
  68. if result {
  69. s.Callback(portName)
  70. }
  71. }
  72. }