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.

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