-
Notifications
You must be signed in to change notification settings - Fork 32
Expand file tree
/
Copy pathhotplug.go
More file actions
332 lines (283 loc) · 7.98 KB
/
hotplug.go
File metadata and controls
332 lines (283 loc) · 7.98 KB
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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
// Copyright (c) 2015-2025 The libusb developers. All rights reserved.
// Project site: https://github.com/gotmc/libusb
// Use of this source code is governed by a MIT-style license that
// can be found in the LICENSE.txt file for the project.
package libusb
// #cgo pkg-config: libusb-1.0
// #include <libusb.h>
// #include <sys/time.h>
// int libusbHotplugCallback (libusb_context *ctx, libusb_device *device, libusb_hotplug_event event, void *user_data);
// typedef struct libusb_device_descriptor libusb_device_descriptor_struct;
// static int libusb_hotplug_register_callback_wrapper (
// libusb_context *ctx,
// int events, int flags,
// int vendor_id, int product_id, int dev_class,
// libusb_hotplug_callback_fn cb_fn, void *user_data,
// libusb_hotplug_callback_handle *callback_handle)
// {
// return libusb_hotplug_register_callback(ctx, events, flags, vendor_id, product_id, dev_class, cb_fn, user_data, callback_handle);
// }
// static int libusb_handle_events_timeout_ms(libusb_context *ctx, int timeout_ms) {
// struct timeval tv;
// tv.tv_sec = timeout_ms / 1000;
// tv.tv_usec = (timeout_ms % 1000) * 1000;
// return libusb_handle_events_timeout_completed(ctx, &tv, NULL);
// }
import "C"
import (
"fmt"
"log"
"sync"
"unsafe"
)
// HotPlugEventType represents the type of hotplug event.
type HotPlugEventType uint8
// HotPlugCbFunc is the callback function signature for hotplug events.
type HotPlugCbFunc func(vID, pID uint16, eventType HotPlugEventType)
// HotPlug Event Types
const (
HotplugUndefined HotPlugEventType = iota
HotplugArrived
HotplugLeft
)
// HotPlugEvent callback message
type HotPlugEvent struct {
VendorID uint16
ProductID uint16
Event HotPlugEventType
}
type hotplugCallback struct {
handler *C.libusb_hotplug_callback_handle
fn HotPlugCbFunc
}
// HotplugCallbackStorage holds the callback map and done channel for a single
// context.
type HotplugCallbackStorage struct {
callbackMap map[uint32]hotplugCallback
done chan struct{}
mu sync.RWMutex
}
// hotplugEventTimeoutMs is the timeout in milliseconds for
// libusb_handle_events_timeout_completed in the event loop. This prevents
// busy-spinning while still being responsive to the done signal.
const hotplugEventTimeoutMs = 200
// hotplugRegistry maps context pointers to their hotplug storage, allowing
// multiple contexts to register hotplug callbacks independently.
var (
hotplugRegistry = make(map[*C.libusb_context]*HotplugCallbackStorage)
hotplugRegistryMu sync.RWMutex
)
func getHotplugStorage(
libCtx *C.libusb_context,
) *HotplugCallbackStorage {
hotplugRegistryMu.RLock()
defer hotplugRegistryMu.RUnlock()
return hotplugRegistry[libCtx]
}
func (ctx *Context) newHotPlugHandler() *HotplugCallbackStorage {
storage := &HotplugCallbackStorage{
callbackMap: make(map[uint32]hotplugCallback),
done: make(chan struct{}),
}
hotplugRegistryMu.Lock()
hotplugRegistry[ctx.libusbContext] = storage
hotplugRegistryMu.Unlock()
go storage.handleEvents(ctx.libusbContext)
return storage
}
func (ctx *Context) getOrCreateHotplugStorage() *HotplugCallbackStorage {
storage := getHotplugStorage(ctx.libusbContext)
if storage == nil {
storage = ctx.newHotPlugHandler()
}
return storage
}
func removeHotplugStorage(libCtx *C.libusb_context) {
hotplugRegistryMu.Lock()
delete(hotplugRegistry, libCtx)
hotplugRegistryMu.Unlock()
}
// HotplugRegisterCallbackEvent registers a hotplug callback for the given
// vendor/product ID pair and event type.
func (ctx *Context) HotplugRegisterCallbackEvent(
vendorID, productID uint16,
eventType HotPlugEventType, cb HotPlugCbFunc,
) error {
storage := ctx.getOrCreateHotplugStorage()
var event C.int
switch eventType {
case HotplugArrived:
event = C.LIBUSB_HOTPLUG_EVENT_DEVICE_ARRIVED
case HotplugLeft:
event = C.LIBUSB_HOTPLUG_EVENT_DEVICE_LEFT
default:
event = C.LIBUSB_HOTPLUG_EVENT_DEVICE_ARRIVED |
C.LIBUSB_HOTPLUG_EVENT_DEVICE_LEFT
}
var vID C.int = C.LIBUSB_HOTPLUG_MATCH_ANY
var pID C.int = C.LIBUSB_HOTPLUG_MATCH_ANY
if vendorID != 0 {
vID = C.int(vendorID)
}
if productID != 0 {
pID = C.int(productID)
}
var cbHandle C.libusb_hotplug_callback_handle
rc := C.libusb_hotplug_register_callback_wrapper(
ctx.libusbContext,
event,
C.LIBUSB_HOTPLUG_NO_FLAGS,
vID,
pID,
C.LIBUSB_HOTPLUG_MATCH_ANY,
C.libusb_hotplug_callback_fn(
unsafe.Pointer(C.libusbHotplugCallback),
),
nil,
&cbHandle,
)
if rc != C.LIBUSB_SUCCESS {
return fmt.Errorf(
"libusb_hotplug_register_callback error: %s", ErrorCode(rc),
)
}
key := vidPidToUint32(vendorID, productID)
storage.mu.Lock()
storage.callbackMap[key] = hotplugCallback{
handler: &cbHandle,
fn: cb,
}
storage.mu.Unlock()
return nil
}
// HotplugDeregisterCallback deregisters a hotplug callback for the given
// vendor/product ID pair.
func (ctx *Context) HotplugDeregisterCallback(
vendorID, productID uint16,
) error {
storage := getHotplugStorage(ctx.libusbContext)
if storage == nil {
return nil
}
key := vidPidToUint32(vendorID, productID)
storage.mu.RLock()
cb, ok := storage.callbackMap[key]
storage.mu.RUnlock()
if !ok {
return nil
}
C.libusb_hotplug_deregister_callback(ctx.libusbContext, *cb.handler)
storage.mu.Lock()
delete(storage.callbackMap, key)
mapEmpty := len(storage.callbackMap) == 0
storage.mu.Unlock()
if mapEmpty {
ctx.hotplugHandleEventsCompleteAll()
}
return nil
}
// HotplugDeregisterAllCallbacks deregisters all hotplug callbacks for this
// context and stops the event handler goroutine.
func (ctx *Context) HotplugDeregisterAllCallbacks() error {
storage := getHotplugStorage(ctx.libusbContext)
if storage == nil {
return nil
}
storage.mu.RLock()
handlers := make(
[]*C.libusb_hotplug_callback_handle,
0,
len(storage.callbackMap),
)
for _, cb := range storage.callbackMap {
handlers = append(handlers, cb.handler)
}
storage.mu.RUnlock()
for _, handler := range handlers {
C.libusb_hotplug_deregister_callback(ctx.libusbContext, *handler)
}
ctx.hotplugHandleEventsCompleteAll()
return nil
}
func (ctx *Context) hotplugHandleEventsCompleteAll() {
storage := getHotplugStorage(ctx.libusbContext)
if storage == nil {
return
}
// Signal the event handler goroutine to stop. Closing the channel
// unblocks all receivers immediately without needing a separate send.
close(storage.done)
// Clean up the storage for this context.
storage.mu.Lock()
storage.callbackMap = nil
storage.mu.Unlock()
removeHotplugStorage(ctx.libusbContext)
}
func (storage *HotplugCallbackStorage) handleEvents(
libCtx *C.libusb_context,
) {
for {
select {
case <-storage.done:
return
default:
}
errno := C.libusb_handle_events_timeout_ms(
libCtx, C.int(hotplugEventTimeoutMs),
)
if errno < 0 {
if ErrorCode(errno) == errorInterrupted {
continue
}
log.Printf("handle_events error: %s", ErrorCode(errno))
}
}
}
//export libusbHotplugCallback
func libusbHotplugCallback(
ctx *C.libusb_context, dev *C.libusb_device,
event C.libusb_hotplug_event, p unsafe.Pointer,
) C.int {
var desc C.libusb_device_descriptor_struct
rc := C.libusb_get_device_descriptor(dev, &desc)
if rc != C.LIBUSB_SUCCESS {
return rc
}
vendorID := uint16(desc.idVendor)
productID := uint16(desc.idProduct)
var e HotPlugEventType
switch event {
case C.LIBUSB_HOTPLUG_EVENT_DEVICE_ARRIVED:
e = HotplugArrived
case C.LIBUSB_HOTPLUG_EVENT_DEVICE_LEFT:
e = HotplugLeft
default:
e = HotplugUndefined
}
storage := getHotplugStorage(ctx)
if storage == nil {
return C.LIBUSB_SUCCESS
}
storage.mu.RLock()
cb, ok := storage.callbackMap[vidPidToUint32(vendorID, productID)]
var deviceCallback HotPlugCbFunc
if ok {
deviceCallback = cb.fn
}
cb, ok = storage.callbackMap[0]
var allCallback HotPlugCbFunc
if ok {
allCallback = cb.fn
}
storage.mu.RUnlock()
if deviceCallback != nil {
deviceCallback(vendorID, productID, e)
}
if allCallback != nil {
allCallback(vendorID, productID, e)
}
return C.LIBUSB_SUCCESS
}
func vidPidToUint32(vID, pID uint16) uint32 {
return (uint32(vID) << 16) | (uint32(pID))
}