-
-
Notifications
You must be signed in to change notification settings - Fork 172
/
listen.go
98 lines (84 loc) · 2.62 KB
/
listen.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
package ios
import (
"bytes"
"fmt"
"howett.net/plist"
)
//ListenType contains infos for creating a LISTEN message for USBMUX
type ListenType struct {
MessageType string
ProgName string
ClientVersionString string
ConnType int
kLibUSBMuxVersion int
}
//AttachedMessage contains some info about when iOS devices are connected or disconnected from the host
type AttachedMessage struct {
MessageType string
DeviceID int
Properties DeviceProperties
}
func (a AttachedMessage) DeviceEntry() DeviceEntry {
return DeviceEntry{DeviceID: a.DeviceID, MessageType: "Attached", Properties: a.Properties}
}
func attachedFromBytes(plistBytes []byte) (AttachedMessage, error) {
decoder := plist.NewDecoder(bytes.NewReader(plistBytes))
var obj AttachedMessage
err := decoder.Decode(&obj)
if err != nil {
return obj, err
}
return obj, nil
}
//DeviceAttached checks if the attached message is about a newly added device
func (msg AttachedMessage) DeviceAttached() bool {
return "Attached" == msg.MessageType
}
//DeviceDetached checks if the attachedMessage is about a disconnected device
func (msg AttachedMessage) DeviceDetached() bool {
return "Detached" == msg.MessageType
}
//NewListen creates a new Listen Message for USBMUX
func NewListen() ListenType {
data := ListenType{
MessageType: "Listen",
ProgName: "go-usbmux",
ClientVersionString: "usbmuxd-471.8.1",
//Seems like Conntype is not really needed
ConnType: 1,
kLibUSBMuxVersion: 3,
}
return data
}
//Listen will send a listen command to usbmuxd which will cause this connection to stay open indefinitely and receive
// messages whenever devices are connected or disconnected
func (muxConn *UsbMuxConnection) Listen() (func() (AttachedMessage, error), error) {
msg := NewListen()
err := muxConn.Send(msg)
if err != nil {
return nil, err
}
response, err := muxConn.ReadMessage()
if err != nil {
return nil, err
}
if !MuxResponsefromBytes(response.Payload).IsSuccessFull() {
return nil, fmt.Errorf("Listen command to usbmuxd failed: %x", response.Payload)
}
return func() (AttachedMessage, error) {
mux, err := muxConn.ReadMessage()
if err != nil {
return AttachedMessage{}, err
}
return attachedFromBytes(mux.Payload)
}, nil
}
func Listen() (func() (AttachedMessage, error), func() error, error) {
deviceConn, err := NewDeviceConnection(GetUsbmuxdSocket())
if err != nil {
return nil, nil, fmt.Errorf("could not connect to usbmuxd: %w", err)
}
muxConnection := NewUsbMuxConnection(deviceConn)
attachedReceiver, err := muxConnection.Listen()
return attachedReceiver, muxConnection.Close, err
}