radar_event.go 1.6 KB

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