thermark 0.36.1

Local sticker printing for pocket thermal printers over BLE/USB — QR links, inventory tags, badges, photos; no vendor app
Documentation
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
use super::*;
use btleplug::api::{
    Central, CentralEvent, Characteristic, Manager as _, Peripheral as _, ScanFilter, WriteType,
};
use btleplug::platform::{Adapter, Manager, Peripheral};
use futures::stream::StreamExt;
use std::collections::HashMap;
use tokio::runtime::RuntimeFlavor;
use tokio::sync::mpsc;
use tokio::time::{Instant, sleep, sleep_until, timeout, timeout_at};
use tracing::{debug, info};
use uuid::Uuid;

/// BLE service / characteristic used by common pocket thermal label printers
/// (community reverse-engineering; same UUIDs as B1-class devices).
pub const PRINTER_SERVICE: Uuid = Uuid::from_u128(0xe7810a71_73ae_499d_8c15_faa9aef0c3f2);
pub const PRINTER_CHAR: Uuid = Uuid::from_u128(0xbef8d6c9_9c21_4c9e_b632_bd58c1009f9f);

pub struct BleTransport {
    peripheral: Peripheral,
    characteristic: Characteristic,
    /// Acknowledged when the characteristic allows it — see
    /// [`choose_write_type`].
    write_type: WriteType,
    rx: mpsc::UnboundedReceiver<Vec<u8>>,
    notify_task: Option<tokio::task::JoinHandle<()>>,
    /// True after explicit or Drop-time teardown (avoids double disconnect).
    closed: bool,
}

/// Owns cleanup from the moment a peripheral connects until the complete
/// transport has been constructed. This also covers future cancellation.
struct BleSetupGuard(Option<Peripheral>);

impl BleSetupGuard {
    fn new(peripheral: &Peripheral) -> Self {
        Self(Some(peripheral.clone()))
    }

    fn disarm(&mut self) {
        self.0 = None;
    }
}

impl Drop for BleSetupGuard {
    fn drop(&mut self) {
        if let Some(peripheral) = self.0.take() {
            disconnect_on_drop(peripheral, "BLE disconnected after incomplete setup");
        }
    }
}

/// A scanned peripheral plus its signal strength.
#[derive(Debug, Clone)]
pub struct BleDeviceInfo {
    pub candidate: BleCandidate,
    pub rssi: Option<i16>,
}

impl BleDeviceInfo {
    pub fn id(&self) -> &str {
        &self.candidate.id
    }

    pub fn display_name(&self) -> &str {
        self.candidate.display_name()
    }
}

/// Exact platform IDs can finish discovery as soon as their advertisement
/// arrives. Names (even exact ones) need the complete scan window so a second
/// printer with the same advertising name still produces an ambiguity error.
fn can_finish_connect_scan(selector: &str, candidate: &BleCandidate, mode: BleMatchMode) -> bool {
    mode == BleMatchMode::Exact && candidate.id.eq_ignore_ascii_case(selector.trim())
}

async fn wait_for_exact_match(
    adapter: &Adapter,
    events: &mut (impl futures::Stream<Item = CentralEvent> + Unpin),
    selector: &str,
    deadline: Instant,
) -> Option<(BleCandidate, Peripheral)> {
    loop {
        if Instant::now() >= deadline {
            return None;
        }
        let event = match timeout_at(deadline, events.next()).await {
            Ok(Some(event)) => event,
            Ok(None) => {
                // Preserve the configured scan deadline if this platform's
                // event stream ends unexpectedly; the catalog fallback below
                // should see the same scan window as the old implementation.
                sleep_until(deadline).await;
                return None;
            }
            Err(_) => return None,
        };
        let (CentralEvent::DeviceDiscovered(id) | CentralEvent::DeviceUpdated(id)) = event else {
            continue;
        };
        let id_only = BleCandidate::new(id.to_string(), None);
        if !can_finish_connect_scan(selector, &id_only, BleMatchMode::Exact) {
            continue;
        }
        let peripheral = match timeout_at(deadline, adapter.peripheral(&id)).await {
            Ok(Ok(peripheral)) => peripheral,
            Ok(Err(error)) => {
                debug!(%error, "BLE discovery event referenced an unavailable peripheral");
                continue;
            }
            Err(_) => return None,
        };

        // Only an exact platform id may exit early. Returning the first exact
        // name would bypass the catalog's duplicate-name ambiguity check.
        return Some((id_only, peripheral));
    }
}

