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.

81 lines
1.6 KiB

4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
3 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. "sync"
  8. "time"
  9. )
  10. func StartPublisher() {
  11. ctx := context.Background()
  12. go func() {
  13. for devices := range config.PublishChannel {
  14. if len(devices) == 0 {
  15. continue
  16. }
  17. lists := make(map[int][]models.Device, 4)
  18. for _, device := range devices {
  19. lists[device.BridgeID] = append(lists[device.BridgeID], device)
  20. }
  21. ctx, cancel := context.WithTimeout(ctx, time.Second * 30)
  22. bridges, err := config.BridgeRepository().FetchAll(ctx)
  23. if err != nil {
  24. log.Println("Publishing error (1): " + err.Error())
  25. cancel()
  26. continue
  27. }
  28. wg := sync.WaitGroup{}
  29. for _, devices := range lists {
  30. wg.Add(1)
  31. go func(devices []models.Device) {
  32. defer wg.Done()
  33. var bridge models.Bridge
  34. for _, bridge2 := range bridges {
  35. if bridge2.ID == devices[0].BridgeID {
  36. bridge = bridge2
  37. }
  38. }
  39. if bridge.ID == 0 {
  40. log.Println("Unknown bridge")
  41. return
  42. }
  43. if bridge.Driver == models.DTLIFX {
  44. return
  45. }
  46. bridge, err := config.BridgeRepository().Find(ctx, devices[0].BridgeID)
  47. if err != nil {
  48. log.Println("Publishing error (1): " + err.Error())
  49. return
  50. }
  51. driver, err := config.DriverProvider().Provide(bridge.Driver)
  52. if err != nil {
  53. log.Println("Publishing error (2): " + err.Error())
  54. return
  55. }
  56. err = driver.Publish(ctx, bridge, devices)
  57. if err != nil {
  58. log.Println("Publishing error (3): " + err.Error())
  59. return
  60. }
  61. }(devices)
  62. }
  63. wg.Wait()
  64. cancel()
  65. }
  66. }()
  67. }