Skip to content

All your computers and your phone/iPhone, working as one desk. Screens, apps, files, clipboard, calls, texts, notifications, mouse and keyboard, shared between Mac, Windows, Linux , Android, Web and ios / ipados . Free and open source. No account, no cloud, and no shared network needed.

iPhone: advertises over Bluetooth for a computer that can't, which links to it

Inuka Asithe5a8a39cf934
diff --git a/ios/TwinDesk/Core/Ble.swift b/ios/TwinDesk/Core/Ble.swift
index 43e53692..768ecc37 100644
--- a/ios/TwinDesk/Core/Ble.swift
+++ b/ios/TwinDesk/Core/Ble.swift
@@ -43,7 +43,30 @@ final class Ble: Feature, CBCentralManagerDelegate, CBPeripheralDelegate {
private var tried: [UUID: Date] = [:] // unpaired ones read lately: not again for a while
private(set) var radio = "off" // main: on, off, unauthorized, unsupported
private(set) var near: [String: String] = [:] // main: host id -> name, linked and paired
- private(set) var unpaired: [String: String] = [:] // main: host id -> name, linked, not paired (Pair over Bluetooth)
+ private(set) var unpairedLinked: [String: String] = [:] // main: host id -> name, linked, not paired (Pair over Bluetooth)
+ // main: …and the ones linked to us (BleServe), for a computer that can't advertise
+ var unpaired: [String: String] {
+ var m = unpairedLinked
+ for (id, n) in serve.found where Store.shared.host(id) == nil { m[id] = n }
+ return m
+ }
+
+ // We advertise for the computers that can't (BleServe): made only when one needs it.
+ private(set) var serve: BleServe!
+
+ override init(_ core: Core) {
+ super.init(core)
+ serve = BleServe(
+ hello: { [unowned self] in ["id": self.core.store.deviceId, "name": self.core.store.deviceName, "os": Proto.os] },
+ onChange: { [unowned self] in self.core.changed(); self.updateServe() },
+ onOpen: { [unowned self] id, port in self.core.bleServed(id, port) })
+ }
+ // Paired computers that said ble.host {ads: false}: their Bluetooth can't advertise, so we do.
+ private var noAds: Set<String> {
+ get { Set((UserDefaults.standard.array(forKey: "ble.noAds") as? [String]) ?? []) }
+ set { UserDefaults.standard.set(Array(newValue), forKey: "ble.noAds") }
+ }
+ private var serving = false // q: BleServe asked to advertise
private var looking = false // q: Connection is on screen: unpaired computers are kept linked, for Pair
// q: when the scan last (re)started. iOS reports a peripheral once per scan, so one that was read
// and let go (unpaired then, a failed connect) is seen again only after a fresh scan.
@@ -54,7 +77,10 @@ final class Ble: Feature, CBCentralManagerDelegate, CBPeripheralDelegate {
var on: Bool { core.store.flag("ble", true) }
// When bytes last came through a pipe (Link's liveness counts them: a big message takes a while).
- var lastDown: Date { lock.lock(); defer { lock.unlock() }; return downAt }
+ var lastDown: Date {
+ lock.lock(); let d = downAt; lock.unlock()
+ return serving ? max(d, serve.lastRx) : d
+ }
// Peripheral → host id, to reconnect without scanning (retrievePeripherals).
private var known: [String: String] {
@@ -95,6 +121,7 @@ final class Ble: Feature, CBCentralManagerDelegate, CBPeripheralDelegate {
for c in self.conns.values where c.guest && c.sock == nil && c.listener == nil { self.drop(c) }
}
self.scan()
+ self.updateServe() // we advertise too while Connection looks: a computer that can't still finds us
}
}
@@ -105,6 +132,7 @@ final class Ble: Feature, CBCentralManagerDelegate, CBPeripheralDelegate {
for c in self.conns.values { self.closePipe(c, tell: false); cm.cancelPeripheralConnection(c.p) }
self.conns.removeAll()
self.publish()
+ if self.serving { self.serving = false; self.serve.stop() }
}
}
@@ -114,7 +142,37 @@ final class Ble: Feature, CBCentralManagerDelegate, CBPeripheralDelegate {
core.changed()
}
- func has(_ hostId: String) -> Bool { near[hostId] != nil }
+ func has(_ hostId: String) -> Bool { near[hostId] != nil || (serve.has(hostId) && Store.shared.host(hostId) != nil) }
+
+ // We advertise (BleServe) while a paired computer that can't isn't linked the usual way, or while
+ // Connection looks (pairing with nothing but Bluetooth). Off for everything else: nothing changes
+ // with a computer that advertises. On q.
+ private func updateServe() {
+ q.async {
+ let linked = Set(self.conns.values.filter { $0.ready }.map { $0.hostId })
+ let need = self.noAds.filter { Store.shared.host($0) != nil && !linked.contains($0) }
+ let on = self.on && self.cm?.state == .poweredOn && (self.looking || !need.isEmpty)
+ if on == self.serving { return }
+ self.serving = on
+ self.serve.want(on)
+ }
+ }
+
+ // ble.host {ads, ble} from the computer in the session: whether we advertise for it from now on.
+ override func onMessage(_ t: String, _ m: JSON) -> Bool {
+ guard t == Proto.T.bleHost else { return false }
+ DispatchQueue.main.async {
+ guard let id = self.core.link.host?.id, self.core.store.host(id) != nil else { return }
+ var s = self.noAds
+ if m.bool("ble") && !m.bool("ads") { s.insert(id) } else { s.remove(id) }
+ if s != self.noAds {
+ self.noAds = s
+ NSLog("TwinDesk: %@ %@ advertise over Bluetooth", self.core.link.host?.name ?? id, s.contains(id) ? "can't" : "can")
+ }
+ self.updateServe()
+ }
+ return true
+ }
// ---- central ----
@@ -131,10 +189,12 @@ final class Ble: Feature, CBCentralManagerDelegate, CBPeripheralDelegate {
for c in conns.values { closePipe(c, tell: false) }
conns.removeAll()
publish()
+ updateServe()
return
}
relink()
scan()
+ updateServe()
}
// The computers we linked to before: connected again directly (a pending connection never
@@ -317,7 +377,8 @@ final class Ble: Feature, CBCentralManagerDelegate, CBPeripheralDelegate {
for c in conns.values where c.ready { m[c.hostId] = Store.shared.host(c.hostId)?.name ?? "Computer" }
for c in conns.values where c.guest { u[c.hostId] = c.name }
DispatchQueue.main.async {
- if self.near != m || self.unpaired != u { self.near = m; self.unpaired = u; self.core.changed() }
+ if self.near != m || self.unpairedLinked != u { self.near = m; self.unpairedLinked = u; self.core.changed() }
+ self.updateServe()
}
}
@@ -348,7 +409,8 @@ final class Ble: Feature, CBCentralManagerDelegate, CBPeripheralDelegate {
q.async {
guard let c = self.conns.values.first(where: { ($0.ready || $0.guest) && $0.hostId == hostId }) else {
self.scan()
- return DispatchQueue.main.async { done(nil) }
+ // Linked to us instead (a computer that can't advertise): through BleServe, nil if not.
+ return self.serve.open(hostId, done)
}
self.closePipe(c, tell: true)
let params = NWParameters.tcp
@@ -427,6 +489,6 @@ final class Ble: Feature, CBCentralManagerDelegate, CBPeripheralDelegate {
}
func piped(_ hostId: String) -> Bool {
- q.sync { conns.values.contains { $0.hostId == hostId && $0.sock != nil } }
+ q.sync { conns.values.contains { $0.hostId == hostId && $0.sock != nil } } || serve.piped(hostId)
}
}
diff --git a/ios/TwinDesk/Core/BleServe.swift b/ios/TwinDesk/Core/BleServe.swift
new file mode 100644
index 00000000..0c7156f5
--- /dev/null
+++ b/ios/TwinDesk/Core/BleServe.swift
@@ -0,0 +1,351 @@
+// TwinDesk — Copyright (C) 2026 inukaasith. GPL-3.0, see LICENSE.
+// Bluetooth LE the other way round (Android's BleServe.kt, the same protocol): for a computer whose
+// Bluetooth can't advertise (Windows aborts it on some adapters, a Realtek one among them), this
+// iPhone advertises the phone service and serves INFO, CTRL, UP and DOWN; the computer connects to
+// it (shared/blepipe.js BlePhones), says hello on CTRL with its beacon, and a pipe opens when it
+// writes {op: open}: because we asked ({op: want}: Ble.openPipe for a computer only this way) or
+// because it invites us back. The session (TLS, pinned certificate, token) is still ours, through
+// a 127.0.0.1 port here as for Ble.swift's pipes.
+//
+// Only while Ble wants it (Ble.updateServe): a paired computer said ble.host {ads: false} and isn't
+// linked the usual way, or Connection is on screen (pairing with nothing but Bluetooth). A computer
+// that advertises (a Mac) never starts it, so nothing changes there.
+import Foundation
+import CoreBluetooth
+import Network
+
+final class BleServe: NSObject, CBPeripheralManagerDelegate {
+ static let phoneService = CBUUID(string: "B7F30006-2C4E-4D1A-9A57-3E8C2F6D0A91")
+
+ // One computer connected to us (a central), once it subscribed or wrote.
+ private final class Peer {
+ let central: CBCentral
+ var hostId = ""
+ var name = ""
+ var listener: NWListener?
+ var sock: NWConnection?
+ var gen = 0
+ var pending = Data() // UP before the session's socket connected
+ var asked: ((Bool) -> Void)? // our want: waiting for its {op: open}
+ var reading = false
+ init(_ c: CBCentral) { central = c }
+ }
+
+ private let q = DispatchQueue(label: "td.blp")
+ private var pm: CBPeripheralManager?
+ private var ctrl: CBMutableCharacteristic?
+ private var up: CBMutableCharacteristic?
+ private var down: CBMutableCharacteristic?
+ private var added = false
+ private var wanted = false // q: advertising asked for
+ private var peers: [UUID: Peer] = [:] // q
+ // q: what goes out, in order; a pipe's bytes only while that pipe is on (gen).
+ private var notes: [(c: CBMutableCharacteristic, d: Data, to: CBCentral, peer: Peer?, gen: Int)] = []
+ private let lock = NSLock()
+ private var rxAt = Date.distantPast
+
+ private let hello: () -> JSON // {id, name, os}
+ private let onChange: () -> Void
+ // A computer opened a pipe without our asking (its invite): the port the session can connect to.
+ // False: not taken (not paired, busy): the pipe closes.
+ private let onOpen: (String, UInt16) -> Bool
+
+ // main: computers that said hello here: host id -> name
+ private(set) var found: [String: String] = [:]
+
+ init(hello: @escaping () -> JSON, onChange: @escaping () -> Void, onOpen: @escaping (String, UInt16) -> Bool) {
+ self.hello = hello
+ self.onChange = onChange
+ self.onOpen = onOpen
+ super.init()
+ }
+
+ // Bytes from a computer through a pipe count as alive (Link.bleRx).
+ var lastRx: Date { lock.lock(); defer { lock.unlock() }; return rxAt }
+
+ // ---- on or off (Ble.updateServe) ----
+
+ func want(_ on: Bool) {
+ q.async {
+ self.wanted = on
+ if on, self.pm == nil {
+ // Created only now: an iPhone with computers that advertise never makes one.
+ self.pm = CBPeripheralManager(delegate: self, queue: self.q, options: [CBPeripheralManagerOptionShowPowerAlertKey: false])
+ return // peripheralManagerDidUpdateState goes on
+ }
+ self.advertise()
+ }
+ }
+
+ // Bluetooth off for TwinDesk: nothing advertised, every computer let go.
+ func stop() {
+ q.async {
+ self.wanted = false
+ self.pm?.stopAdvertising()
+ for p in self.peers.values { self.closePipe(p, tell: false) }
+ self.peers.removeAll()
+ self.notes.removeAll()
+ self.publish()
+ }
+ }
+
+ func has(_ hostId: String) -> Bool { found[hostId] != nil }
+
+ func piped(_ hostId: String) -> Bool {
+ q.sync { peers.values.contains { $0.hostId == hostId && $0.sock != nil } }
+ }
+
+ private func advertise() {
+ guard let pm = pm, pm.state == .poweredOn, added else { return }
+ if wanted && !pm.isAdvertising {
+ pm.startAdvertising([CBAdvertisementDataServiceUUIDsKey: [Self.phoneService]])
+ } else if !wanted && pm.isAdvertising {
+ pm.stopAdvertising() // the computers already linked stay
+ }
+ }
+
+ // ---- the service ----
+
+ func peripheralManagerDidUpdateState(_ pm: CBPeripheralManager) {
+ guard pm.state == .poweredOn else {
+ for p in peers.values { closePipe(p, tell: false) }
+ peers.removeAll()
+ notes.removeAll()
+ added = false
+ publish()
+ return
+ }
+ if added { return advertise() }
+ let info = CBMutableCharacteristic(type: Ble.infoId, properties: [.read], value: nil, permissions: [.readable])
+ let c = CBMutableCharacteristic(type: Ble.ctrlId, properties: [.write, .notify], value: nil, permissions: [.writeable])
+ let u = CBMutableCharacteristic(type: Ble.upId, properties: [.write, .writeWithoutResponse], value: nil, permissions: [.writeable])
+ let d = CBMutableCharacteristic(type: Ble.downId, properties: [.notify], value: nil, permissions: [])
+ let s = CBMutableService(type: Self.phoneService, primary: true)
+ s.characteristics = [info, c, u, d]
+ ctrl = c; up = u; down = d
+ pm.removeAllServices()
+ pm.add(s)
+ }
+
+ func peripheralManager(_ pm: CBPeripheralManager, didAdd service: CBService, error: Error?) {
+ if let e = error { NSLog("TwinDesk: Bluetooth (we advertise): %@", e.localizedDescription); return }
+ added = true
+ advertise()
+ }
+
+ func peripheralManagerDidStartAdvertising(_ pm: CBPeripheralManager, error: Error?) {
+ if let e = error { NSLog("TwinDesk: advertising over Bluetooth failed: %@", e.localizedDescription) }
+ else { NSLog("TwinDesk: advertising over Bluetooth (the computer can't)") }
+ }
+
+ private func peer(_ c: CBCentral) -> Peer {
+ if let p = peers[c.identifier] { return p }
+ let p = Peer(c)
+ peers[c.identifier] = p
+ return p
+ }
+
+ func peripheralManager(_ pm: CBPeripheralManager, didReceiveRead r: CBATTRequest) {
+ guard r.characteristic.uuid == Ble.infoId else { return pm.respond(to: r, withResult: .readNotPermitted) }
+ let v = (try? JSONSerialization.data(withJSONObject: hello())) ?? Data()
+ guard r.offset <= v.count else { return pm.respond(to: r, withResult: .invalidOffset) }
+ r.value = v.subdata(in: r.offset..<v.count)
+ pm.respond(to: r, withResult: .success)
+ }
+
+ func peripheralManager(_ pm: CBPeripheralManager, didReceiveWrite requests: [CBATTRequest]) {
+ for r in requests {
+ let p = peer(r.central)
+ let v = r.value ?? Data()
+ switch r.characteristic.uuid {
+ case Ble.upId: upBytes(p, v)
+ case Ble.ctrlId: onCtrl(p, v)
+ default: break
+ }
+ }
+ if let first = requests.first { pm.respond(to: first, withResult: .success) }
+ }
+
+ func peripheralManager(_ pm: CBPeripheralManager, central: CBCentral, didSubscribeTo c: CBCharacteristic) {
+ _ = peer(central)
+ }
+
+ // Its subscription went (it disconnected or let go): that computer is gone.
+ func peripheralManager(_ pm: CBPeripheralManager, central: CBCentral, didUnsubscribeFrom c: CBCharacteristic) {
+ guard c.uuid == Ble.ctrlId || c.uuid == Ble.downId, let p = peers.removeValue(forKey: central.identifier) else { return }
+ closePipe(p, tell: false)
+ p.asked?(false)
+ p.asked = nil
+ notes.removeAll { $0.to.identifier == central.identifier }
+ publish()
+ }
+
+ // ---- CTRL ----
+
+ private func onCtrl(_ p: Peer, _ v: Data) {
+ guard let o = (try? JSONSerialization.jsonObject(with: v)) as? JSON else { return }
+ switch o["op"] as? String {
+ case "hello":
+ let id = o.str("id", max: 64)
+ guard !id.isEmpty else { return }
+ p.hostId = id
+ p.name = o.str("name", max: 100)
+ if p.name.isEmpty { p.name = "Computer" }
+ NSLog("TwinDesk: %@ linked to us over Bluetooth", p.name)
+ publish()
+ case "open":
+ if let a = p.asked { p.asked = nil; return a(true) } // the answer to our want
+ guard !p.hostId.isEmpty else { return note(p, ["op": "closed"]) }
+ let id = p.hostId
+ listen(p) { [weak self] port in
+ guard let self = self else { return }
+ guard let port = port else { return self.q.async { self.closePipe(p, tell: true) } }
+ DispatchQueue.main.async {
+ if !self.onOpen(id, port) { self.q.async { self.closePipe(p, tell: true) } }
+ }
+ }
+ case "close": closePipe(p, tell: false)
+ default: break
+ }
+ }
+
+ private func note(_ p: Peer, _ o: JSON) {
+ guard let c = ctrl, let d = try? JSONSerialization.data(withJSONObject: o) else { return }
+ notes.append((c, d, p.central, nil, 0))
+ flush()
+ }
+
+ // ---- our Pair or Connect: a pipe through a computer linked only this way ----
+
+ // A 127.0.0.1 port whose one connection goes to that computer (nil: none linked, or it didn't open).
+ func open(_ hostId: String, _ done: @escaping (UInt16?) -> Void) {
+ q.async {
+ guard let p = self.peers.values.first(where: { $0.hostId == hostId }) else { return DispatchQueue.main.async { done(nil) } }
+ self.closePipe(p, tell: false)
+ var finished = false
+ let finish = { (port: UInt16?) in
+ if finished { return }
+ finished = true
+ DispatchQueue.main.async { done(port) }
+ }
+ p.asked = { [weak self] ok in
+ guard let self = self else { return }
+ guard ok else { return finish(nil) }
+ self.listen(p) { port in finish(port) }
+ }
+ self.note(p, ["op": "want"])
+ self.q.asyncAfter(deadline: .now() + 15) {
+ if p.asked != nil { p.asked = nil; finish(nil) }
+ }
+ }
+ }
+
+ // The session's socket connects here; its bytes go DOWN, UP's come back to it. done: the port (q).
+ private func listen(_ p: Peer, _ done: @escaping (UInt16?) -> Void) {
+ closePipe(p, tell: false)
+ let params = NWParameters.tcp
+ params.requiredLocalEndpoint = .hostPort(host: "127.0.0.1", port: .any)
+ guard let l = try? NWListener(using: params) else { return done(nil) }
+ p.listener = l
+ var answered = false
+ l.stateUpdateHandler = { st in
+ switch st {
+ case .ready: if !answered { answered = true; done(l.port?.rawValue) }
+ case .failed, .cancelled: if !answered { answered = true; done(nil) }
+ default: break
+ }
+ }
+ l.newConnectionHandler = { [weak self] s in
+ guard let self = self, p.listener === l else { return s.cancel() }
+ l.cancel()
+ p.listener = nil
+ p.gen += 1
+ p.sock = s
+ let gen = p.gen
+ s.stateUpdateHandler = { [weak self] st in
+ switch st {
+ case .failed, .cancelled: self?.q.async { if p.gen == gen { self?.closePipe(p, tell: true) } }
+ default: break
+ }
+ }
+ s.start(queue: self.q)
+ if !p.pending.isEmpty {
+ let d = p.pending
+ p.pending = Data()
+ s.send(content: d, completion: .contentProcessed { _ in })
+ }
+ self.read(p, s, gen)
+ }
+ l.start(queue: q)
+ q.asyncAfter(deadline: .now() + 15) { if p.listener === l { l.cancel(); p.listener = nil } }
+ }
+
+ private func upBytes(_ p: Peer, _ v: Data) {
+ lock.lock(); rxAt = Date(); lock.unlock()
+ guard let s = p.sock else {
+ if p.pending.count < 1 << 20 { p.pending.append(v) }
+ return
+ }
+ s.send(content: v, completion: .contentProcessed { [weak self] e in
+ if e != nil { self?.q.async { self?.closePipe(p, tell: true) } }
+ })
+ }
+
+ // The session's bytes to DOWN, as the link takes them (a few notifications ahead at most).
+ private func read(_ p: Peer, _ s: NWConnection, _ gen: Int) {
+ guard p.sock === s, p.gen == gen, let d = down, !p.reading else { return }
+ if notes.count > 64 { return } // flush reads on once the link took them
+ p.reading = true
+ s.receive(minimumIncompleteLength: 1, maximumLength: 8192) { [weak self] data, _, end, err in
+ guard let self = self else { return }
+ p.reading = false
+ guard p.sock === s, p.gen == gen else { return }
+ if let data = data, !data.isEmpty {
+ let max = Swift.max(20, Swift.min(512, p.central.maximumUpdateValueLength))
+ var i = 0
+ while i < data.count {
+ let n = Swift.min(max, data.count - i)
+ self.notes.append((d, data.subdata(in: (data.startIndex + i)..<(data.startIndex + i + n)), p.central, p, gen))
+ i += n
+ }
+ self.flush()
+ }
+ if end || err != nil { return self.closePipe(p, tell: true) }
+ self.read(p, s, gen)
+ }
+ }
+
+ // Notifications in order; when iOS's queue is full, the rest wait for peripheralManagerIsReady.
+ private func flush() {
+ guard let pm = pm else { return }
+ while let n = notes.first {
+ if let peer = n.peer, peer.gen != n.gen { notes.removeFirst(); continue } // that pipe is over
+ if !pm.updateValue(n.d, for: n.c, onSubscribedCentrals: [n.to]) { return }
+ notes.removeFirst()
+ }
+ // Drained: the pipes that stopped reading for it read on.
+ for p in peers.values { if let s = p.sock { read(p, s, p.gen) } }
+ }
+
+ func peripheralManagerIsReady(toUpdateSubscribers pm: CBPeripheralManager) { flush() }
+
+ private func closePipe(_ p: Peer, tell: Bool) {
+ p.listener?.cancel()
+ p.listener = nil
+ p.pending = Data()
+ guard let s = p.sock else { return }
+ p.sock = nil
+ p.gen += 1
+ s.cancel()
+ NSLog("TwinDesk: Bluetooth pipe (we advertise) closed%@", tell ? "" : " by the computer")
+ if tell { note(p, ["op": "closed"]) }
+ }
+
+ private func publish() {
+ var m: [String: String] = [:]
+ for p in peers.values where !p.hostId.isEmpty { m[p.hostId] = p.name }
+ DispatchQueue.main.async {
+ if self.found != m { self.found = m; self.onChange() }
+ }
+ }
+}
diff --git a/ios/TwinDesk/Core/Core.swift b/ios/TwinDesk/Core/Core.swift
index a69e49b4..2e804897 100644
--- a/ios/TwinDesk/Core/Core.swift
+++ b/ios/TwinDesk/Core/Core.swift
@@ -228,6 +228,22 @@ final class Core: ObservableObject, LinkEvents {
// The computer asked over Bluetooth (its invite on CTRL, which also wakes the app): back on it
// unless we left it on purpose or are with another.
+ // A computer that can't advertise opened a pipe to us (BleServe: its invite, as bleInvite for one
+ // that can): the session through it, with the same guards. False: not taken, the pipe closes.
+ func bleServed(_ id: String, _ port: UInt16) -> Bool {
+ guard let h = store.host(id), link.pair == nil, !peer.connected,
+ store.lastHostId == id || store.lastHostId == nil && store.flag("autoConnect", true) else { return false }
+ if link.host?.id == id && (link.state == "connected" || link.state == "connecting") { return false }
+ if link.connected { return false }
+ resumeUntil = .distantPast
+ var b = h
+ b.address = "127.0.0.1"
+ b.port = port
+ NSLog("TwinDesk: session through Bluetooth (%@ linked to us)", h.name)
+ link.connect(b, force: true, ble: true)
+ return true
+ }
+
func bleInvite(_ id: String) {
guard let h = store.host(id), link.pair == nil, store.lastHostId == id || store.lastHostId == nil && store.flag("autoConnect", true) else { return }
if link.host?.id == id && (link.state == "connected" || link.state == "connecting") { return }
diff --git a/ios/TwinDesk/Core/Proto.swift b/ios/TwinDesk/Core/Proto.swift
index 46342fd2..5e26b27c 100644
--- a/ios/TwinDesk/Core/Proto.swift
+++ b/ios/TwinDesk/Core/Proto.swift
@@ -38,6 +38,7 @@ enum Proto {
static let pairOk = "pair.ok"
static let pairCancel = "pair.cancel"
static let hello = "hello"
+ static let bleHost = "ble.host" // computer->us {ads, ble}: ads false: its Bluetooth can't advertise, we do (BleServe)
static let welcome = "welcome"
static let error = "error"
static let ping = "ping"
diff --git a/ios/TwinDesk/Info.plist b/ios/TwinDesk/Info.plist
index f613c219..95f9570d 100644
--- a/ios/TwinDesk/Info.plist
+++ b/ios/TwinDesk/Info.plist
@@ -94,6 +94,7 @@
<string>location</string>
<string>fetch</string>
<string>bluetooth-central</string>
+ <string>bluetooth-peripheral</string>
</array>
<key>UILaunchScreen</key>
<dict>
diff --git a/shared/blepipe.js b/shared/blepipe.js
index 7fad3bb6..9a87d0e5 100644
--- a/shared/blepipe.js
+++ b/shared/blepipe.js
@@ -529,7 +529,7 @@ class BlePhones extends EventEmitter {
}
list() {
- return [...this.found.values()].map(({ id, name, dev }) => ({ id, name, os: P.OS.ANDROID, address: `ble:${dev}`, port: 0, fp: '', ble: true }));
+ return [...this.found.values()].map(({ id, name, dev, os }) => ({ id, name, os: os || P.OS.ANDROID, address: `ble:${dev}`, port: 0, fp: '', ble: true }));
}
// Pair or Connect here: a pipe to the phone (it pairs or connects through it, as for an invite).
@@ -544,6 +544,12 @@ class BlePhones extends EventEmitter {
return true;
}
+ // That phone is linked now (its pipe may be closed).
+ linked(id) {
+ const f = this.found.get(id);
+ return !!f && this.links.get(f.dev) === 'up';
+ }
+
_link(dev, force) {
if (this.links.has(dev) || (!force && Date.now() - (this.tried.get(dev) || 0) < 15000)) return;
this.tried.set(dev, Date.now());
@@ -566,7 +572,8 @@ class BlePhones extends EventEmitter {
if (!info || typeof info.id !== 'string' || !info.id) return;
const old = this.found.get(info.id);
if (old && old.dev !== dev) this._drop(old.dev); // a new address (Android changes it now and then)
- this.found.set(info.id, { dev, id: info.id.slice(0, 64), name: str(info.name, 64) || 'Phone', lastSeen: Date.now() });
+ // os: an iPhone or iPad that advertises (its BleServe.swift, for a computer that can't) says ios
+ this.found.set(info.id, { dev, id: info.id.slice(0, 64), name: str(info.name, 64) || 'Phone', os: info.os === P.OS.IOS ? P.OS.IOS : P.OS.ANDROID, lastSeen: Date.now() });
if (!old || old.dev !== dev || old.name !== info.name) this.emit('change');
if (this.autoLink) this._link(dev, false);
return;
diff --git a/shared/protocol.js b/shared/protocol.js
index 94ff9654..a16defbc 100644
--- a/shared/protocol.js
+++ b/shared/protocol.js
@@ -361,6 +361,11 @@
NET_RELEASE: 'net.release', // either {why}: I don't need it any more; {all: true}: Back to Bluetooth, nobody does
NET_LAN: 'net.lan', // phone->computer {}: its own Wi-Fi network is back while it hosts a link for 'fallback' (General › Network fallback): the link can go
NET_HOTSPOT: 'net.hotspot', // computer->phone {on}: ask the person to switch the phone's hotspot on (the screen through adb)
+ // computer->iPhone or iPad {ads, ble}, as its session starts and when it changes: ads false: this
+ // computer's Bluetooth can't advertise (Windows aborts it on some adapters), so the phone advertises
+ // instead and the computer links to it (shared/blepipe.js BlePhones, ios BleServe.swift); ble: Bluetooth
+ // with phones is on here. Older phones ignore it and keep linking only to a computer that advertises.
+ BLE_HOST: 'ble.host',
// Calls, Messages and Media from a phone (shared/phonehub.js here, Hub.kt on the phone). Each is
// off until switched on (its page here, or the phone's Overview); while one is off the phone
// keeps nothing running for it: no listener, no observer, no query.
diff --git a/windows/main.js b/windows/main.js
index 13a53f3f..8dbff7e2 100644
--- a/windows/main.js
+++ b/windows/main.js
@@ -602,6 +602,9 @@ async function startHost(guest) {
else batteryAlerts.reset();
});
server.on('closed', (ctx) => { if (ctx && P.isPhoneOs(ctx.os)) batteryAlerts.end(ctx); });
+ server.on('client', (ctx) => { if (ctx && ctx.os === P.OS.IOS) { iosCtxs.add(ctx); tellBleHost(ctx); } });
+ server.on('closed', (ctx) => iosCtxs.delete(ctx));
+ pairedIds = () => pairing.list().map((p) => p.id);
server.on(`t:${P.T.PHONE_INFO}`, (msg, ctx) => {
if (liveClient(ctx) && P.isPhoneOs(ctx.os)) batteryAlerts.info(msg, ctx);
});
@@ -618,6 +621,7 @@ async function startHost(guest) {
holdAds: () => iosNow() && !bleHost.list().some((g) => g.id === link.current.deviceId),
});
bleHost.on('change', pushState);
+ bleHost.on('state', () => { for (const c of iosCtxs) tellBleHost(c); }); // advertising came or went: the iPhones know
discovery.extras.unshift(bleHost);
blePhones = new BlePhones({ helper, server, hello: bleHost.info });
blePhones.on('change', pushState);
@@ -1131,14 +1135,27 @@ function setupNet(guest) {
inviteIos();
const near = link.snapshot().link.state !== 'connected' && !link.hosting && !bleOff;
bleGuest.scan(near && settings.net.blePc); // looking for a host only while there's no session
- if (blePhones) blePhones.scan(near && settings.net.ble); // … and for phones
+ // … and for phones; also while an iPhone is here and this computer can't advertise: linked to it now,
+ // the session has Bluetooth to go on with when the iPhone's Wi-Fi goes
+ if (blePhones) blePhones.scan((near || (iosNear() && !bleAds() && !bleOff)) && settings.net.ble);
}, 2000);
}
// An iPhone or iPad as the session (its Bluetooth link is held through quiet: BleHost hold).
-// …or one linked over Bluetooth (BleHost): Bluetooth is never quieted for it (applyQuiet).
-const iosNear = () => iosNow() || (!!bleHost && bleHost.list().some((g) => g.os === P.OS.IOS));
const iosNow = () => !!link.current && link.current.os === P.OS.IOS;
+// …or one linked over Bluetooth, to us or we to it (BlePhones): Bluetooth is never quieted for it (applyQuiet).
+const iosNear = () => iosNow() || (!!bleHost && bleHost.list().some((g) => g.os === P.OS.IOS)) || (!!blePhones && blePhones.list().some((f) => f.os === P.OS.IOS));
+// This computer's Bluetooth advertises (BleHost on): an adapter Windows aborts it on can't (Realtek here).
+const bleAds = () => !!bleHost && bleHost.state === 'on';
+
+// iPhones and iPads in a session here, told whether this computer advertises (ble.host {ads, ble}):
+// while it can't, they advertise instead and BlePhones links to them, also while the session is on Wi-Fi.
+const iosCtxs = new Set();
+let pairedIds = () => [];
+function tellBleHost(ctx) {
+ if (!hostServer || !ctx) return;
+ try { hostServer.send(ctx, { t: P.T.BLE_HOST, ads: bleAds(), ble: !!settings.net.ble }); } catch (_) { /* gone */ }
+}
// No session, and an iPhone or iPad linked over Bluetooth (it links only to computers it's paired
// with): invited now and then, which wakes TwinDesk there to come back (its Ble.swift).
@@ -1150,6 +1167,14 @@ function inviteIos() {
iosInvitedAt = Date.now();
bleHost.invite(g.id);
}
+ // An iPhone that advertises for us (we can't), linked and paired here: a pipe, which wakes it to come back.
+ if (!blePhones || !settings.net.ble) return;
+ const paired = new Set(pairedIds());
+ for (const f of blePhones.list()) {
+ if (f.os !== P.OS.IOS || !paired.has(f.id) || !blePhones.linked(f.id)) continue;
+ iosInvitedAt = Date.now();
+ blePhones.invite(f.id);
+ }
}
// The session on the same Wi-Fi a while (General's Turn off Bluetooth on Wi-Fi connections,
diff --git a/windows/mesh/main.js b/windows/mesh/main.js
index fa4b9206..93167867 100644
--- a/windows/mesh/main.js
+++ b/windows/mesh/main.js
@@ -824,6 +824,9 @@ async function startHost() {
&& P.isPhoneOs(ctx.os) && server.clients.get(ctx.deviceId) === ctx && hub.sessions.get(ctx.deviceId)?.ctx === ctx;
server.on('client', (ctx) => { if (livePhone(ctx)) batteryAlerts.begin(ctx); });
server.on('closed', (ctx) => { if (ctx && P.isPhoneOs(ctx.os)) batteryAlerts.end(ctx); });
+ server.on('client', (ctx) => { if (ctx && ctx.os === P.OS.IOS) { iosCtxs.add(ctx); tellBleHost(ctx); } });
+ server.on('closed', (ctx) => iosCtxs.delete(ctx));
+ pairedIds = () => pairing.list().map((p) => p.id);
server.on(`t:${P.T.PHONE_INFO}`, (msg, ctx) => { if (livePhone(ctx)) batteryAlerts.info(msg, ctx); });
bleHost = new BleHost({
helper, server,
@@ -837,6 +840,7 @@ async function startHost() {
holdAds: () => iosSessions().some((s) => !bleHost.list().some((g) => g.id === s.id)),
});
bleHost.on('change', pushState);
+ bleHost.on('state', () => { for (const c of iosCtxs) tellBleHost(c); }); // advertising came or went: the iPhones know
discovery.extras.unshift(bleHost);
blePhones = new BlePhones({ helper, server, hello: bleHost.info });
blePhones.on('change', pushState);
@@ -1247,15 +1251,28 @@ function setupNet() {
const near = link.snapshot().link.state !== 'connected' && !link.hosting && !bleOff;
// looking for a host only while there's no session, or, with mouse and keyboard over Bluetooth, for the hosts it rides to
bleGuest.scan((near || settings.net.bleInput === true) && settings.net.blePc);
- if (blePhones) blePhones.scan(near && settings.net.ble); // … and for phones
+ // … and for phones; also while an iPhone is here and this computer can't advertise: linked to it now,
+ // the session has Bluetooth to go on with when the iPhone's Wi-Fi goes
+ if (blePhones) blePhones.scan((near || (iosNear() && !bleAds() && !bleOff)) && settings.net.ble);
}, 2000);
}
// iPhones and iPads in a session (their Bluetooth link is held through quiet: BleHost hold).
const iosSessions = () => (hub ? hub.sessions.list().filter((s) => s.connected && s.peerOs === P.OS.IOS) : []);
const iosNow = () => iosSessions().length > 0;
-// …or one linked over Bluetooth (BleHost): Bluetooth is never quieted for it (applyQuiet).
-const iosNear = () => iosNow() || (!!bleHost && bleHost.list().some((g) => g.os === P.OS.IOS));
+// …or one linked over Bluetooth, to us or we to it (BlePhones): Bluetooth is never quieted for it (applyQuiet).
+const iosNear = () => iosNow() || (!!bleHost && bleHost.list().some((g) => g.os === P.OS.IOS)) || (!!blePhones && blePhones.list().some((f) => f.os === P.OS.IOS));
+// This computer's Bluetooth advertises (BleHost on): an adapter Windows aborts it on can't (Realtek here).
+const bleAds = () => !!bleHost && bleHost.state === 'on';
+
+// iPhones and iPads in a session here, told whether this computer advertises (ble.host {ads, ble}):
+// while it can't, they advertise instead and BlePhones links to them, also while their session is on Wi-Fi.
+const iosCtxs = new Set();
+let pairedIds = () => [];
+function tellBleHost(ctx) {
+ if (!hostServer || !ctx) return;
+ try { hostServer.send(ctx, { t: P.T.BLE_HOST, ads: bleAds(), ble: !!settings.net.ble }); } catch (_) { /* gone */ }
+}
// An iPhone or iPad linked over Bluetooth but not in a session (it links only to computers it's
// paired with): invited now and then, which wakes TwinDesk there to come back (its Ble.swift).
@@ -1268,6 +1285,15 @@ function inviteIos() {
iosInvitedAt = Date.now();
bleHost.invite(g.id);
}
+ // An iPhone that advertises for us (we can't), linked and paired here, not in a session: a pipe,
+ // which wakes it to come back.
+ if (!blePhones || !settings.net.ble) return;
+ const paired = new Set(pairedIds());
+ for (const f of blePhones.list()) {
+ if (f.os !== P.OS.IOS || on.has(f.id) || !paired.has(f.id) || !blePhones.linked(f.id)) continue;
+ iosInvitedAt = Date.now();
+ blePhones.invite(f.id);
+ }
}
// Cursor › Mouse and keyboard over Bluetooth (#158): shared/bleinput.js only while it's on, for every
// session: the ones we host (server.js send) and the ones we dialled (links.js; each one near over