Skip to content

Commit a25f9ff

Browse files
authored
Merge pull request #2 from arduino/refactored
Refactored code
2 parents 1c38363 + b9c51a2 commit a25f9ff

File tree

6 files changed

+195
-190
lines changed

6 files changed

+195
-190
lines changed

args.go

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
//
2+
// This file is part of mdns-discovery.
3+
//
4+
// Copyright 2021 ARDUINO SA (http://www.arduino.cc/)
5+
//
6+
// This software is released under the GNU General Public License version 3,
7+
// which covers the main part of arduino-cli.
8+
// The terms of this license can be found at:
9+
// https://www.gnu.org/licenses/gpl-3.0.en.html
10+
//
11+
// You can be released from the requirements of the above licenses by purchasing
12+
// a commercial license. Buying such a license is mandatory if you want to modify or
13+
// otherwise use the software for commercial activities involving the Arduino
14+
// software without disclosing the source code of your own applications. To purchase
15+
// a commercial license, send an email to license@arduino.cc.
16+
//
17+
18+
package main
19+
20+
import (
21+
"fmt"
22+
"os"
23+
24+
"github.com/arduino/mdns-discovery/version"
25+
)
26+
27+
func parseArgs() {
28+
for _, arg := range os.Args[1:] {
29+
if arg == "" {
30+
continue
31+
}
32+
if arg == "-v" || arg == "--version" {
33+
fmt.Printf("mdns-discovery %s (build timestamp: %s)\n", version.Tag, version.Timestamp)
34+
os.Exit(0)
35+
}
36+
fmt.Fprintf(os.Stderr, "invalid argument: %s\n", arg)
37+
os.Exit(1)
38+
}
39+
}

go.mod

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
module github.com/arduino/mdns-discovery
2+
3+
go 1.16
4+
5+
require (
6+
github.com/arduino/go-paths-helper v1.6.1 // indirect
7+
github.com/arduino/go-properties-orderedmap v1.5.0
8+
github.com/arduino/pluggable-discovery-protocol-handler v1.1.0
9+
github.com/brutella/dnssd v1.1.1
10+
github.com/miekg/dns v1.1.31 // indirect
11+
golang.org/x/crypto v0.0.0-20201002094018-c90954cbb977 // indirect
12+
golang.org/x/net v0.0.0-20200930145003-4acb6c075d10 // indirect
13+
golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f // indirect
14+
)

go.sum

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
github.com/arduino/go-paths-helper v1.0.1/go.mod h1:HpxtKph+g238EJHq4geEPv9p+gl3v5YYu35Yb+w31Ck=
2+
github.com/arduino/go-paths-helper v1.6.1 h1:lha+/BuuBsx0qTZ3gy6IO1kU23lObWdQ/UItkzVWQ+0=
3+
github.com/arduino/go-paths-helper v1.6.1/go.mod h1:V82BWgAAp4IbmlybxQdk9Bpkz8M4Qyx+RAFKaG9NuvU=
4+
github.com/arduino/go-properties-orderedmap v1.4.0/go.mod h1:DKjD2VXY/NZmlingh4lSFMEYCVubfeArCsGPGDwb2yk=
5+
github.com/arduino/go-properties-orderedmap v1.5.0 h1:istmr13qQN3nneuU3lsqlMvI6jqB3u8QUfVU1tX/t/8=
6+
github.com/arduino/go-properties-orderedmap v1.5.0/go.mod h1:DKjD2VXY/NZmlingh4lSFMEYCVubfeArCsGPGDwb2yk=
7+
github.com/arduino/pluggable-discovery-protocol-handler v1.1.0 h1:/fYOQ9f6beV9+mv9rDs+kvkhNKJ1edIT0RvIRj5Jj4U=
8+
github.com/arduino/pluggable-discovery-protocol-handler v1.1.0/go.mod h1:vQfYGJnunfcscLoUcZKqJBlEkZ/qiE28TQj+RV9UT74=
9+
github.com/brutella/dnssd v1.1.1 h1:Ar5ytE2Z9x5DTmuNnASlMTBpcQWQLm9ceHb326s0ykg=
10+
github.com/brutella/dnssd v1.1.1/go.mod h1:9gIcMKQSJvYlO2x+HR50cqqjghb9IWK9hvykmyveVVs=
11+
github.com/davecgh/go-spew v1.1.0 h1:ZDRjVQ15GmhC3fiQ8ni8+OwkZQO4DARzQgrnXU1Liz8=
12+
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
13+
github.com/miekg/dns v1.1.1/go.mod h1:W1PPwlIAgtquWBMBEV9nkV9Cazfe8ScdGz/Lj7v3Nrg=
14+
github.com/miekg/dns v1.1.31 h1:sJFOl9BgwbYAWOGEwr61FU28pqsBNdpRBnhGXtO06Oo=
15+
github.com/miekg/dns v1.1.31/go.mod h1:KNUDUusw/aVsxyTYZM1oqvCicbwhgbNgztCETuNZ7xM=
16+
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
17+
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
18+
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
19+
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
20+
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
21+
github.com/stretchr/testify v1.3.0 h1:TivCn/peBQ7UY8ooIcPgZFpTNSz0Q2U6UrFlUfqbe0Q=
22+
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
23+
golang.org/x/crypto v0.0.0-20181203042331-505ab145d0a9/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4=
24+
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
25+
golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
26+
golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
27+
golang.org/x/crypto v0.0.0-20201002094018-c90954cbb977 h1:yH6opeNE+0SY+7pXT4gclZUoKHogXeC2EvOSHGOMGPU=
28+
golang.org/x/crypto v0.0.0-20201002094018-c90954cbb977/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
29+
golang.org/x/mod v0.1.1-0.20191105210325-c90efee705ee/go.mod h1:QqPTAvyqsEbceGzBzNggFXnrqF1CaUcvgkdR5Ot7KZg=
30+
golang.org/x/net v0.0.0-20181201002055-351d144fa1fc/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
31+
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
32+
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
33+
golang.org/x/net v0.0.0-20190923162816-aa69164e4478/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
34+
golang.org/x/net v0.0.0-20200930145003-4acb6c075d10 h1:YfxMZzv3PjGonQYNUaeU2+DhAdqOxerQ30JFB6WgAXo=
35+
golang.org/x/net v0.0.0-20200930145003-4acb6c075d10/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA=
36+
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
37+
golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e h1:vcxGaoTs7kV8m5Np9uUNQin4BrLOthgV7252N8V+FwY=
38+
golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
39+
golang.org/x/sys v0.0.0-20181206074257-70b957f3b65e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
40+
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
41+
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
42+
golang.org/x/sys v0.0.0-20190924154521-2837fb4f24fe/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
43+
golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
44+
golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f h1:+Nyd8tzPX9R7BWHguqsrbFdRx3WQ/1ib8I44HXV5yTA=
45+
golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
46+
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
47+
golang.org/x/tools v0.0.0-20191216052735-49a3e744a425/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28=
48+
golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=