impl BleTransport {
    /// Scan for B1-class label-printer peripherals.
    ///
    /// Devices advertising the printer GATT service are included even when
    /// their name is unrecognized, so an unknown model is still findable.
    pub async fn scan(duration: Duration) -> Result<Vec<BleDeviceInfo>> {
        let adapter = default_adapter().await?;
        adapter
            .start_scan(ScanFilter::default())
            .await
            .map_err(|e| Error::transport(format!("BLE start_scan: {e}")))?;
        sleep(duration).await;
        let peris = adapter
            .peripherals()
            .await
            .map_err(|e| Error::transport(format!("BLE peripherals: {e}")))?;
        let mut found: HashMap<String, BleDeviceInfo> = HashMap::new();
        for p in peris {
            let Some(props) = p
                .properties()
                .await
                .map_err(|e| Error::transport(format!("BLE properties: {e}")))?
            else {
                continue;
            };
            let candidate = BleCandidate::new(p.id().to_string(), props.local_name);
            let interesting =
                candidate.looks_like_label_printer() || props.services.contains(&PRINTER_SERVICE);
            if interesting {
                found.insert(
                    candidate.id.clone(),
                    BleDeviceInfo {
                        candidate,
                        rssi: props.rssi,
                    },
                );
            }
        }
        adapter.stop_scan().await.ok();
        let mut list: Vec<_> = found.into_values().collect();
        list.sort_by(|a, b| a.display_name().cmp(b.display_name()));
        Ok(list)
    }

    /// Connect with exact name or id match (safe default).
    pub async fn connect(selector: &str, scan_for: Duration) -> Result<Self> {
        Self::connect_with(selector, scan_for, BleMatchMode::Exact).await
    }

    /// Connect using [`BleMatchMode`] (`Exact` default, or `Fuzzy` substring).
    pub async fn connect_with(
        selector: &str,
        scan_for: Duration,
        mode: BleMatchMode,
    ) -> Result<Self> {
        let adapter = default_adapter().await?;
        let mut events = if mode == BleMatchMode::Exact {
            match adapter.events().await {
                Ok(events) => Some(events),
                Err(error) => {
                    debug!(%error, "BLE event stream unavailable; using full scan window");
                    None
                }
            }
        } else {
            None
        };
        adapter
            .start_scan(ScanFilter::default())
            .await
            .map_err(|e| Error::transport(format!("BLE start_scan: {e}")))?;
        let deadline = Instant::now() + scan_for;
        let early_match = match events.as_mut() {
            Some(events) => wait_for_exact_match(&adapter, events, selector, deadline).await,
            None => {
                sleep_until(deadline).await;
                None
            }
        };
        adapter.stop_scan().await.ok();

        let (winner, peripheral) = if let Some(found) = early_match {
            found
        } else {
            let peris = adapter
                .peripherals()
                .await
                .map_err(|e| Error::transport(format!("BLE peripherals: {e}")))?;

            let mut catalog: Vec<(BleCandidate, Peripheral)> = Vec::new();
            for p in peris {
                let props = p
                    .properties()
                    .await
                    .map_err(|e| Error::transport(format!("BLE properties: {e}")))?;
                let name = props.as_ref().and_then(|pr| pr.local_name.clone());
                catalog.push((BleCandidate::new(p.id().to_string(), name), p));
            }

            let candidates: Vec<BleCandidate> = catalog.iter().map(|(c, _)| c.clone()).collect();
            let has_matching_candidate = candidates
                .iter()
                .any(|candidate| score_ble_candidate(selector, candidate, mode).is_some());
            let winner = match select_ble_candidate(selector, &candidates, mode) {
                Ok(winner) => winner,
                Err(error) if !has_matching_candidate => {
                    #[cfg(all(target_os = "macos", feature = "serial"))]
                    if let Some(path) = super::serial_port_for_selector(selector) {
                        let detail = match error {
                            Error::Transport(message) => message,
                            other => other.to_string(),
                        };
                        return Err(Error::transport(format!(
                            "{detail}. macOS exposes a matching serial endpoint at {path}, which can mean another Bluetooth client already owns the printer session. Disconnect the printer from macOS Bluetooth settings and quit any vendor app, then retry BLE; or explicitly try `--conn usb --addr {path}`."
                        )));
                    }
                    return Err(error);
                }
                Err(error) => return Err(error),
            };

            let peripheral = catalog
                .into_iter()
                .find(|(c, _)| c.id == winner.id)
                .map(|(_, p)| p)
                .ok_or_else(|| Error::transport("internal: matched BLE device vanished"))?;
            (winner, peripheral)
        };

        info!(
            name = %winner.display_name(),
            id = %peripheral.id(),
            ?mode,
            "connecting"
        );

        let mut setup_guard = BleSetupGuard::new(&peripheral);
        with_timeout("BLE connect", Duration::from_secs(15), async {
            peripheral.connect().await.map_err(|e| {
                Error::transport(format!(
                    "BLE connect failed: {e}. \
                 Only one app can use the printer — quit the official label app, \
                 then retry. If it still fails: power-cycle the printer, move closer, \
                 and use the full name from `thermark scan` (exact match by default)."
                ))
            })
        })
        .await?;
        if let Err(e) = with_timeout("BLE discover services", Duration::from_secs(15), async {
            peripheral
                .discover_services()
                .await
                .map_err(|e| Error::transport(e.to_string()))
        })
        .await
        {
            let error = Error::transport(format!(
                "discover services failed: {e}. Wrong device or incomplete BLE connection — \
                 run `thermark scan` and pass -a with the full advertising name."
            ));
            return Err(error);
        }

        let characteristic = match find_printer_char(&peripheral) {
            Ok(characteristic) => characteristic,
            Err(error) => return Err(error),
        };

        let (tx, rx) = mpsc::unbounded_channel::<Vec<u8>>();
        if let Err(e) = with_timeout("BLE subscribe", IO_TIMEOUT, async {
            peripheral
                .subscribe(&characteristic)
                .await
                .map_err(|e| Error::transport(e.to_string()))
        })
        .await
        {
            return Err(Error::transport(format!("subscribe: {e}")));
        }

        let mut notif = match with_timeout("BLE notifications", IO_TIMEOUT, async {
            peripheral
                .notifications()
                .await
                .map_err(|e| Error::transport(e.to_string()))
        })
        .await
        {
            Ok(notifications) => notifications,
            Err(e) => return Err(Error::transport(format!("notifications stream: {e}"))),
        };
        let notify_task = tokio::spawn(async move {
            while let Some(n) = notif.next().await {
                let _ = tx.send(n.value);
            }
        });

        let transport = Self {
            peripheral,
            write_type: choose_write_type(&characteristic),
            characteristic,
            rx,
            notify_task: Some(notify_task),
            closed: false,
        };
        setup_guard.disarm();
        sleep(Duration::from_millis(200)).await;
        Ok(transport)
    }

