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
#[cfg_attr(
not(all(feature = "client", feature = "server", feature = "camera")),
allow(unused_macro_rules)
)]
macro_rules! rpc_trait {
(@extras Device trait) => {
/// Static device name for the configured list.
fn static_name(&self) -> &str;
/// Unique ID of this device.
fn unique_id(&self) -> &str;
/// ```rust,no_run
/// async fn setup(&self) -> eyre::Result<String>
/// # { unimplemented!() }
/// ```
///
/// Web page user interface that enables device specific configuration to be set for each available device.
///
/// The server should implement this to return HTML string. You can use [`Self::action`] to store the configuration.
///
/// Note: on the client side you almost never want to just retrieve HTML to show it in the browser, as that breaks relative URLs.
/// Use the `/{device_type}/{device_number}/setup` URL instead.
fn setup(&self) -> futures::future::BoxFuture<'_, eyre::Result<String>> {
Box::pin(futures::future::ok(include_str!("../server/device_setup_template.html").to_owned()))
}
};
(@extras $trait_name:ident trait) => {
/// Return all operational properties of this device.
///
/// See [What is the “read all” feature and what are its rules?](https://ascom-standards.org/newdocs/readall-faq.html#readall-faq).
fn device_state<'this: 'async_trait, 'async_trait>(&'this self) -> crate::api::ASCOMResultFuture<'async_trait, crate::api::TimestampedDeviceState<DeviceState>> {
Box::pin(async move {
Ok(crate::api::TimestampedDeviceState::new(DeviceState::new(self).await))
})
}
};
(@extras Device client) => {
fn static_name(&self) -> &str {
&self.name
}
fn unique_id(&self) -> &str {
&self.unique_id
}
fn setup(&self) -> futures::future::BoxFuture<'_, eyre::Result<String>> {
Box::pin(async move {
Ok(
$crate::client::REQWEST
.get(self.inner.base_url.join("setup")?)
.send()
.await?
.text()
.await?
)
})
}
};
(@extras $trait_name:ident client) => {
#[expect(single_use_lifetimes)] // we need compat with #[async_trait]
fn device_state<'this: 'async_trait, 'async_trait>(&'this self) -> crate::api::ASCOMResultFuture<'async_trait, crate::api::TimestampedDeviceState<DeviceState>> {
Box::pin(async move {
match self.exec_action(Action::DeviceState).await.map(crate::api::device_state::de::TimestampedDeviceStateRepr::into_inner) {
Err(crate::ASCOMError { code: crate::ASCOMErrorCode::NOT_IMPLEMENTED, .. }) => {
// Fallback to individual property retrieval.
Ok(crate::api::TimestampedDeviceState::new(DeviceState::new(self).await))
}
result => result,
}
})
}
};
(@extras Device mod) => {
#[cfg(feature = "server")]
#[derive(serde::Serialize)]
pub(super) struct DeviceState; // dummy, we don't have any properties here
#[cfg(feature = "server")]
impl dyn Device {
async fn device_state(&self) -> ASCOMResult<crate::api::TimestampedDeviceState<DeviceState>> {
// we don't expose Device::device_state, but we do need to handle it on the server
Ok(crate::api::TimestampedDeviceState::new(DeviceState))
}
}
};
(@extras $trait_name:ident mod) => {
impl super::RetrieavableDevice for dyn $trait_name {
const TYPE: super::DeviceType = super::DeviceType::$trait_name;
fn get_storage(storage: &super::Devices) -> &[std::sync::Arc<Self>] {
&storage.$trait_name
}
}
impl super::RegistrableDevice<dyn $trait_name> for std::sync::Arc<dyn $trait_name> {
fn add_to(self, storage: &mut super::Devices) {
storage.$trait_name.push(self);
}
}
impl<T: 'static + $trait_name> super::RegistrableDevice<dyn $trait_name> for T {
fn add_to(self, storage: &mut super::Devices) {
storage.$trait_name.push(std::sync::Arc::new(self));
}
}
#[cfg(test)]
#[tokio::test]
async fn run_proxy_tests() -> eyre::Result<()> {
$crate::test::run_proxy_tests::<dyn $trait_name>().await
}
};
// We only have dummy device state in the server-side handler.
(@device_state Device) => {};
// Switch needs some special handling to gather device state across all devices.
(@device_state Switch) => {};
(@device_state $trait_name:ident $(
$name:ident : $wire_name:literal as $ty:ty
)*) => {
/// An object representing all operational properties of the device.
#[derive(Default, Debug, Clone, Copy, serde::Serialize, serde::Deserialize)]
#[allow(clippy::unsafe_derive_deserialize)] // seems to be false positive
pub struct DeviceState {
$(
#[doc = concat!("Result of [`", stringify!($trait_name), "::", stringify!($name), "`].")]
#[serde(skip_serializing_if = "Option::is_none")]
#[serde(rename = $wire_name)]
pub $name: Option<$ty>,
)*
}
impl DeviceState {
async fn new(_device: &(impl ?Sized + $trait_name)) -> Self {
let ($($name,)*) = futures::join!($(_device.$name(),)*);
Self {
$($name: $name.ok(),)*
}
}
}
};
(@via $return_type:ty, $via:ty) => ($via);
(@via $return_type:ty) => ($return_type);
(@body ; $($header:tt)*) => {
$($header)* ;
};
(@body $default_body:block $($header:tt)*) => {
$($header)* {
Box::pin(async move $default_body)
}
};
(
$(# $attr:tt)*
$pub:vis trait $trait_name:ident: $trait_parents:ty {
$(
$(#[doc = $doc:literal])*
#[http($method_path:literal, method = $http_method:ident $(, via = $via:ty)? $(, device_state = $device_state_name:literal)?)]
$(# $method_attr:tt)*
async fn $method_name:ident(
& $self:ident $(, #[http($param_query:literal $(, via = $param_via:ty)?)] $param:ident: $param_ty:ty)* $(,)?
) -> ASCOMResult<$return_type:ty> $default_body:tt
)*
}
) => (paste::paste! {
rpc_trait!(@device_state $trait_name $($(
$method_name: $device_state_name as $return_type
)?)*);
#[cfg_attr(feature = "client", derive(serde::Serialize), serde(untagged))]
#[expect(non_camel_case_types)]
pub(super) enum Action {
$(
$method_name {
$(
#[cfg_attr(feature = "client", serde(rename = $param_query))]
$param: rpc_trait!(@via $param_ty $(, $param_via)?),
)*
},
)*
#[allow(dead_code)]
DeviceState,
}
#[cfg(feature = "server")]
#[derive(serde::Serialize)]
#[serde(untagged)]
#[expect(non_camel_case_types)]
pub(super) enum Response {
$(
$method_name(rpc_trait!(@via $return_type $(, $via)?)),
)*
#[serde(with = "crate::api::device_state::ser")]
DeviceState(crate::api::TimestampedDeviceState<DeviceState>),
}
impl $crate::params::Action for Action {
#[cfg(feature = "server")]
fn from_parts(action: &str, params: &mut $crate::server::ActionParams) -> $crate::server::Result<Option<Self>> {
Ok(Some(match (action, params) {
$(
($method_path, $crate::server::ActionParams::$http_method(_params)) => {
Self::$method_name {
$(
$param: _params.extract($param_query)?,
)*
}
}
)*
("devicestate", _) => Self::DeviceState,
_ => return Ok(None),
}))
}
#[cfg(feature = "client")]
fn into_parts(self) -> $crate::params::ActionParams<impl serde::Serialize> {
let (method, action) = match self {
$(Self::$method_name { .. } => ($crate::params::Method::$http_method, $method_path),)*
Self::DeviceState => ($crate::params::Method::Get, "devicestate"),
};
$crate::params::ActionParams {
action,
method,
params: self,
}
}
}
$(# $attr)*
#[allow(unused_variables)]
#[expect(single_use_lifetimes)]
$pub trait $trait_name: $trait_parents {
$(rpc_trait!(@body $default_body
/// ```rust,no_run
#[doc = concat!("async fn ", stringify!($method_name), "(&self", $(", ", stringify!($param), ": ", stringify!($param_ty),)* ") -> ASCOMResult<", stringify!($return_type), ">")]
/// # { unimplemented!() }
/// ```
///
$(#[doc = $doc])*
$(# $method_attr)*
fn $method_name<'this: 'async_trait, 'async_trait>(
&'this $self $(, $param: $param_ty)*
) -> crate::api::ASCOMResultFuture<'async_trait, $return_type>
);)*
rpc_trait!(@extras $trait_name trait);
}
#[cfg(feature = "client")]
#[async_trait::async_trait]
#[allow(useless_deprecated)]
impl $trait_name for $crate::client::RawDeviceClient {
$(
// some attrs are only applicable to the original method declaration in the trait, not to the impls
#[allow(unused_attributes)]
$(# $method_attr)*
async fn $method_name(
& $self $(, $param: $param_ty)*
) -> ASCOMResult<$return_type> {
$self
.exec_action(Action::$method_name {
$(
$param: $param.into(),
)*
})
.await
$(.map(<$via>::into))?
}
)*
rpc_trait!(@extras $trait_name client);
}
impl PartialEq for dyn $trait_name {
fn eq(&self, other: &Self) -> bool {
self.unique_id() == other.unique_id()
}
}
impl Eq for dyn $trait_name {}
impl std::hash::Hash for dyn $trait_name {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
self.unique_id().hash(state);
}
}
#[cfg(feature = "server")]
#[allow(deprecated)]
impl Action {
pub(super) async fn handle(self, device: std::sync::Arc<dyn $trait_name>) -> ASCOMResult<Response> {
match self {
$(
Self::$method_name { $($param),* } => {
device.$method_name($($param.into()),*)
.await
$(.map(<$via>::from))?
.map(Response::$method_name)
}
)*
Self::DeviceState => {
device.device_state()
.await
.map(Response::DeviceState)
}
}
}
}
rpc_trait!(@extras $trait_name mod);
});
}
macro_rules! rpc_mod {
($(# $cfg:tt $trait_name:ident = $path:literal,)*) => (paste::paste! {
$(
# $cfg
#[doc = "Types related to [`" $trait_name "`] devices."]
pub mod [<$trait_name:snake>];
# $cfg
pub use [<$trait_name:snake>]::$trait_name;
)*
#[derive(PartialOrd, Ord, PartialEq, Eq, Clone, Copy, Debug, derive_more::Display, serde::Serialize, serde::Deserialize)]
pub(super) enum DeviceType {
$(
# $cfg
#[display($path)]
$trait_name,
)*
}
/// A tagged enum wrapper for a type-erased instance of a device.
#[derive(Clone, Debug)]
#[expect(missing_docs)] // self-explanatory variants
pub enum TypedDevice {
$(
# $cfg
$trait_name(std::sync::Arc<dyn $trait_name>),
)*
}
impl RegistrableDevice<dyn Device> for TypedDevice {
fn add_to(self, storage: &mut Devices) {
match self {
$(
# $cfg
Self::$trait_name(device) => storage.$trait_name.push(device),
)*
}
}
}
/// Devices collection.
///
/// This data structure holds devices of arbitrary categories (cameras, telescopes, etc.)
/// and allows to register and access them by their kind and index.
#[expect(non_snake_case)]
#[derive(Clone)]
pub struct Devices {
$(
# $cfg
$trait_name: Vec<std::sync::Arc<dyn $trait_name>>,
)*
}
impl std::fmt::Debug for Devices {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut f = f.debug_struct("Devices");
$(
# $cfg
if !self.$trait_name.is_empty() {
_ = f.field(stringify!($trait_name), &self.$trait_name);
}
)*
f.finish()
}
}
impl Devices {
/// Create an empty collection of devices.
///
/// Same as [`Default::default`] but works in const contexts.
pub const fn default() -> Self {
Self {
$(
# $cfg
$trait_name: Vec::new(),
)*
}
}
/// Iterate over all registered devices.
///
/// The second element of the tuple is the index of the device within its category
/// (not the whole collection).
//
// TODO: make this IntoIterator (although the type is going to be ugly-looking).
// The usize is returned as 2nd arg just to attract attention to it not being
// a normal whole-iteration index.
pub fn iter_all(&self) -> impl Iterator<Item = (TypedDevice, usize)> {
let iter = std::iter::empty();
$(
# $cfg
let iter = iter.chain(
self.iter::<dyn $trait_name>()
.map(TypedDevice::$trait_name)
.enumerate()
.map(|(typed_index, device)| (device, typed_index))
);
)*
iter
}
}
#[cfg(feature = "client")]
impl $crate::client::RawDeviceClient {
pub(super) const fn into_typed_client(self: std::sync::Arc<Self>, device_type: DeviceType) -> TypedDevice {
match device_type {
$(
# $cfg
DeviceType::$trait_name => TypedDevice::$trait_name(self),
)*
}
}
}
#[cfg(feature = "server")]
#[derive(serde::Deserialize)]
#[serde(remote = "DeviceType")]
pub(super) enum DevicePath {
$(
# $cfg
#[serde(rename = $path)]
$trait_name,
)*
}
#[cfg(feature = "server")]
const _: () = {
impl TypedDevice {
pub(super) fn to_configured_device(&self, as_number: usize) -> ConfiguredDevice<DeviceType> {
match *self {
$(
# $cfg
Self::$trait_name(ref device) => device.to_configured_device(as_number),
)*
}
}
}
#[derive(serde::Serialize)]
#[serde(untagged)]
enum TypedResponse {
Device(device::Response),
$(
# $cfg
$trait_name([<$trait_name:snake>]::Response),
)*
}
enum TypedDeviceAction {
Device(device::Action),
$(
# $cfg
$trait_name([<$trait_name:snake>]::Action),
)*
}
impl TypedDeviceAction {
fn from_parts(device_type: DeviceType, action: &str, mut params: crate::server::ActionParams) -> crate::server::Result<Self> {
let result = match device_type {
$(
# $cfg
DeviceType::$trait_name =>
$crate::params::Action::from_parts(action, &mut params)?
.map(Self::$trait_name),
)*
};
let result = match result {
Some(result) => result,
// Fallback to generic device actions.
None => {
$crate::params::Action::from_parts(action, &mut params)?
.map(Self::Device)
.ok_or_else(|| crate::server::Error::UnknownAction {
device_type,
action: action.to_owned(),
})?
}
};
params.finish_extraction();
Ok(result)
}
}
impl Devices {
pub(super) fn get_device_for_server(
&self,
device_type: DeviceType,
device_number: usize,
) -> $crate::server::Result<Arc<dyn Device>> {
// With trait upcasting, we can get any device as dyn Device directly
Ok(match device_type {
$(
# $cfg
DeviceType::$trait_name => {
self.get_for_server::<dyn $trait_name>(device_number)?
}
)*
})
}
pub(super) async fn handle_action<'this>(&'this self, device_type: DeviceType, device_number: usize, action: &'this str, params: $crate::server::ActionParams) -> $crate::server::Result<impl serde::Serialize + use<>> {
let action = TypedDeviceAction::from_parts(device_type, action, params)?;
Ok(match action {
$(
# $cfg
TypedDeviceAction::$trait_name(action) => {
let device = self.get_for_server::<dyn $trait_name>(device_number)?;
TypedResponse::$trait_name(action.handle(device).await?)
}
)*
TypedDeviceAction::Device(action) => {
let device = self.get_device_for_server(device_type, device_number)?;
TypedResponse::Device(action.handle(device).await?)
}
})
}
}
};
});
}