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.

88 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 main
  13. import (
  14. "context"
  15. "fmt"
  16. "os"
  17. "time"
  18. "github.com/bboozzoo/mconnect/discovery"
  19. "github.com/bboozzoo/mconnect/logger"
  20. "github.com/bboozzoo/mconnect/protocol/packet"
  21. )
  22. var (
  23. Stderr = os.Stderr
  24. Stdout = os.Stdout
  25. )
  26. func main() {
  27. ctx := context.Background()
  28. ctx = logger.WithContext(ctx, logger.New())
  29. log := logger.FromContext(ctx)
  30. log.SetLevel(logger.ErrorLevel)
  31. log.Infof("setting up listener")
  32. l, err := discovery.NewListener()
  33. if err != nil {
  34. fmt.Fprintf(Stderr, "error: failed to setup listener: %v\n",
  35. err)
  36. os.Exit(1)
  37. }
  38. hostname, err := os.Hostname()
  39. if err != nil {
  40. fmt.Fprintf(Stderr, "error: failed to obtain hostname: %v\n",
  41. err)
  42. os.Exit(1)
  43. }
  44. go func() {
  45. for {
  46. err := discovery.Announce(ctx, packet.Identity{
  47. DeviceId: "mconnect-" + hostname,
  48. DeviceName: hostname,
  49. DeviceType: "computer",
  50. ProtocolVersion: 7,
  51. TcpPort: 1716,
  52. })
  53. if err != nil {
  54. log.Errorf("failed to self announce: %v", err)
  55. }
  56. time.Sleep(5 * time.Second)
  57. }
  58. }()
  59. devices := map[string]*discovery.Discovery{}
  60. for {
  61. log.Info("receive wait")
  62. d, err := l.Receive(ctx)
  63. if err != nil {
  64. log.Warning("failed to receive identity packet: %v", err)
  65. continue
  66. }
  67. log.Infof("discovered a device at %s packet: %v",
  68. d.From, d.Identity)
  69. if _, ok := devices[d.Identity.DeviceId]; !ok {
  70. devices[d.Identity.DeviceId] = d
  71. fmt.Fprintf(Stdout, " * %q (ID: %v) %v\n",
  72. d.Identity.DeviceName,
  73. d.Identity.DeviceId,
  74. d.From.IP)
  75. }
  76. }
  77. }