    async fn close_inner(&mut self) -> Result<()> {
        if self.closed {
            return Ok(());
        }
        if let Some(task) = self.notify_task.take() {
            task.abort();
        }
        with_timeout("BLE disconnect", IO_TIMEOUT, async {
            self.peripheral
                .disconnect()
                .await
                .map_err(|e| Error::transport(format!("BLE disconnect: {e}")))
        })
        .await?;
        self.closed = true;
        debug!("BLE disconnected");
        Ok(())
    }
}

impl Drop for BleTransport {
    /// Backstop teardown for paths that skip [`Transport::close`]
    /// — a mid-job error, or the whole future being dropped on Ctrl-C.
    ///
    /// This *blocks* on a multi-threaded runtime rather than spawning a
    /// detached task. A detached task is not guaranteed to run at all: the
    /// common case is `main` returning right after an error, which shuts
    /// the runtime down before the task is ever polled, leaving the printer
    /// connected and holding the single-client BLE lock.
    fn drop(&mut self) {
        if self.closed {
            return;
        }
        self.closed = true;
        if let Some(task) = self.notify_task.take() {
            task.abort();
        }

        disconnect_on_drop(self.peripheral.clone(), "BLE disconnected on drop");
    }
}

impl Transport for BleTransport {
    async fn send_raw(&mut self, data: &[u8]) -> Result<()> {
        const CHUNK: usize = 180;
        with_timeout("BLE write", IO_TIMEOUT, async {
            for chunk in data.chunks(CHUNK) {
                self.peripheral
                    .write(&self.characteristic, chunk, self.write_type)
                    .await
                    .map_err(|e| Error::transport(format!("BLE write: {e}")))?;
                sleep(Duration::from_millis(5)).await;
            }
            Ok(())
        })
        .await
    }

