-
-
Notifications
You must be signed in to change notification settings - Fork 208
Expand file tree
/
Copy pathindex.ts
More file actions
1050 lines (946 loc) · 34 KB
/
Copy pathindex.ts
File metadata and controls
1050 lines (946 loc) · 34 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
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* eslint-disable @typescript-eslint/no-explicit-any */
import { createDebug } from '../../debug'
const debug = createDebug('signalk-server:api:ble')
import cookie from 'cookie'
import fs from 'fs'
import { IRouter, NextFunction, Request, Response } from 'express'
import { Value } from '@sinclair/typebox/value'
import {
BLESettingsRequestSchema,
BLEMacParamSchema
} from '@signalk/server-api/typebox'
import { WithSecurityStrategy } from '../../security'
import { SignalKMessageHub, WithConfig } from '../../app'
import WebSocket from 'ws'
import { writeSettingsFile } from '../../config/config'
import { LocalBLEProvider } from './localProvider'
import { RemoteGatewayProvider } from './remoteProvider'
import { bleVendorName } from './bleCompanyIds'
import {
BLEProvider,
BLEProviders,
BLEAdvertisement,
BLEDeviceInfo,
BLEConsumerInfo,
BLEApi as IBLEApi,
GATTSubscriptionDescriptor,
GATTSubscriptionHandle,
BLEGattConnection,
isBLEProvider
} from '@signalk/server-api'
const BLE_API_PATH = `/signalk/v2/api/vessels/self/ble`
// Devices not seen for this long are pruned from the device table
export const DEVICE_STALE_MS = 120_000
interface BLEApplication
extends WithSecurityStrategy, SignalKMessageHub, WithConfig, IRouter {
server?: any // HTTP server for WebSocket upgrade
}
interface BLESettings {
localBluetoothManaged: boolean
localAdapters: string[] // [] = auto-enumerate all available adapters
localMaxGATTSlots: number
}
/**
* Internal extension of GATTSubscriptionHandle: providers may attach
* `_fireDisconnect` so the server can deliver disconnect callbacks when
* the underlying transport is already dead and `close()` cannot fire them.
*/
type InternalGATTSubscriptionHandle = GATTSubscriptionHandle & {
_fireDisconnect?: () => void
}
interface GATTClaim {
pluginId: string
providerId: string
handle: InternalGATTSubscriptionHandle
keepAliveTimer?: ReturnType<typeof setInterval>
}
const DEFAULT_BLE_SETTINGS: BLESettings = {
localBluetoothManaged: false,
localAdapters: [],
localMaxGATTSlots: 3
}
export class BLEApi implements IBLEApi {
private bleProviders: Map<string, BLEProvider> = new Map()
private providerUnsubscribers: Map<string, () => void> = new Map()
private deviceTable: Map<string, BLEDeviceInfo> = new Map()
private gattClaims: Map<string, GATTClaim> = new Map()
private pendingGattClaims: Set<string> = new Set()
private advertisementCallbacks: Map<string, (adv: BLEAdvertisement) => void> =
new Map()
private wsClients: Set<WebSocket> = new Set()
private localProviders: Map<string, LocalBLEProvider> = new Map() // key = providerId
private localProviderErrors: Map<string, string> = new Map() // key = adapterName
// Tracks an initLocalProviders() attempt still in flight for a given
// providerId, from before provider.init() resolves through to
// register()/startDiscovery() (or the catch-block rollback). Without
// this, two overlapping initLocalProviders() calls for the same adapter
// (e.g. start() racing a PUT /settings-triggered reinit) can both pass
// the `localProviders.has(providerId)` skip-check before either await
// completes, each construct their own LocalBLEProvider, and the later
// one's register() ends up displacing the earlier one's registration -
// but the earlier LocalBLEProvider instance keeps running its own
// discovery loop, now unreferenced by localProviders and therefore
// unreachable by shutdown.
private localProviderInitializations: Map<string, Promise<void>> = new Map()
private defaultProviderId: string | null = null
private settings: BLESettings
private remoteGatewayProvider: RemoteGatewayProvider | null = null
private devicePruneTimer?: ReturnType<typeof setInterval>
get localBluetoothManaged(): boolean {
return this.settings.localBluetoothManaged
}
get localAdapters(): string[] {
return this.settings.localAdapters
}
constructor(private app: BLEApplication) {
const appSettings = (this.app.config?.settings as any) ?? {}
if (!appSettings.bleApi) {
appSettings.bleApi = { ...DEFAULT_BLE_SETTINGS }
}
this.settings = {
...DEFAULT_BLE_SETTINGS,
...appSettings.bleApi
}
}
async start() {
this.initApiEndpoints()
this.initWebSocketEndpoint()
// Prune independently of REST polling so the device table cannot
// grow without bound when no client requests /devices
this.devicePruneTimer = setInterval(
() => this.pruneStaleDevices(),
DEVICE_STALE_MS
)
this.devicePruneTimer.unref()
this.remoteGatewayProvider = new RemoteGatewayProvider(
this.app,
this.register.bind(this),
this.unRegister.bind(this),
this.releaseGATTClaimsForProvider.bind(this)
)
this.remoteGatewayProvider.attach(this.app)
if (this.settings.localBluetoothManaged) {
await this.initLocalProviders()
}
}
// Local Bluetooth adapter support requires Linux + BlueZ. Not available on
// macOS or Windows (no DBus/BlueZ). See docs/develop/rest-api/ble_api.md.
private isLocalBLESupported(): boolean {
return process.platform === 'linux'
}
private async getAvailableAdapters(): Promise<string[]> {
// /sys/class/bluetooth is populated by the kernel for every BT adapter.
// Empty or absent means no hardware — skip to avoid DBus stack traces.
try {
const entries = fs.readdirSync('/sys/class/bluetooth')
if (entries.length === 0) {
debug('No Bluetooth hardware detected — skipping local BLE')
return []
}
} catch {
debug('No Bluetooth hardware detected — skipping local BLE')
return []
}
try {
// eslint-disable-next-line @typescript-eslint/no-require-imports
const { createBluetooth } = require('@naugehyde/node-ble')
const { bluetooth, destroy } = createBluetooth()
const adapters = await bluetooth.activeAdapters()
destroy()
return adapters.map((a: any) => a.adapter as string)
} catch {
return []
}
}
private async initLocalProviders() {
if (!this.isLocalBLESupported()) {
debug('Local Bluetooth not supported on this platform — skipping')
return
}
let adapterNames = this.settings.localAdapters
if (adapterNames.length === 0) {
adapterNames = await this.getAvailableAdapters()
if (adapterNames.length === 0) adapterNames = ['hci0']
}
for (const adapterName of adapterNames) {
const providerId = `_localBLE:${adapterName}`
if (this.localProviders.has(providerId)) continue
// Serialize against a concurrent initLocalProviders() call already
// in flight for this same adapter (see
// localProviderInitializations's comment) - await its result
// instead of racing it with a second LocalBLEProvider construction.
const inFlight = this.localProviderInitializations.get(providerId)
if (inFlight) {
await inFlight
continue
}
const initialization = this.initOneLocalProvider(
adapterName,
providerId
)
this.localProviderInitializations.set(providerId, initialization)
try {
await initialization
} finally {
if (this.localProviderInitializations.get(providerId) === initialization) {
this.localProviderInitializations.delete(providerId)
}
}
}
}
private async initOneLocalProvider(adapterName: string, providerId: string) {
let provider: LocalBLEProvider | undefined
let registeredProvider: BLEProvider | undefined
try {
provider = new LocalBLEProvider(
adapterName,
this.settings.localMaxGATTSlots,
providerId
)
await provider.init()
this.localProviders.set(providerId, provider)
this.localProviderErrors.delete(adapterName)
// Register (which wires up onAdvertisement -> _handleAdvertisement,
// populating deviceTable) before starting discovery. Discovery's
// first pass emits advertisements for every already-known device
// synchronously as part of startDiscovery(), and LocalBLEProvider's
// emitDeviceAdvertisement drops advertisements entirely when nobody
// has subscribed yet - registering afterward silently lost that
// whole first batch, leaving those devices absent from the device
// table (and therefore unreachable via subscribeGATT) until BlueZ
// happened to re-report one of their properties later.
registeredProvider = {
name: `Local Bluetooth (${adapterName})`,
methods: provider.getMethods()
}
this.register(providerId, registeredProvider)
await provider.startDiscovery()
debug.enabled &&
debug(`Local BLE provider registered and scanning: ${providerId}`)
} catch (e: any) {
// Roll back any partial state if init and/or register succeeded but
// startDiscovery failed. Only touch state that's still this
// provider's - localProviderInitializations already prevents a
// concurrent initLocalProviders() call for the same adapter from
// running at the same time as this one, but the identity checks
// stay as defense in depth (e.g. a caller invoking
// initOneLocalProvider directly, or a future refactor that removes
// the serialization).
if (this.localProviders.get(providerId) === provider) {
if (this.bleProviders.get(providerId) === registeredProvider) {
this.unRegister(providerId)
}
this.localProviders.delete(providerId)
}
if (provider) {
try {
provider.shutdown()
} catch (_e) {
/* ignore */
}
}
const msg = `Local BLE adapter ${adapterName} unavailable: ${e.message}`
debug(msg)
// Suppress console.log for expected "no hardware / no BlueZ" errors
const isExpected =
e.message?.includes('org.freedesktop.DBus.Error.ServiceUnknown') ||
e.message?.includes('not provided by any .service files') ||
e.message?.includes('ENOENT') ||
e.message?.includes('ECONNREFUSED')
if (!isExpected) {
console.log(`[BLE API] ${msg}`)
}
this.localProviderErrors.set(adapterName, e.message)
}
}
private async shutdownLocalProviders() {
// Wait out any initOneLocalProvider() calls still in flight before
// tearing anything down. Without this, a call still awaiting
// provider.startDiscovery() (DBus) can resolve *after* this method
// has already run - at that point it finishes registering/logging
// for a provider this method just unregistered and shut down, and
// its now-orphaned discovery loop is left running (unreferenced by
// localProviders, so a later shutdown can no longer find it either).
// Waiting first means initOneLocalProvider's own try/catch has always
// fully settled localProviders/bleProviders for a given providerId by
// the time the loop below runs, so there's nothing left in flight to
// race against.
//
// A single Promise.all() snapshot isn't enough: initLocalProviders()
// could still be running concurrently (e.g. a settings change firing
// again mid-shutdown) and add a *new* entry to
// localProviderInitializations while this method's own await is
// pending, and that new entry wouldn't be in the snapshot. Re-check
// and re-await until the map is actually empty, so a fresh entry
// added during the wait still gets caught before teardown proceeds.
while (this.localProviderInitializations.size > 0) {
await Promise.all(this.localProviderInitializations.values())
}
for (const [providerId, provider] of this.localProviders) {
// One misbehaving adapter must not keep the others registered
try {
this.unRegister(providerId)
provider.shutdown()
debug.enabled && debug(`Local BLE provider shut down: ${providerId}`)
} catch (e: any) {
debug.enabled &&
debug(
`Local BLE provider shutdown failed: ${providerId}: ${e.message}`
)
}
}
this.localProviders.clear()
this.localProviderErrors.clear()
}
// -------------------------------------------------------------------
// Provider registration
// -------------------------------------------------------------------
register(pluginId: string, provider: BLEProvider) {
if (!pluginId || !provider) {
throw new Error(`Error registering BLE provider ${pluginId}!`)
}
if (!isBLEProvider(provider)) {
throw new Error(`${pluginId} is missing BLEProvider properties/methods!`)
}
debug.enabled &&
debug.enabled &&
debug(`Registering BLE provider: ${pluginId} "${provider.name}"`)
if (this.bleProviders.has(pluginId)) {
this.unRegister(pluginId)
}
this.bleProviders.set(pluginId, provider)
const unsub = provider.methods.onAdvertisement((adv: BLEAdvertisement) => {
// Advertisements are routed by providerId; never trust the provider
// to stamp its own id correctly
if (adv.providerId !== pluginId) {
adv = { ...adv, providerId: pluginId }
}
this._handleAdvertisement(adv)
})
this.providerUnsubscribers.set(pluginId, unsub)
debug.enabled &&
debug(`BLE providers registered: ${this.bleProviders.size}`)
}
unRegister(pluginId: string) {
if (!pluginId) return
debug.enabled && debug(`Unregistering BLE provider: ${pluginId}`)
const unsub = this.providerUnsubscribers.get(pluginId)
if (unsub) {
unsub()
this.providerUnsubscribers.delete(pluginId)
}
for (const [mac, claim] of this.gattClaims) {
if (claim.providerId === pluginId) {
claim.handle.close().catch(() => {})
this.gattClaims.delete(mac)
}
}
this.bleProviders.delete(pluginId)
debug.enabled && debug(`BLE providers remaining: ${this.bleProviders.size}`)
}
// -------------------------------------------------------------------
// Advertisement handling
// -------------------------------------------------------------------
onAdvertisement(
pluginId: string,
callback: (adv: BLEAdvertisement) => void
): () => void {
this.advertisementCallbacks.set(pluginId, callback)
return () => {
this.advertisementCallbacks.delete(pluginId)
}
}
private _handleAdvertisement(adv: BLEAdvertisement) {
const mac = adv.mac.toUpperCase()
let device = this.deviceTable.get(mac)
if (!device) {
device = {
mac,
name: adv.name,
rssi: adv.rssi,
lastSeen: adv.timestamp,
connectable: adv.connectable ?? false,
seenBy: []
}
this.deviceTable.set(mac, device)
}
const providerEntry = device.seenBy.find(
(s) => s.providerId === adv.providerId
)
if (providerEntry) {
providerEntry.rssi = adv.rssi
providerEntry.lastSeen = adv.timestamp
} else {
device.seenBy.push({
providerId: adv.providerId,
rssi: adv.rssi,
lastSeen: adv.timestamp
})
}
// Prefer advertised name; fall back to Bluetooth SIG company ID lookup
if (adv.name) {
device.name = adv.name
} else if (!device.name) {
const companyId = Object.keys(adv.manufacturerData ?? {})[0]
if (companyId !== undefined) {
device.name = bleVendorName(parseInt(companyId)) ?? undefined
}
}
if (adv.connectable) device.connectable = true
if (adv.addressType) device.addressType = adv.addressType
// Prune providers that haven't reported this device recently
const seenByCutoff = Date.now() - DEVICE_STALE_MS
device.seenBy = device.seenBy.filter((s) => s.lastSeen > seenByCutoff)
if (device.seenBy.length > 0) {
device.rssi = Math.max(...device.seenBy.map((s) => s.rssi))
device.lastSeen = Math.max(...device.seenBy.map((s) => s.lastSeen))
}
const claim = this.gattClaims.get(mac)
device.gattClaimedBy = claim?.pluginId
for (const cb of this.advertisementCallbacks.values()) {
try {
cb(adv)
} catch (e: any) {
debug.enabled && debug(`Advertisement callback error: ${e.message}`)
}
}
if (this.wsClients.size > 0) {
const json = JSON.stringify(adv)
for (const ws of this.wsClients) {
if (ws.readyState === WebSocket.OPEN) {
ws.send(json)
}
}
}
}
// -------------------------------------------------------------------
// Device queries
// -------------------------------------------------------------------
async getDevices(): Promise<BLEDeviceInfo[]> {
this.pruneStaleDevices()
// Ensure every GATT-claimed device is in the table, even if it stopped
// advertising after connection (GATT devices typically do).
for (const [mac, claim] of this.gattClaims) {
if (!this.deviceTable.has(mac)) {
this.deviceTable.set(mac, {
mac,
rssi: 0,
lastSeen: Date.now(),
connectable: true,
seenBy: [
{ providerId: claim.providerId, rssi: 0, lastSeen: Date.now() }
]
})
}
const device = this.deviceTable.get(mac)!
device.gattClaimedBy = claim.pluginId
}
for (const [mac, device] of this.deviceTable) {
if (!this.gattClaims.has(mac)) {
device.gattClaimedBy = undefined
}
}
return Array.from(this.deviceTable.values())
}
async getDevice(mac: string): Promise<BLEDeviceInfo | null> {
mac = mac.toUpperCase()
const device = this.deviceTable.get(mac)
if (!device) return null
device.gattClaimedBy = this.gattClaims.get(mac)?.pluginId
return device
}
private pruneStaleDevices() {
const cutoff = Date.now() - DEVICE_STALE_MS
for (const [mac, device] of this.deviceTable) {
// Never prune a device that has an active GATT claim
if (this.gattClaims.has(mac)) continue
if (device.lastSeen < cutoff) {
this.deviceTable.delete(mac)
}
}
}
// -------------------------------------------------------------------
// GATT
// -------------------------------------------------------------------
/**
* Reserve a MAC before the provider call awaits, so two concurrent
* subscribeGATT/connectGATT calls for the same device cannot both pass
* the claim check. Throws when the device is claimed or being claimed.
*/
private reserveGATTClaim(mac: string) {
const existing = this.gattClaims.get(mac)
if (existing) {
throw new Error(`Device ${mac} already claimed by ${existing.pluginId}`)
}
if (this.pendingGattClaims.has(mac)) {
throw new Error(`Device ${mac} has a GATT claim in progress`)
}
this.pendingGattClaims.add(mac)
}
async subscribeGATT(
descriptor: GATTSubscriptionDescriptor,
pluginId: string,
callback: (charUuid: string, data: Buffer) => void
): Promise<GATTSubscriptionHandle> {
const mac = descriptor.mac.toUpperCase()
this.reserveGATTClaim(mac)
try {
const providerId = this.selectGATTProvider(mac)
if (!providerId) {
throw new Error(
`No provider with GATT support and available slots can see ${mac}`
)
}
const provider = this.bleProviders.get(providerId)!
const handle = await provider.methods.subscribeGATT(descriptor, callback)
debug.enabled &&
debug(`GATT claim: ${mac} → ${pluginId} via ${providerId}`)
// Ensure the device exists in the table — GATT devices may stop advertising
// once connected, so they would otherwise be pruned.
if (!this.deviceTable.has(mac)) {
this.deviceTable.set(mac, {
mac,
rssi: 0,
lastSeen: Date.now(),
connectable: true,
seenBy: [{ providerId, rssi: 0, lastSeen: Date.now() }]
})
}
// Keep lastSeen fresh for the duration of the claim so the device
// is not pruned while GATT is active (GATT devices stop advertising).
const keepAliveTimer = setInterval(() => {
const d = this.deviceTable.get(mac)
if (d) d.lastSeen = Date.now()
}, DEVICE_STALE_MS / 2)
keepAliveTimer.unref()
const claimEntry: GATTClaim = {
pluginId,
providerId,
handle,
keepAliveTimer
}
this.gattClaims.set(mac, claimEntry)
const origClose = handle.close.bind(handle)
handle.close = async () => {
clearInterval(keepAliveTimer)
this.gattClaims.delete(mac)
debug.enabled && debug(`GATT released: ${mac} (was ${pluginId})`)
return origClose()
}
return handle
} finally {
this.pendingGattClaims.delete(mac)
}
}
async connectGATT(mac: string, pluginId: string): Promise<BLEGattConnection> {
mac = mac.toUpperCase()
this.reserveGATTClaim(mac)
try {
const providerId = this.selectGATTProvider(mac)
if (!providerId) {
throw new Error(`No provider with GATT support can see ${mac}`)
}
const provider = this.bleProviders.get(providerId)!
if (!provider.methods.connectGATT) {
throw new Error(
`Provider ${providerId} does not support raw GATT connections`
)
}
const conn = await provider.methods.connectGATT(mac)
const syntheticHandle: GATTSubscriptionHandle = {
read: async () => Buffer.alloc(0),
write: async () => {},
close: async () => {
this.gattClaims.delete(mac)
await conn.disconnect()
},
get connected() {
return conn.connected
},
onDisconnect: (cb) => conn.onDisconnect(cb),
onConnect: (cb) => {
// Raw connection is already established when connectGATT returns
if (conn.connected) cb()
}
}
this.gattClaims.set(mac, {
pluginId,
providerId,
handle: syntheticHandle
})
conn.onDisconnect(() => {
this.gattClaims.delete(mac)
debug.enabled &&
debug(`Raw GATT claim auto-released (disconnect): ${mac}`)
})
return conn
} finally {
this.pendingGattClaims.delete(mac)
}
}
async releaseGATTDevice(mac: string, pluginId: string): Promise<void> {
mac = mac.toUpperCase()
const claim = this.gattClaims.get(mac)
if (!claim) return
if (claim.pluginId !== pluginId) {
throw new Error(
`Device ${mac} is claimed by ${claim.pluginId}, not ${pluginId}`
)
}
await claim.handle.close()
}
getGATTClaims(): Map<string, string> {
const result = new Map<string, string>()
for (const [mac, claim] of this.gattClaims) {
result.set(mac, claim.pluginId)
}
return result
}
private _buildSettingsResponse() {
const adapterErrors: Record<string, string> = {}
for (const [k, v] of this.localProviderErrors) {
adapterErrors[k] = v
}
return {
localBluetoothManaged: this.settings.localBluetoothManaged,
localAdapters: this.settings.localAdapters,
localMaxGATTSlots: this.settings.localMaxGATTSlots,
localBLESupported: this.isLocalBLESupported(),
activeAdapters: Array.from(this.localProviders.keys()),
adapterErrors
}
}
/**
* Release all GATT claims held through the given providerId.
* Called when a gateway WS disconnects so plugins can re-subscribe
* via another provider (or the same one when it reconnects).
*/
releaseGATTClaimsForProvider(providerId: string) {
for (const [mac, claim] of this.gattClaims) {
if (claim.providerId === providerId) {
if (claim.keepAliveTimer) clearInterval(claim.keepAliveTimer)
this.gattClaims.delete(mac)
debug.enabled &&
debug(
`GATT claim released (gateway offline): ${mac} was ${claim.pluginId} via ${providerId}`
)
// Fire disconnect callbacks so the plugin knows to reconnect via
// another provider. Don't call handle.close() — the WS is already
// dead and close() does not fire disconnectCallbacks.
claim.handle._fireDisconnect?.()
}
}
}
private selectGATTProvider(mac: string): string | undefined {
const device = this.deviceTable.get(mac)
if (!device) return undefined
// Sort providers by RSSI (strongest first), filter to those with
// GATT support and available slots
const candidates = device.seenBy
.filter((s) => {
const provider = this.bleProviders.get(s.providerId)
return (
provider &&
provider.methods.supportsGATT() &&
provider.methods.availableGATTSlots() > 0
)
})
.sort((a, b) => b.rssi - a.rssi)
if (candidates.length === 0) return undefined
// Prefer the default provider if it is among the candidates
if (this.defaultProviderId) {
const preferred = candidates.find(
(c) => c.providerId === this.defaultProviderId
)
if (preferred) return preferred.providerId
}
return candidates[0].providerId
}
// -------------------------------------------------------------------
// REST endpoints
// -------------------------------------------------------------------
private initApiEndpoints() {
debug.enabled && debug(`Initialise ${BLE_API_PATH} endpoints`)
this.app.use(
`${BLE_API_PATH}/*`,
(req: Request, res: Response, next: NextFunction) => {
if (['PUT', 'POST', 'DELETE'].includes(req.method)) {
if (
!this.app.securityStrategy.shouldAllowPut(
req,
'vessels.self',
null,
'ble'
)
) {
res.status(403).json({ message: 'Unauthorized' })
return
}
}
next()
}
)
this.app.get(`${BLE_API_PATH}`, async (_req: Request, res: Response) => {
res.json({
devices: {
description:
'All visible BLE devices across all providers, deduplicated by MAC'
},
providers: {
description: 'Registered BLE providers'
},
gattClaims: {
description: 'Current GATT connection claims'
}
})
})
this.app.get(
`${BLE_API_PATH}/_providers`,
async (_req: Request, res: Response) => {
const providers: BLEProviders = {}
for (const [id, provider] of this.bleProviders) {
const available = provider.methods.availableGATTSlots()
const total = provider.methods.totalGATTSlots
? provider.methods.totalGATTSlots()
: available
providers[id] = {
name: provider.name,
supportsGATT: provider.methods.supportsGATT(),
gattSlots: { total, available }
}
}
res.json(providers)
}
)
this.app.get(
`${BLE_API_PATH}/_providers/_default`,
async (_req: Request, res: Response) => {
res.json({ id: this.defaultProviderId })
}
)
this.app.post(
`${BLE_API_PATH}/_providers/_default/:id`,
async (req: Request, res: Response) => {
const id = req.params.id
if (!id) {
res.status(400).json({ error: 'Provider id not supplied' })
return
}
if (this.bleProviders.has(id)) {
this.defaultProviderId = id
res.json({
state: 'COMPLETED',
message: `Default provider set to ${id}`
})
} else {
res.status(404).json({ error: `Provider ${id} not found` })
}
}
)
this.app.get(
`${BLE_API_PATH}/devices`,
async (_req: Request, res: Response) => {
const devices = await this.getDevices()
res.json(devices)
}
)
this.app.get(
`${BLE_API_PATH}/devices/:mac`,
async (req: Request, res: Response) => {
if (!Value.Check(BLEMacParamSchema, req.params.mac)) {
res.status(400).json({ message: 'Invalid MAC address' })
return
}
const device = await this.getDevice(req.params.mac)
if (device) {
res.json(device)
} else {
res.status(404).json({ message: 'Device not found' })
}
}
)
this.app.get(
`${BLE_API_PATH}/devices/:mac/gatt`,
async (req: Request, res: Response) => {
if (!Value.Check(BLEMacParamSchema, req.params.mac)) {
res.status(400).json({ message: 'Invalid MAC address' })
return
}
const mac = req.params.mac.toUpperCase()
const claim = this.gattClaims.get(mac)
res.json({
claimedBy: claim?.pluginId ?? null
})
}
)
this.app.get(
`${BLE_API_PATH}/consumers`,
async (_req: Request, res: Response) => {
const consumerMap = new Map<string, BLEConsumerInfo>()
for (const pluginId of this.advertisementCallbacks.keys()) {
consumerMap.set(pluginId, {
pluginId,
advertisementSubscriber: true,
gattClaims: []
})
}
for (const [mac, claim] of this.gattClaims) {
let entry = consumerMap.get(claim.pluginId)
if (!entry) {
entry = {
pluginId: claim.pluginId,
advertisementSubscriber: false,
gattClaims: []
}
consumerMap.set(claim.pluginId, entry)
}
entry.gattClaims.push(mac)
}
res.json(Array.from(consumerMap.values()))
}
)
this.app.get(
`${BLE_API_PATH}/settings`,
async (_req: Request, res: Response) => {
res.json(this._buildSettingsResponse())
}
)
this.app.put(
`${BLE_API_PATH}/settings`,
async (req: Request, res: Response) => {
if (!Value.Check(BLESettingsRequestSchema, req.body)) {
const first = Value.Errors(BLESettingsRequestSchema, req.body).First()
res.status(400).json({
message: first
? `Invalid settings at ${first.path}: ${first.message}`
: 'Invalid settings'
})
return
}
const body = req.body
if (
body.localBluetoothManaged === true &&
!this.isLocalBLESupported()
) {
res.status(400).json({
message:
'Local Bluetooth adapter management is only supported on Linux.'
})
return
}
// Apply to a candidate first: in-memory settings only change
// after the write to disk has succeeded
const candidate: BLESettings = { ...this.settings }
let changed = false
let providerChange = false
if (typeof body.localBluetoothManaged === 'boolean') {
candidate.localBluetoothManaged = body.localBluetoothManaged
changed = true
providerChange = true
}
if (Array.isArray(body.localAdapters)) {
candidate.localAdapters = body.localAdapters
changed = true
providerChange = true
}
if (typeof body.localMaxGATTSlots === 'number') {
candidate.localMaxGATTSlots = body.localMaxGATTSlots
changed = true
providerChange = true
}
if (changed) {
const candidateSettings = structuredClone(
this.app.config.settings
) as any
candidateSettings.bleApi = { ...candidate }
try {
await new Promise<void>((resolve, reject) => {
writeSettingsFile(
this.app as any,
candidateSettings,
(err: any) => (err ? reject(err) : resolve())
)
})
} catch (err: any) {
debug.enabled && debug(`Error saving BLE settings: ${err.message}`)
res
.status(500)
.json({ message: `Failed to save settings: ${err.message}` })
return
}
this.settings = candidate
;(this.app.config.settings as any).bleApi = { ...candidate }
if (providerChange) {
await this.shutdownLocalProviders()
if (this.settings.localBluetoothManaged) {
await this.initLocalProviders()
}
}
}
res.json(this._buildSettingsResponse())
}
)
}
// -------------------------------------------------------------------
// WebSocket endpoint for advertisement streaming
// -------------------------------------------------------------------
private initWebSocketEndpoint() {
const wsPath = `${BLE_API_PATH}/advertisements`
const wss = new WebSocket.Server({ noServer: true })
wss.on('connection', (ws: WebSocket) => {
debug('WebSocket client connected for BLE advertisements')
this.wsClients.add(ws)
ws.on('close', () => {
this.wsClients.delete(ws)
debug('WebSocket client disconnected')
})
ws.on('error', () => {
this.wsClients.delete(ws)
})
})