mconnect - KDE Connect protocol implementation in Vala/C
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.

80 lines
2.1 KiB

  1. // Licensed under the Apache License, Version 2.0 (the "License");
  2. // you may not use this file except in compliance with the License.
  3. // You may obtain a copy of the License at
  4. //
  5. // http://www.apache.org/licenses/LICENSE-2.0
  6. //
  7. // Unless required by applicable law or agreed to in writing, software
  8. // distributed under the License is distributed on an "AS IS" BASIS,
  9. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. // See the License for the specific language governing permissions and
  11. // limitations under the License.
  12. package discovery
  13. import (
  14. "context"
  15. "net"
  16. "github.com/pkg/errors"
  17. "github.com/bboozzoo/mconnect/logger"
  18. "github.com/bboozzoo/mconnect/protocol/packet"
  19. )
  20. type Listener struct {
  21. conn *net.UDPConn
  22. }
  23. func NewListener() (*Listener, error) {
  24. addr := net.UDPAddr{
  25. Port: 1714,
  26. }
  27. conn, err := net.ListenUDP("udp", &addr)
  28. if err != nil {
  29. return nil, err
  30. }
  31. listener := &Listener{
  32. conn: conn,
  33. }
  34. return listener, nil
  35. }
  36. // Discovery conveys the received discovery information
  37. type Discovery struct {
  38. // Packet is the original packet received
  39. Packet *packet.Packet
  40. // Identity is the parsed identity data
  41. Identity *packet.Identity
  42. // From is the address the packet was received from
  43. From *net.UDPAddr
  44. }
  45. // Receive blocks waiting to receive a discovery packet. Once received, it will
  46. // parse the packet and return a result.
  47. func (l *Listener) Receive(ctx context.Context) (*Discovery, error) {
  48. log := logger.FromContext(ctx)
  49. buf := make([]byte, 4096)
  50. count, addr, err := l.conn.ReadFromUDP(buf)
  51. if err != nil {
  52. return nil, errors.Wrap(err, "failed to receive a packet")
  53. }
  54. log.Debugf("got %v bytes from %v", count, addr)
  55. log.Debugf("data:\n%s", string(buf))
  56. p, err := packet.FromData(buf)
  57. if err != nil {
  58. return nil, errors.Wrap(err, "failed to parse packet")
  59. }
  60. identity, err := p.AsIdentity()
  61. if err != nil {
  62. return nil, errors.Wrap(err, "failed to parse as identity packet")
  63. }
  64. discovery := &Discovery{
  65. Packet: p,
  66. Identity: identity,
  67. From: addr,
  68. }
  69. return discovery, nil
  70. }