server.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. package lc
  2. import (
  3. "github.com/sirupsen/logrus"
  4. "lc-smartX/util"
  5. "lc-smartX/util/gopool"
  6. "time"
  7. )
  8. type SmartXServer interface {
  9. Serve()
  10. }
  11. func StartSmartXServer(s SmartXServer) {
  12. s.Serve()
  13. }
  14. type IntersectionServer struct {
  15. MainState byte
  16. SubState byte
  17. MainDevices []IDevice
  18. SubDevices []IDevice
  19. ReTicker *time.Ticker
  20. Main *time.Ticker
  21. Sub *time.Ticker
  22. }
  23. type MainNotifier struct{ s *IntersectionServer }
  24. // Notify 主路来车,通知支路设备
  25. func (m MainNotifier) Notify() {
  26. m.s.Main.Reset(5 * time.Second)
  27. if m.s.MainState != 1 {
  28. m.s.MainState = 1
  29. for _, v := range m.s.SubDevices {
  30. gopool.Go(v.Call)
  31. }
  32. }
  33. }
  34. type SubNotifier struct{ s *IntersectionServer }
  35. // Notify 支路来车,通知主路设备
  36. func (s SubNotifier) Notify() {
  37. s.s.Sub.Reset(5 * time.Second)
  38. if s.s.SubState != 1 {
  39. s.s.SubState = 1
  40. for _, v := range s.s.MainDevices {
  41. gopool.Go(v.Call)
  42. }
  43. }
  44. }
  45. func (is *IntersectionServer) Serve() {
  46. RegisterCallback(1, &SubNotifier{is})
  47. RegisterCallback(0, &MainNotifier{is})
  48. //先创建响应设备
  49. for _, v := range util.Config.OutputDevices {
  50. iDevice := &IntersectionDevice{
  51. Info: v,
  52. }
  53. iDevice.ReConnect() //初次连接
  54. if iDevice.Info.Branch == 1 {
  55. is.MainDevices = append(is.MainDevices, iDevice)
  56. } else {
  57. is.SubDevices = append(is.SubDevices, iDevice)
  58. }
  59. }
  60. logrus.Info("主路输出设备列表:", is.MainDevices)
  61. logrus.Info("支路输出设备列表:", is.SubDevices)
  62. for {
  63. select {
  64. case <-is.Main.C: //检查主路状态->支路输出设备回到初始状态
  65. for _, v := range is.SubDevices {
  66. if is.MainState == 1 {
  67. gopool.Go(v.Back)
  68. }
  69. }
  70. is.MainState = 0
  71. case <-is.Sub.C: //检查支路状态->主路输出设备作出响应
  72. for _, v := range is.MainDevices {
  73. if is.SubState == 1 {
  74. gopool.Go(v.Back)
  75. }
  76. }
  77. is.SubState = 0
  78. case <-is.ReTicker.C: //每19s检查并尝试重连
  79. gopool.Go(func() {
  80. for _, v := range is.MainDevices {
  81. v.ReConnect()
  82. }
  83. })
  84. gopool.Go(func() {
  85. for _, v := range is.SubDevices {
  86. v.ReConnect()
  87. }
  88. })
  89. }
  90. }
  91. }
  92. // LServer ###
  93. // ===
  94. // ===
  95. // ===
  96. // === todo 服务器模式没测通,屏没有连接服务器