You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

76 lines
1.7 KiB

4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
  1. package services
  2. import (
  3. "context"
  4. "git.aiterp.net/lucifer/new-server/app/config"
  5. "git.aiterp.net/lucifer/new-server/models"
  6. "log"
  7. "strconv"
  8. "sync"
  9. "time"
  10. )
  11. var cancelMap = make(map[int]context.CancelFunc, 8)
  12. var cancelMutex sync.Mutex
  13. func ConnectToBridges() {
  14. go func() {
  15. for {
  16. err := runConnectToBridges()
  17. if err != nil {
  18. log.Println("Bridge connection error: ", err.Error())
  19. }
  20. time.Sleep(15 * time.Second)
  21. }
  22. }()
  23. }
  24. func runConnectToBridges() error {
  25. bridges, err := config.BridgeRepository().FetchAll(context.Background())
  26. if err != nil {
  27. return err
  28. }
  29. for _, bridge := range bridges {
  30. cancelMutex.Lock()
  31. isRunning := cancelMap[bridge.ID] != nil
  32. cancelMutex.Unlock()
  33. if isRunning {
  34. continue
  35. }
  36. driver, err := config.DriverProvider().Provide(bridge.Driver)
  37. if err != nil {
  38. return err
  39. }
  40. ctx, cancel := context.WithCancel(context.Background())
  41. cancelMutex.Lock()
  42. cancelMap[bridge.ID] = cancel
  43. cancelMutex.Unlock()
  44. log.Printf("Running bridge \"%s\" (%d)", bridge.Name, bridge.ID)
  45. go func(bridge models.Bridge, cancel func()) {
  46. savedDevices, err := config.DeviceRepository().FetchByReference(ctx, models.RKBridgeID, strconv.Itoa(bridge.ID))
  47. if err != nil {
  48. log.Println("Failed to fetch devices from db for refresh:", err)
  49. }
  50. err = driver.Publish(ctx, bridge, savedDevices)
  51. if err != nil {
  52. log.Println("Failed to publish devices from db before run:", err)
  53. }
  54. err = driver.Run(ctx, bridge, config.EventChannel)
  55. log.Printf("Bridge \"%s\" (%d) stopped: %s", bridge.Name, bridge.ID, err)
  56. cancelMutex.Lock()
  57. cancel()
  58. cancelMap[bridge.ID] = nil
  59. cancelMutex.Unlock()
  60. }(bridge, cancel)
  61. }
  62. return nil
  63. }