main.go

Lines changed: 70 additions & 121 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
//
2-
// This file is part of serial-discovery.
2+
// This file is part of mdns-discovery.
33
//
4-
// Copyright 2018 ARDUINO SA (http://www.arduino.cc/)
4+
// Copyright 2018-2021 ARDUINO SA (http://www.arduino.cc/)
55
//
66
// This software is released under the GNU General Public License version 3,
77
// which covers the main part of arduino-cli.
@@ -18,153 +18,102 @@
1818
package main
1919

2020
import (
21-
"bufio"
22-
"encoding/json"
21+
"context"
2322
"fmt"
2423
"os"
2524
"strconv"
26-
"strings"
27-
"sync"
2825

2926
properties "github.com/arduino/go-properties-orderedmap"
27+
discovery "github.com/arduino/pluggable-discovery-protocol-handler"
3028
"github.com/brutella/dnssd"
3129
)
3230

3331
func main() {
34-
syncStarted := false
35-
var syncCloseChan chan<- bool
36-
37-
reader := bufio.NewReader(os.Stdin)
38-
for {
39-
cmd, err := reader.ReadString('\n')
40-
if err != nil {
41-
outputError(err)
42-
os.Exit(1)
43-
}
44-
cmd = strings.ToUpper(strings.TrimSpace(cmd))
45-
switch cmd {
46-
case "START":
47-
outputMessage("start", "OK")
48-
case "STOP":
49-
if syncStarted {
50-
syncCloseChan <- true
51-
syncStarted = false
52-
}
53-
outputMessage("stop", "OK")
54-
case "LIST":
55-
outputList()
56-
case "QUIT":
57-
outputMessage("quit", "OK")
58-
os.Exit(0)
59-
case "START_SYNC":
60-
if syncStarted {
61-
outputMessage("startSync", "OK")
62-
} else if close, err := startSync(); err != nil {
63-
outputError(err)
64-
} else {
65-
syncCloseChan = close
66-
syncStarted = true
67-
}
68-
default:
69-
outputError(fmt.Errorf("Command %s not supported", cmd))
70-
}
32+
parseArgs()
33+
mdnsDiscovery := &MDNSDiscovery{}
34+
disc := discovery.NewDiscoveryServer(mdnsDiscovery)
35+
if err := disc.Run(os.Stdin, os.Stdout); err != nil {
36+
fmt.Fprintf(os.Stderr, "Error: %s\n", err.Error())
37+
os.Exit(1)
7138
}
39+
7240
}
7341

74-
type boardPortJSON struct {
75-
Address string `json:"address"`
76-
Label string `json:"label,omitempty"`
77-
Prefs *properties.Map `json:"prefs,omitempty"`
78-
IdentificationPrefs *properties.Map `json:"identificationPrefs,omitempty"`
79-
Protocol string `json:"protocol,omitempty"`
80-
ProtocolLabel string `json:"protocolLabel,omitempty"`
42+
const mdnsServiceName = "_arduino._tcp.local."
43+
44+
type MDNSDiscovery struct {
45+
cancelFunc func()
8146
}
8247

83-
type listOutputJSON struct {
84-
EventType string `json:"eventType"`
85-
Ports []*boardPortJSON `json:"ports"`
48+
// Hello handles the pluggable-discovery HELLO command
49+
func (d *MDNSDiscovery) Hello(userAgent string, protocolVersion int) error {
50+
return nil
8651
}
8752

88-
func outputList() {
89-
/*
90-
list, err := enumerator.GetDetailedPortsList()
91-
if err != nil {
92-
outputError(err)
93-
return
94-
}
95-
portsJSON := []*boardPortJSON{}
96-
for _, port := range list {
97-
portJSON := newBoardPortJSON(port)
98-
portsJSON = append(portsJSON, portJSON)
99-
}
100-
d, err := json.MarshalIndent(&listOutputJSON{
101-
EventType: "list",
102-
Ports: portsJSON,
103-
}, "", " ")
104-
if err != nil {
105-
outputError(err)
106-
return
107-
}
108-
syncronizedPrintLn(string(d))
109-
*/
53+
// Start handles the pluggable-discovery START command
54+
func (d *MDNSDiscovery) Start() error {
55+
return nil
11056
}
11157

112-
func newBoardPortJSON(port *dnssd.Service) *boardPortJSON {
113-
prefs := properties.NewMap()
114-
identificationPrefs := properties.NewMap()
58+
// Stop handles the pluggable-discovery STOP command
59+
func (d *MDNSDiscovery) Stop() error {
60+
if d.cancelFunc != nil {
61+
d.cancelFunc()
62+
d.cancelFunc = nil
63+
}
64+
return nil
65+
}
11566

116-
ip := "127.0.0.1"
67+
// Quit handles the pluggable-discovery QUIT command
68+
func (d *MDNSDiscovery) Quit() {
69+
}
70+
71+
// List handles the pluggable-discovery LIST command
72+
func (d *MDNSDiscovery) List() ([]*discovery.Port, error) {
73+
return []*discovery.Port{}, nil
74+
}
75+
76+
// StartSync handles the pluggable-discovery START_SYNC command
77+
func (d *MDNSDiscovery) StartSync(eventCB discovery.EventCallback, errorCB discovery.ErrorCallback) error {
78+
addFn := func(srv dnssd.Service) {
79+
eventCB("add", newBoardPortJSON(&srv))
80+
}
81+
remFn := func(srv dnssd.Service) {
82+
eventCB("remove", newBoardPortJSON(&srv))
83+
}
84+
ctx, cancel := context.WithCancel(context.Background())
85+
86+
go func() {
87+
if err := dnssd.LookupType(ctx, mdnsServiceName, addFn, remFn); err != nil {
88+
errorCB("mdns lookup error: " + err.Error())
89+
}
90+
}()
91+
d.cancelFunc = cancel
92+
return nil
93+
}
11794

95+
func newBoardPortJSON(port *dnssd.Service) *discovery.Port {
96+
ip := "127.0.0.1"
11897
if len(port.IPs) > 0 {
11998
ip = port.IPs[0].String()
12099
}
121100

122-
portJSON := &boardPortJSON{
123-
Address: ip,
124-
Label: port.Name + " at " + ip,
125-
Protocol: "network",
126-
ProtocolLabel: "Network Port",
127-
Prefs: prefs,
128-
IdentificationPrefs: identificationPrefs,
129-
}
130-
portJSON.Prefs.Set("ttl", port.Ttl.String())
131-
portJSON.Prefs.Set("hostname", port.Hostname())
132-
portJSON.Prefs.Set("port", strconv.Itoa(port.Port))
101+
props := properties.NewMap()
102+
props.Set("ttl", strconv.Itoa(int(port.TTL.Seconds())))
103+
props.Set("hostname", port.Hostname())
104+
props.Set("port", strconv.Itoa(port.Port))
133105
for key, value := range port.Text {
134-
portJSON.Prefs.Set(key, value)
106+
props.Set(key, value)
135107
if key == "board" {
136108
// duplicate for backwards compatibility
137-
identificationPrefs.Set(".", value)
109+
props.Set(".", value)
138110
}
139111
}
140-
return portJSON
141-
}
142-
143-
type messageOutputJSON struct {
144-
EventType string `json:"eventType"`
145-
Message string `json:"message"`
146-
}
147-
148-
func outputMessage(eventType, message string) {
149-
d, err := json.MarshalIndent(&messageOutputJSON{
150-
EventType: eventType,
151-
Message: message,
152-
}, "", " ")
153-
if err != nil {
154-
outputError(err)
155-
} else {
156-
syncronizedPrintLn(string(d))
112+
return &discovery.Port{
113+
Address: ip,
114+
AddressLabel: port.Name + " at " + ip,
115+
Protocol: "network",
116+
ProtocolLabel: "Network Port",
117+
Properties: props,
157118
}
158119
}
159-
160-
func outputError(err error) {
161-
outputMessage("error", err.Error())
162-
}
163-
164-
var stdoutMutext sync.Mutex
165-
166-
func syncronizedPrintLn(a ...interface{}) {
167-
stdoutMutext.Lock()
168-
fmt.Println(a...)
169-
stdoutMutext.Unlock()
170-
}

0 commit comments

Comments
 (0)