event.go 1.6 KB

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