agent_handlers.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. // SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
  2. // SPDX-License-Identifier: MIT
  3. package ice
  4. // OnConnectionStateChange sets a handler that is fired when the connection state changes
  5. func (a *Agent) OnConnectionStateChange(f func(ConnectionState)) error {
  6. a.onConnectionStateChangeHdlr.Store(f)
  7. return nil
  8. }
  9. // OnSelectedCandidatePairChange sets a handler that is fired when the final candidate
  10. // pair is selected
  11. func (a *Agent) OnSelectedCandidatePairChange(f func(Candidate, Candidate)) error {
  12. a.onSelectedCandidatePairChangeHdlr.Store(f)
  13. return nil
  14. }
  15. // OnCandidate sets a handler that is fired when new candidates gathered. When
  16. // the gathering process complete the last candidate is nil.
  17. func (a *Agent) OnCandidate(f func(Candidate)) error {
  18. a.onCandidateHdlr.Store(f)
  19. return nil
  20. }
  21. func (a *Agent) onSelectedCandidatePairChange(p *CandidatePair) {
  22. if h, ok := a.onSelectedCandidatePairChangeHdlr.Load().(func(Candidate, Candidate)); ok {
  23. h(p.Local, p.Remote)
  24. }
  25. }
  26. func (a *Agent) onCandidate(c Candidate) {
  27. if onCandidateHdlr, ok := a.onCandidateHdlr.Load().(func(Candidate)); ok {
  28. onCandidateHdlr(c)
  29. }
  30. }
  31. func (a *Agent) onConnectionStateChange(s ConnectionState) {
  32. if hdlr, ok := a.onConnectionStateChangeHdlr.Load().(func(ConnectionState)); ok {
  33. hdlr(s)
  34. }
  35. }
  36. func (a *Agent) candidatePairRoutine() {
  37. for p := range a.chanCandidatePair {
  38. a.onSelectedCandidatePairChange(p)
  39. }
  40. }
  41. func (a *Agent) connectionStateRoutine() {
  42. for s := range a.chanState {
  43. go a.onConnectionStateChange(s)
  44. }
  45. }
  46. func (a *Agent) candidateRoutine() {
  47. for c := range a.chanCandidate {
  48. a.onCandidate(c)
  49. }
  50. }