server.go 2.0 KB

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