    async fn recv_raw(&mut self, wait: Duration) -> Result<Vec<u8>> {
        if let Ok(first) = self.rx.try_recv() {
            let mut bytes = first;
            while let Ok(chunk) = self.rx.try_recv() {
                bytes.extend_from_slice(&chunk);
            }
            debug!(bytes = %hex::encode(&bytes), "RX bytes");
            return Ok(bytes);
        }
        match timeout(wait, self.rx.recv()).await {
            Ok(Some(chunk)) => {
                let mut bytes = chunk;
                while let Ok(chunk) = self.rx.try_recv() {
                    bytes.extend_from_slice(&chunk);
                }
                debug!(bytes = %hex::encode(&bytes), "RX bytes");
                Ok(bytes)
            }
            Ok(None) => Err(Error::transport("BLE notification channel closed")),
            Err(_) => Ok(Vec::new()),
        }
    }

    async fn close(&mut self) -> Result<()> {
        self.close_inner().await
    }
}

/// Write type for row data.
///
/// Unacknowledged, with a fixed inter-packet delay — what this protocol
/// expects for row streaming. Acknowledged writes were tried against a real
/// B1 and made no difference to the truncation being investigated, so the
/// deviation was not worth keeping.
fn choose_write_type(_characteristic: &Characteristic) -> WriteType {
    WriteType::WithoutResponse
}

fn disconnect_on_drop(peripheral: Peripheral, success_message: &'static str) {
    let Ok(handle) = tokio::runtime::Handle::try_current() else {
        debug!("BLE connection dropped outside a runtime");
        return;
    };
    match handle.runtime_flavor() {
        RuntimeFlavor::MultiThread => {
            tokio::task::block_in_place(|| {
                handle.block_on(async {
                    match with_timeout("BLE disconnect on drop", IO_TIMEOUT, async {
                        peripheral
                            .disconnect()
                            .await
                            .map_err(|e| Error::transport(e.to_string()))
                    })
                    .await
                    {
                        Ok(()) => debug!("{success_message}"),
                        Err(e) => debug!(error = %e, "BLE disconnect on drop (ignored)"),
                    }
                });
            });
        }
        _ => {
            handle.spawn(async move {
                let _ = with_timeout("BLE disconnect on drop", IO_TIMEOUT, async {
                    peripheral
                        .disconnect()
                        .await
                        .map_err(|e| Error::transport(e.to_string()))
                })
                .await;
            });
        }
    }
}

async fn default_adapter() -> Result<Adapter> {
    let manager = Manager::new()
        .await
        .map_err(|e| Error::transport(format!("btleplug Manager: {e}")))?;
    let adapters = manager
        .adapters()
        .await
        .map_err(|e| Error::transport(format!("list adapters: {e}")))?;
    adapters
        .into_iter()
        .next()
        .ok_or_else(|| Error::transport("no Bluetooth adapter found — is Bluetooth enabled?"))
}

/// True if a host Bluetooth adapter is available (does not require a printer).
pub async fn bluetooth_available() -> Result<String> {
    let adapter = default_adapter().await?;
    let name = adapter
        .adapter_info()
        .await
        .unwrap_or_else(|_| "Bluetooth adapter".into());
    Ok(name)
}

fn find_printer_char(peripheral: &Peripheral) -> Result<Characteristic> {
    let chars = peripheral.characteristics();

    if let Some(c) = chars.iter().find(|c| c.uuid == PRINTER_CHAR) {
        return Ok(c.clone());
    }

    Err(Error::transport(format!(
        "printer characteristic {PRINTER_CHAR} not found (wrong device?). \
         Discovered characteristics:\n{}",
        chars
            .iter()
            .map(|c| format!("  {} props={:?}", c.uuid, c.properties))
            .collect::<Vec<_>>()
            .join("\n")
    )))
}

#[cfg(test)]
mod discovery_tests {
    use super::*;

    #[test]
    fn only_an_exact_id_can_finish_connect_scan() {
        let candidate = BleCandidate::new("A1B2-C3D4", Some("B1-Kitchen".into()));
        assert!(!can_finish_connect_scan(
            "b1-kitchen",
            &candidate,
            BleMatchMode::Exact
        ));
        assert!(can_finish_connect_scan(
            "a1b2-c3d4",
            &candidate,
            BleMatchMode::Exact
        ));
        assert!(!can_finish_connect_scan(
            "B1-Kit",
            &candidate,
            BleMatchMode::Exact
        ));
    }

    #[test]
    fn fuzzy_match_always_uses_the_complete_scan_window() {
        let candidate = BleCandidate::new("A1B2-C3D4", Some("B1-Kitchen".into()));
        assert!(!can_finish_connect_scan(
            "Kitchen",
            &candidate,
            BleMatchMode::Fuzzy
        ));
        assert!(!can_finish_connect_scan(
            "B1-Kitchen",
            &candidate,
            BleMatchMode::Fuzzy
        ));
    }
}