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
//! Async client for the Lager box HTTP API (feature `async`).
//!
//! Runs the exact same request builders and response parsers as the
//! blocking client — only the transport differs.
use std::time::Duration;
use serde_json::Value;
use crate::auth::{self, GatewayAuth};
use crate::error::{Error, Result};
use crate::nets::adc::AsyncAdc;
use crate::nets::arm::AsyncArm;
use crate::nets::battery::AsyncBattery;
use crate::nets::ble::AsyncBle;
use crate::nets::blufi::AsyncBlufi;
use crate::nets::custom::AsyncCustomNet;
use crate::nets::dac::AsyncDac;
use crate::nets::debug::AsyncDebugNet;
use crate::nets::dfu::AsyncDfu;
use crate::nets::eload::AsyncEload;
use crate::nets::energy::AsyncEnergyAnalyzer;
use crate::nets::gpio::AsyncGpio;
use crate::nets::hsm::AsyncHsm;
use crate::nets::i2c::AsyncI2c;
use crate::nets::router::AsyncRouter;
use crate::nets::scope::AsyncScope;
use crate::nets::solar::AsyncSolar;
use crate::nets::spi::AsyncSpi;
use crate::nets::supply::AsyncSupply;
use crate::nets::thermocouple::AsyncThermocouple;
use crate::nets::usb::AsyncUsbPort;
use crate::nets::watt::AsyncWattMeter;
use crate::nets::webcam::AsyncWebcam;
use crate::nets::wifi::AsyncWifi;
use crate::wire::{
self, BoxLock, BoxStatus, Health, HttpRequest, Method, NetRecord, NetState, Op, SafetyLimits,
Timeout, UsbDeviceFilter, UsbDeviceInfo,
};
/// A connection to one Lager box, over async HTTP (reqwest/tokio).
///
/// ```no_run
/// use lager::AsyncLagerBox;
///
/// #[tokio::main]
/// async fn main() -> lager::Result<()> {
/// let lager = AsyncLagerBox::connect("192.168.1.42")?;
/// let supply = lager.supply("supply1");
/// supply.set_voltage(3.3).await?;
/// supply.enable().await?;
/// let v = lager.adc("vbat_sense").read().await?;
/// assert!((v - 3.3).abs() < 0.1);
/// supply.disable().await
/// }
/// ```
pub struct AsyncLagerBox {
base: String,
debug_base: String,
http: reqwest::Client,
default_timeout: Duration,
auth: GatewayAuth,
}
/// Builder for [`AsyncLagerBox`], for overriding the default timeout, the
/// debug-service URL, and gateway auth.
pub struct AsyncLagerBoxBuilder {
host: String,
debug_url: Option<String>,
default_timeout: Duration,
bearer_token: Option<String>,
}
impl AsyncLagerBoxBuilder {
/// Override the default HTTP timeout for quick commands (10s unless
/// changed). Long-running actions still compute their own wider budgets.
pub fn timeout(mut self, timeout: Duration) -> Self {
self.default_timeout = timeout;
self
}
/// Override the debug-service base URL (default: the box host on port
/// 8765). Also settable via `LAGER_DEBUG_SERVICE_URL`.
pub fn debug_service_url(mut self, url: impl Into<String>) -> Self {
self.debug_url = Some(url.into());
self
}
/// Attach `Authorization: Bearer <token>` to every request, for boxes
/// behind an authenticating gateway. Also settable via the
/// `LAGER_GATEWAY_TOKEN` environment variable.
///
/// Without this, the crate reuses the Lager CLI's session
/// (`lager login <auth_url>`, stored in `~/.lager_gateway_auth`)
/// automatically when a gateway asks for auth, including transparent
/// refresh of expired access tokens. Plain (ungated) boxes are
/// unaffected either way.
pub fn bearer_token(mut self, token: impl Into<String>) -> Self {
self.bearer_token = Some(token.into());
self
}
/// Build the client.
pub fn build(self) -> Result<AsyncLagerBox> {
let base = wire::base_url(&self.host)?;
let debug_base = match self.debug_url {
Some(url) => wire::base_url_with_port(&url, wire::DEBUG_SERVICE_PORT)?,
None => wire::service_base(&base, wire::DEBUG_SERVICE_PORT),
};
let auth = GatewayAuth::new(&base, self.bearer_token);
Ok(AsyncLagerBox {
base,
debug_base,
http: reqwest::Client::new(),
default_timeout: self.default_timeout,
auth,
})
}
}
impl AsyncLagerBox {
/// Connect to a box by host name, IP, `host:port`, or full URL.
/// The port defaults to 9000 (the box HTTP server).
pub fn connect(host: impl Into<String>) -> Result<Self> {
Self::builder(host).build()
}
/// Connect to the box named by the `LAGER_BOX_HOST` environment
/// variable.
pub fn from_env() -> Result<Self> {
let host = std::env::var(crate::BOX_HOST_ENV)
.map_err(|_| Error::Config(format!("{} is not set", crate::BOX_HOST_ENV)))?;
Self::connect(host)
}
/// Start building a client with non-default settings.
pub fn builder(host: impl Into<String>) -> AsyncLagerBoxBuilder {
AsyncLagerBoxBuilder {
host: host.into(),
debug_url: std::env::var(crate::DEBUG_SERVICE_URL_ENV).ok(),
default_timeout: wire::DEFAULT_TIMEOUT,
bearer_token: None,
}
}
/// The base URL this client talks to, e.g. `http://192.168.1.42:9000`.
pub fn base_url(&self) -> &str {
&self.base
}
// -- raw access --------------------------------------------------------
/// Async twin of [`LagerBox::debug_tunnel`](crate::LagerBox::debug_tunnel):
/// a TCP stream to one of the box's debug ports, tunnelled through the
/// box's gateway when it has one and connected directly on a plain box.
///
/// ```no_run
/// # async fn demo() -> lager::Result<()> {
/// let lager_box = lager::AsyncLagerBox::connect("192.168.1.42")?;
/// lager_box.debug("debug1").connect().await?;
/// let stream = lager_box.debug_tunnel(2331).await?;
/// # drop(stream);
/// # Ok(())
/// # }
/// ```
pub async fn debug_tunnel(&self, port: u16) -> Result<tokio::net::TcpStream> {
use crate::tunnel::{self as tun, Refusal};
// Wait out a 502 from a server that is still opening its port; see
// the blocking client. No other refusal is retried.
let deadline = std::time::Instant::now() + tun::NOTHING_LISTENING_WAIT;
let refusal = loop {
match self.tunnel_authorized(port).await? {
Ok(stream) => return Ok(stream),
Err(Refusal::NothingListening { .. })
if std::time::Instant::now() + tun::NOTHING_LISTENING_RETRY <= deadline =>
{
tokio::time::sleep(tun::NOTHING_LISTENING_RETRY).await;
}
Err(refusal) => break refusal,
}
};
match refusal {
Refusal::Unsupported { .. } => self.debug_port_direct(port, &refusal).await,
other => Err(tun::refusal_error(&other, self.auth.box_host(), port)),
}
}
/// One `CONNECT` with the single refresh-and-retry after a 401; see
/// the blocking client's `tunnel_authorized`.
async fn tunnel_authorized(
&self,
port: u16,
) -> Result<std::result::Result<tokio::net::TcpStream, crate::tunnel::Refusal>> {
use crate::tunnel::Refusal;
let token = self.current_token().await;
let (status, auth_url) = match self.tunnel_once(port, token.as_deref()).await? {
Err(Refusal::Denied { status, auth_url }) => (status, auth_url),
other => return Ok(other),
};
self.auth.learn_auth_server(&auth_url);
let fresh = if status == 401 && !self.auth.has_static_token() {
self.auth
.resolve_token_async(&auth_url, token.as_deref())
.await
} else {
None
};
let Some(fresh) = fresh else {
return Err(auth::denial_error(
status,
self.auth.box_host(),
&auth_url,
token.is_some(),
));
};
match self.tunnel_once(port, Some(&fresh)).await? {
Err(Refusal::Denied { status, auth_url }) => Err(auth::denial_error(
status,
self.auth.box_host(),
&auth_url,
true,
)),
other => Ok(other),
}
}
/// Async twin of [`LagerBox::bearer_token`](crate::LagerBox::bearer_token):
/// the bearer token this client attaches, or `None` for a plain box. An
/// escape hatch for raw HTTP calls the typed API does not cover yet.
pub async fn bearer_token(&self) -> Result<Option<String>> {
if let Some(token) = self.current_token().await {
return Ok(Some(token));
}
if self.auth.auth_url().is_none() {
self.health().await?;
if let Some(token) = self.current_token().await {
return Ok(Some(token));
}
}
match self.auth.auth_url() {
None => Ok(None),
Some(auth_url) => Err(Error::AuthRequired {
box_host: self.auth.box_host().to_string(),
message: format!("box {} requires sign-in", self.auth.box_host()),
auth_url,
}),
}
}
/// One `CONNECT` round trip; see the blocking client's `tunnel_once`.
async fn tunnel_once(
&self,
port: u16,
token: Option<&str>,
) -> Result<std::result::Result<tokio::net::TcpStream, crate::tunnel::Refusal>> {
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use crate::tunnel::{self as tun, Refusal};
let (host, service_port) = tun::host_port(&self.debug_base)?;
let context = format!("debug tunnel via {host}:{service_port}");
let mut stream = connect_tcp(&host, service_port, self.default_timeout).await?;
let handshake = async {
stream
.write_all(&tun::connect_request(port, self.auth.box_host(), token))
.await?;
// One byte at a time, so no tunnel byte past the blank line is
// taken out of the socket.
let mut head = Vec::with_capacity(256);
let mut byte = [0u8; 1];
while !head.ends_with(b"\r\n\r\n") {
if head.len() >= tun::MAX_HEAD_BYTES || stream.read(&mut byte).await? == 0 {
return Ok(None);
}
head.push(byte[0]);
}
let Some(head) = tun::parse_head(&head) else {
return Ok(None);
};
let mut body = vec![0u8; head.content_length.min(tun::MAX_BODY_BYTES)];
let got = if head.status == 200 {
0
} else {
stream.read(&mut body).await.unwrap_or(0)
};
let body = String::from_utf8_lossy(&body[..got]).trim().to_string();
Ok::<_, std::io::Error>(Some((head, body)))
};
let answer = tokio::time::timeout(self.default_timeout, handshake)
.await
.map_err(|_| Error::Timeout(format!("{context}: no answer")))?
.map_err(|e| tun::io_error(&context, e))?;
let Some((head, body)) = answer else {
return Ok(Err(Refusal::Unsupported { status: None }));
};
if head.status == 200 {
stream
.set_nodelay(true)
.map_err(|e| tun::io_error(&context, e))?;
return Ok(Ok(stream));
}
Ok(Err(tun::classify(&head, body)))
}
/// No tunnel: connect to the published port, as on a plain box.
async fn debug_port_direct(
&self,
port: u16,
refusal: &crate::tunnel::Refusal,
) -> Result<tokio::net::TcpStream> {
let host = self.auth.box_host();
match connect_tcp(host, port, self.default_timeout).await {
Ok(stream) => {
let _ = stream.set_nodelay(true);
Ok(stream)
}
// As in the blocking client: a token on the CONNECT (known-gated
// box, or a pinned token) means a gateway was in front.
Err(_) if self.auth.has_static_token() || self.auth.auth_url().is_some() => {
Err(crate::tunnel::refusal_error(refusal, host, port))
}
Err(e) => Err(e),
}
}
// -- transport ---------------------------------------------------------
/// Send one request against the port-9000 server.
pub(crate) async fn execute(&self, req: &HttpRequest) -> Result<(u16, Value)> {
self.execute_at(&self.base, req).await
}
/// Send one request against the debug service (port 8765).
pub(crate) async fn execute_debug(&self, req: &HttpRequest) -> Result<(u16, Value)> {
self.execute_at(&self.debug_base, req).await
}
/// Send one request against an arbitrary base URL. Attaches gateway
/// auth when known, and handles a gateway denial by resolving
/// credentials (CLI session store, with transparent refresh) and
/// retrying once. Mirrors the blocking client exactly.
async fn execute_at(&self, base: &str, req: &HttpRequest) -> Result<(u16, Value)> {
let token = self.current_token().await;
let (status, gateway, resp_body) = self.send_once(base, req, token.as_deref()).await?;
let Some(auth_url) = gateway else {
return Ok((status, resp_body));
};
// Gateway denial: learn the box→auth-server mapping (like the CLI),
// then retry once with a credential the gateway has not just seen.
self.auth.learn_auth_server(&auth_url);
if status == 401 && !self.auth.has_static_token() {
if let Some(fresh) = self
.auth
.resolve_token_async(&auth_url, token.as_deref())
.await
{
let (status, gateway, resp_body) = self.send_once(base, req, Some(&fresh)).await?;
let Some(auth_url) = gateway else {
return Ok((status, resp_body));
};
return Err(auth::denial_error(
status,
self.auth.box_host(),
&auth_url,
true,
));
}
}
Err(auth::denial_error(
status,
self.auth.box_host(),
&auth_url,
token.is_some(),
))
}
/// Token to attach right now: builder/env token, cached session token,
/// or a store lookup when the box is already known to be gated.
async fn current_token(&self) -> Option<String> {
if let Some(token) = self.auth.cached_token() {
return Some(token);
}
if self.auth.wants_store_token() {
let auth_url = self.auth.auth_url()?;
return self.auth.resolve_token_async(&auth_url, None).await;
}
None
}
/// One HTTP round-trip. Returns `(status, gateway_denial_auth_url,
/// body)`; the auth URL is `Some` only for a gateway denial (401/403/
/// 503 carrying the discovery header).
async fn send_once(
&self,
base: &str,
req: &HttpRequest,
token: Option<&str>,
) -> Result<(u16, Option<String>, Value)> {
let url = format!("{}{}", base, req.path);
let mut r = match req.method {
Method::Get => self.http.get(&url),
Method::Post => self.http.post(&url),
Method::Put => self.http.put(&url),
};
match req.timeout {
Timeout::Default => r = r.timeout(self.default_timeout),
Timeout::After(d) => r = r.timeout(d),
Timeout::Unbounded => {}
}
if let Some(token) = token {
r = r.header("Authorization", format!("Bearer {token}"));
}
if let Some(body) = &req.body {
r = r.json(body);
}
let resp = r.send().await.map_err(|e| {
if e.is_timeout() {
Error::Timeout(e.to_string())
} else {
Error::Connection(e.to_string())
}
})?;
let status = resp.status().as_u16();
let gateway = if auth::is_denial(status) {
resp.headers()
.get(auth::DISCOVERY_HEADER)
.and_then(|v| v.to_str().ok())
.map(str::to_string)
} else {
None
};
let body: Value = match resp.json().await {
Ok(body) => body,
Err(e) if e.is_timeout() => return Err(Error::Timeout(e.to_string())),
Err(e) if status < 400 => return Err(Error::Decode(format!("non-JSON response: {e}"))),
// Error responses (incl. gateway denials) may have no JSON body.
Err(_) => Value::Null,
};
Ok((status, gateway, body))
}
/// Execute one typed operation against a command endpoint.
pub(crate) async fn run<T>(&self, op: Op<T>) -> Result<T> {
let (status, body) = self.execute(&op.req).await?;
let resp = wire::parse_command(status, body)?;
(op.parse)(resp)
}
/// Resolve a debug net's full saved record for the debug service.
pub(crate) async fn debug_net_record(&self, name: &str) -> Result<Value> {
let records = self.nets_raw().await?;
crate::nets::debug::find_debug_record(records, name)
}
/// Raw saved-net records (untyped), with the `/nets/list` ->
/// `/uart/nets/list` fallback.
async fn nets_raw(&self) -> Result<Vec<Value>> {
let body = match self.get_json("/nets/list").await {
Ok(body) => body,
Err(primary) => self
.get_json("/uart/nets/list")
.await
.map_err(|_| primary)?,
};
Ok(wire::nets_list_values(body))
}
async fn get_json(&self, path: &str) -> Result<Value> {
let (status, body) = self.execute(&wire::get(path)).await?;
if status != 200 {
return Err(Error::Box {
status,
message: body
.get("error")
.and_then(Value::as_str)
.unwrap_or("request failed")
.to_string(),
});
}
Ok(body)
}
// -- box-level queries --------------------------------------------------
/// List every net configured on the box (full saved records).
///
/// Falls back to the older `/uart/nets/list` shape for box images that
/// predate `/nets/list`, like the Lager CLI does.
pub async fn nets(&self) -> Result<Vec<NetRecord>> {
match self.get_json("/nets/list").await {
Ok(body) => wire::nets_from_body(body),
Err(primary) => match self.get_json("/uart/nets/list").await {
Ok(body) => wire::nets_from_body(body),
Err(_) => Err(primary),
},
}
}
/// Check that the box HTTP server is up.
pub async fn health(&self) -> Result<Health> {
let body = self.get_json("/health").await?;
serde_json::from_value(body).map_err(Into::into)
}
/// Box status: version, configured nets, and endpoint capabilities.
pub async fn status(&self) -> Result<BoxStatus> {
let body = self.get_json("/status").await?;
serde_json::from_value(body).map_err(Into::into)
}
/// Enumerate USB devices on the box's bus from sysfs (lsusb-like).
///
/// A few milliseconds per call with no exclusive device access, so it
/// is safe to poll frequently — e.g. reading the DUT's iSerial to see
/// what it re-enumerated as after a hub power-cycle or DFU detach.
///
/// Requires box software >= 0.33.0; older boxes fail with
/// [`Error::UnsupportedByBox`].
pub async fn usb_devices(&self) -> Result<Vec<UsbDeviceInfo>> {
self.usb_devices_matching(&UsbDeviceFilter::default()).await
}
/// Like [`AsyncLagerBox::usb_devices`], with box-side vid/pid/serial
/// filters.
pub async fn usb_devices_matching(
&self,
filter: &UsbDeviceFilter,
) -> Result<Vec<UsbDeviceInfo>> {
match self.execute(&wire::usb_devices(filter)).await {
Ok((status, body)) => wire::parse_usb_devices(status, body),
Err(e) => Err(wire::map_route_missing(e, wire::usb_devices_unsupported)),
}
}
// -- box lock / reservation ----------------------------------------------
async fn lock_call(&self, req: &HttpRequest) -> Result<BoxLock> {
match self.execute(req).await {
Ok((status, body)) => wire::parse_lock(status, body),
Err(e) => Err(wire::map_route_missing(e, wire::lock_unsupported)),
}
}
/// Current box lock state (`GET /lock`); `locked: false` when free.
pub async fn lock_status(&self) -> Result<BoxLock> {
self.lock_call(&wire::lock_status()).await
}
/// Claim the box for `user` (an eternal `holder_type: "user"` lock,
/// exactly like `lager boxes lock`). Re-acquiring your own lock
/// refreshes it; a box held by someone else fails with
/// [`Error::Box`] (HTTP 409) naming the holder.
pub async fn lock(&self, user: &str) -> Result<BoxLock> {
self.lock_call(&wire::lock_acquire(user, "user", None))
.await
}
/// Claim the box with an explicit holder type and TTL.
/// `ttl_seconds: None` means the lock never auto-expires; with a TTL,
/// keep the lock alive via [`AsyncLagerBox::lock_heartbeat`].
pub async fn lock_with(
&self,
user: &str,
holder_type: &str,
ttl_seconds: Option<u64>,
) -> Result<BoxLock> {
self.lock_call(&wire::lock_acquire(user, holder_type, ttl_seconds))
.await
}
/// Refresh a TTL lock's heartbeat. Fails with [`Error::Box`] when the
/// box is not locked (HTTP 404) or held by someone else (HTTP 403).
pub async fn lock_heartbeat(&self, user: &str) -> Result<BoxLock> {
self.lock_call(&wire::lock_heartbeat(user)).await
}
/// Release `user`'s box lock. Releasing an already-unlocked box
/// succeeds; a box held by someone else fails with [`Error::Box`]
/// (HTTP 403).
pub async fn unlock(&self, user: &str) -> Result<()> {
self.lock_call(&wire::unlock(user, false)).await.map(|_| ())
}
/// Release the box lock even when held by another user
/// (`lager boxes unlock --force`).
pub async fn unlock_force(&self, user: &str) -> Result<()> {
self.lock_call(&wire::unlock(user, true)).await.map(|_| ())
}
// -- per-net safety limits ------------------------------------------------
/// Set the safety limits on a saved net (`PUT /nets/<name>/safety-limits`,
/// box >= 0.35.0). Returns the limits the box applied.
///
/// The PUT **replaces** the net's whole limits record: fields left `None`
/// in `limits` are removed from the net, not preserved. Read the current
/// limits first ([`AsyncLagerBox::safety_limits`]) if you mean to change
/// one ceiling and keep the rest. An all-`None` `limits` clears the
/// record, same as [`AsyncLagerBox::clear_safety_limits`].
///
/// The ceilings are enforced by the box's hardware service, out of reach
/// of test scripts; a setpoint (or inline `ovp=`/`ocp=` trip) above a
/// ceiling is refused before it touches the instrument. Older boxes fail
/// with [`Error::UnsupportedByBox`]; validation refusals (`max_power`,
/// non-positive ceilings) and an unknown net come back as [`Error::Box`].
pub async fn set_safety_limits(
&self,
name: &str,
limits: &SafetyLimits,
) -> Result<Option<SafetyLimits>> {
match self.execute(&wire::safety_limits_set(name, limits)).await {
Ok((status, body)) => wire::parse_safety_limits(status, body),
Err(e) => Err(wire::map_route_missing(e, wire::safety_limits_unsupported)),
}
}
/// Remove a net's safety limits, returning it to unrestricted.
pub async fn clear_safety_limits(&self, name: &str) -> Result<()> {
self.set_safety_limits(name, &SafetyLimits::default())
.await
.map(|_| ())
}
/// Brief live state for every saved net (`GET /nets/state`,
/// box >= 0.34.0): what `lager nets state` shows. One entry per saved
/// net; an instrument that is slow, wedged or absent yields
/// `state: None` with a reason rather than failing the request, so this
/// is safe to call as a bench health check. Older boxes fail with
/// [`Error::UnsupportedByBox`].
pub async fn nets_state(&self) -> Result<Vec<NetState>> {
match self.execute(&wire::nets_state()).await {
Ok((status, body)) => wire::parse_nets_state(status, body),
Err(e) => Err(wire::map_route_missing(e, wire::nets_state_unsupported)),
}
}
/// Read the safety limits configured on a saved net, via `/nets/list`.
/// `Ok(None)` means the net exists and is unrestricted; a missing net is
/// an [`Error::Box`] with status 404.
pub async fn safety_limits(&self, name: &str) -> Result<Option<SafetyLimits>> {
let nets = self.nets().await?;
nets.iter()
.find(|rec| rec.name == name)
.map(|rec| rec.safety_limits)
.ok_or_else(|| Error::Box {
status: 404,
message: format!("no saved net named '{name}' on this box"),
})
}
// -- net handle constructors ---------------------------------------------
/// Handle for a power-supply net.
pub fn supply(&self, name: impl Into<String>) -> AsyncSupply<'_> {
AsyncSupply {
client: self,
name: name.into(),
}
}
/// Handle for a battery-simulator net.
pub fn battery(&self, name: impl Into<String>) -> AsyncBattery<'_> {
AsyncBattery {
client: self,
name: name.into(),
}
}
/// Handle for an electronic-load net.
pub fn eload(&self, name: impl Into<String>) -> AsyncEload<'_> {
AsyncEload {
client: self,
name: name.into(),
}
}
/// Handle for a solar-simulator net (EA PSB photovoltaic mode).
pub fn solar(&self, name: impl Into<String>) -> AsyncSolar<'_> {
AsyncSolar {
client: self,
name: name.into(),
}
}
/// Handle for a GPIO net.
pub fn gpio(&self, name: impl Into<String>) -> AsyncGpio<'_> {
AsyncGpio {
client: self,
name: name.into(),
}
}
/// Handle for an ADC net.
pub fn adc(&self, name: impl Into<String>) -> AsyncAdc<'_> {
AsyncAdc {
client: self,
name: name.into(),
}
}
/// Handle for a DAC net.
pub fn dac(&self, name: impl Into<String>) -> AsyncDac<'_> {
AsyncDac {
client: self,
name: name.into(),
}
}
/// Handle for a thermocouple net.
pub fn thermocouple(&self, name: impl Into<String>) -> AsyncThermocouple<'_> {
AsyncThermocouple {
client: self,
name: name.into(),
}
}
/// Handle for a watt-meter net.
pub fn watt_meter(&self, name: impl Into<String>) -> AsyncWattMeter<'_> {
AsyncWattMeter {
client: self,
name: name.into(),
}
}
/// Handle for an energy-analyzer net.
pub fn energy_analyzer(&self, name: impl Into<String>) -> AsyncEnergyAnalyzer<'_> {
AsyncEnergyAnalyzer {
client: self,
name: name.into(),
}
}
/// Handle for an SPI bus net.
pub fn spi(&self, name: impl Into<String>) -> AsyncSpi<'_> {
AsyncSpi {
client: self,
name: name.into(),
}
}
/// Handle for an I2C bus net.
pub fn i2c(&self, name: impl Into<String>) -> AsyncI2c<'_> {
AsyncI2c {
client: self,
name: name.into(),
}
}
/// Handle for a USB hub port net.
pub fn usb(&self, name: impl Into<String>) -> AsyncUsbPort<'_> {
AsyncUsbPort {
client: self,
name: name.into(),
}
}
/// Handle for a robot-arm net (Rotrics Dexarm).
pub fn arm(&self, name: impl Into<String>) -> AsyncArm<'_> {
AsyncArm {
client: self,
name: name.into(),
}
}
/// Handle for a webcam net (MJPEG streaming).
pub fn webcam(&self, name: impl Into<String>) -> AsyncWebcam<'_> {
AsyncWebcam {
client: self,
name: name.into(),
}
}
/// Handle for a net driven by a custom driver installed on the box
/// (box >= 0.59.0). See [`crate::nets::custom`].
pub fn custom(&self, name: impl Into<String>) -> AsyncCustomNet<'_> {
AsyncCustomNet {
client: self,
name: name.into(),
}
}
/// Handle for a router net (MikroTik RouterOS).
pub fn router(&self, name: impl Into<String>) -> AsyncRouter<'_> {
AsyncRouter {
client: self,
name: name.into(),
}
}
/// Handle for the box's BLE adapter (box-level, not a saved net).
pub fn ble(&self) -> AsyncBle<'_> {
AsyncBle { client: self }
}
/// Handle for the box's WiFi interface (box-level, not a saved net).
pub fn wifi(&self) -> AsyncWifi<'_> {
AsyncWifi { client: self }
}
/// Handle for BluFi (ESP32 WiFi provisioning over BLE; box-level).
pub fn blufi(&self) -> AsyncBlufi<'_> {
AsyncBlufi { client: self }
}
/// Handle for box-side DFU via dfu-util (box-level, not a saved net).
pub fn dfu(&self) -> AsyncDfu<'_> {
AsyncDfu { client: self }
}
/// Handle for a debug-probe net (flash/erase/reset/read_memory).
/// Talks to the box debug service on port 8765.
pub fn debug(&self, name: impl Into<String>) -> AsyncDebugNet<'_> {
AsyncDebugNet {
client: self,
name: name.into(),
record: Default::default(),
}
}
/// Handle for an oscilloscope net, the instrument or one of its
/// channels (box >= 0.55.0). See [`crate::nets::scope`].
pub fn scope(&self, name: impl Into<String>) -> AsyncScope<'_> {
AsyncScope {
client: self,
name: name.into(),
}
}
/// Handle for a YubiHSM 2 net (box >= 0.59.0). See [`crate::nets::hsm`].
pub fn hsm(&self, name: impl Into<String>) -> AsyncHsm<'_> {
AsyncHsm {
client: self,
name: name.into(),
}
}
}
/// TCP connect with a timeout (tokio tries every resolved address).
async fn connect_tcp(host: &str, port: u16, timeout: Duration) -> Result<tokio::net::TcpStream> {
let context = format!("{host}:{port}");
match tokio::time::timeout(timeout, tokio::net::TcpStream::connect((host, port))).await {
Ok(Ok(stream)) => Ok(stream),
Ok(Err(e)) => Err(crate::tunnel::io_error(&context, e)),
Err(_) => Err(Error::Timeout(format!("{context}: connect timed out"))),
}
}