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.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. }
  42. bridge, err := config.BridgeRepository().Find(ctx, devices[0].BridgeID)
  43. if err != nil {
  44. log.Println("Publishing error (1): " + err.Error())
  45. return
  46. }
  47. driver, err := config.DriverProvider().Provide(bridge.Driver)
  48. if err != nil {
  49. log.Println("Publishing error (2): " + err.Error())
  50. return
  51. }
  52. err = driver.Publish(ctx, bridge, devices)
  53. if err != nil {
  54. log.Println("Publishing error (3): " + err.Error())
  55. return
  56. }
  57. }(devices)
  58. }
  59. wg.Wait()
  60. cancel()
  61. }
  62. }()
  63. }