opc-da-client 0.1.3

Backend-agnostic OPC DA client library for Rust — async, trait-based, with RAII COM guard
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
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
use crate::opc_da::utils::{
    IntoBridge, LocalPointer, RemoteArray, ToNative, TryFromNative, TryToNative,
};
use crate::try_from_native;

/// Supported OPC DA Specification versions.
#[derive(Debug, Clone, PartialEq)]
pub enum Version {
    V1,
    V2,
    V3,
}

/// Current state and properties of an active OPC group.
#[derive(Debug, Clone, Default, PartialEq)]
pub struct GroupState {
    pub update_rate: u32,
    pub active: bool,
    pub name: String,
    pub time_bias: i32,
    pub percent_deadband: f32,
    pub locale_id: u32,
    pub client_handle: u32,
    pub server_handle: u32,
}

/// Operational status and metadata of the connected server.
#[derive(Debug, Clone, PartialEq)]
pub struct ServerStatus {
    pub start_time: std::time::SystemTime,
    pub current_time: std::time::SystemTime,
    pub last_update_time: std::time::SystemTime,
    pub server_state: ServerState,
    pub group_count: u32,
    pub band_width: u32,
    pub major_version: u16,
    pub minor_version: u16,
    pub build_number: u16,
    pub vendor_info: String,
}

impl TryFromNative<crate::bindings::da::tagOPCSERVERSTATUS> for ServerStatus {
    fn try_from_native(
        native: &crate::bindings::da::tagOPCSERVERSTATUS,
    ) -> windows::core::Result<Self> {
        Ok(Self {
            start_time: try_from_native!(&native.ftStartTime),
            current_time: try_from_native!(&native.ftCurrentTime),
            last_update_time: try_from_native!(&native.ftLastUpdateTime),
            server_state: try_from_native!(&native.dwServerState),
            group_count: native.dwGroupCount,
            band_width: native.dwBandWidth,
            major_version: native.wMajorVersion,
            minor_version: native.wMinorVersion,
            build_number: native.wBuildNumber,
            vendor_info: try_from_native!(&native.szVendorInfo),
        })
    }
}

/// Definition required to add a new item to an OPC group.
#[derive(Debug, Clone, Default, PartialEq)]
pub struct ItemDef {
    pub access_path: String,
    pub item_id: String,
    pub active: bool,
    pub client_handle: u32,
    pub data_type: u16,
    pub blob: Vec<u8>,
}

/// FFI-safe bridge struct for `ItemDef`.
pub struct ItemDefBridge {
    pub access_path: LocalPointer<Vec<u16>>,
    pub item_id: LocalPointer<Vec<u16>>,
    pub active: bool,
    pub item_client_handle: u32,
    pub requested_data_type: u16,
    pub blob: LocalPointer<Vec<u8>>,
}

impl IntoBridge<ItemDefBridge> for ItemDef {
    fn into_bridge(self) -> ItemDefBridge {
        ItemDefBridge {
            access_path: LocalPointer::from(&self.access_path),
            item_id: LocalPointer::from(&self.item_id),
            active: self.active,
            item_client_handle: self.client_handle,
            requested_data_type: self.data_type,
            blob: LocalPointer::new(Some(self.blob)),
        }
    }
}

impl TryToNative<crate::bindings::da::tagOPCITEMDEF> for ItemDefBridge {
    fn try_to_native(&self) -> windows::core::Result<crate::bindings::da::tagOPCITEMDEF> {
        Ok(crate::bindings::da::tagOPCITEMDEF {
            szAccessPath: self.access_path.as_pwstr(),
            szItemID: self.item_id.as_pwstr(),
            bActive: self.active.into(),
            hClient: self.item_client_handle,
            vtRequestedDataType: self.requested_data_type,
            dwBlobSize: self.blob.len().try_into().map_err(|_| {
                windows::core::Error::new(
                    windows::Win32::Foundation::E_INVALIDARG,
                    "Blob size exceeds u32 maximum value",
                )
            })?,
            pBlob: self.blob.as_array_ptr() as *mut _,
            wReserved: 0,
        })
    }
}

/// Result properties of an item after being added to a group.
#[derive(Debug, Clone, PartialEq)]
pub struct ItemResult {
    pub server_handle: u32,
    pub data_type: u16,
    pub access_rights: u32,
    pub blob: Vec<u8>,
}

impl TryFromNative<crate::bindings::da::tagOPCITEMRESULT> for ItemResult {
    fn try_from_native(
        native: &crate::bindings::da::tagOPCITEMRESULT,
    ) -> windows::core::Result<Self> {
        Ok(Self {
            server_handle: native.hServer,
            data_type: native.vtCanonicalDataType,
            access_rights: native.dwAccessRights,
            blob: RemoteArray::from_mut_ptr(native.pBlob, native.dwBlobSize)
                .as_slice()
                .to_vec(),
        })
    }
}

/// Current running state of the OPC server.
#[derive(Debug, Clone, PartialEq)]
pub enum ServerState {
    Running,
    Failed,
    NoConfig,
    Suspended,
    Test,
    CommunicationFault,
}

impl TryFromNative<crate::bindings::da::tagOPCSERVERSTATE> for ServerState {
    fn try_from_native(
        native: &crate::bindings::da::tagOPCSERVERSTATE,
    ) -> windows::core::Result<Self> {
        match *native {
            crate::bindings::da::OPC_STATUS_RUNNING => Ok(ServerState::Running),
            crate::bindings::da::OPC_STATUS_FAILED => Ok(ServerState::Failed),
            crate::bindings::da::OPC_STATUS_NOCONFIG => Ok(ServerState::NoConfig),
            crate::bindings::da::OPC_STATUS_SUSPENDED => Ok(ServerState::Suspended),
            crate::bindings::da::OPC_STATUS_TEST => Ok(ServerState::Test),
            crate::bindings::da::OPC_STATUS_COMM_FAULT => Ok(ServerState::CommunicationFault),
            unknown => Err(windows::core::Error::new(
                windows::Win32::Foundation::E_INVALIDARG,
                format!("Unknown server state: {unknown:?}"),
            )),
        }
    }
}

impl ToNative<crate::bindings::da::tagOPCSERVERSTATE> for ServerState {
    fn to_native(&self) -> crate::bindings::da::tagOPCSERVERSTATE {
        match self {
            ServerState::Running => crate::bindings::da::OPC_STATUS_RUNNING,
            ServerState::Failed => crate::bindings::da::OPC_STATUS_FAILED,
            ServerState::NoConfig => crate::bindings::da::OPC_STATUS_NOCONFIG,
            ServerState::Suspended => crate::bindings::da::OPC_STATUS_SUSPENDED,
            ServerState::Test => crate::bindings::da::OPC_STATUS_TEST,
            ServerState::CommunicationFault => crate::bindings::da::OPC_STATUS_COMM_FAULT,
        }
    }
}

/// Scope for enumerating server items or connections.
#[derive(Debug, Clone, PartialEq)]
pub enum EnumScope {
    PrivateConnections,
    PublicConnections,
    AllConnections,
    Public,
    Private,
    All,
}

impl TryFromNative<crate::bindings::da::tagOPCENUMSCOPE> for EnumScope {
    fn try_from_native(
        native: &crate::bindings::da::tagOPCENUMSCOPE,
    ) -> windows::core::Result<Self> {
        match *native {
            crate::bindings::da::OPC_ENUM_PRIVATE_CONNECTIONS => Ok(EnumScope::PrivateConnections),
            crate::bindings::da::OPC_ENUM_PUBLIC_CONNECTIONS => Ok(EnumScope::PublicConnections),
            crate::bindings::da::OPC_ENUM_ALL_CONNECTIONS => Ok(EnumScope::AllConnections),
            crate::bindings::da::OPC_ENUM_PUBLIC => Ok(EnumScope::Public),
            crate::bindings::da::OPC_ENUM_PRIVATE => Ok(EnumScope::Private),
            crate::bindings::da::OPC_ENUM_ALL => Ok(EnumScope::All),
            unknown => Err(windows::core::Error::new(
                windows::Win32::Foundation::E_INVALIDARG,
                format!("Unknown enum scope: {unknown:?}"),
            )),
        }
    }
}

impl ToNative<crate::bindings::da::tagOPCENUMSCOPE> for EnumScope {
    fn to_native(&self) -> crate::bindings::da::tagOPCENUMSCOPE {
        match self {
            EnumScope::PrivateConnections => crate::bindings::da::OPC_ENUM_PRIVATE_CONNECTIONS,
            EnumScope::PublicConnections => crate::bindings::da::OPC_ENUM_PUBLIC_CONNECTIONS,
            EnumScope::AllConnections => crate::bindings::da::OPC_ENUM_ALL_CONNECTIONS,
            EnumScope::Public => crate::bindings::da::OPC_ENUM_PUBLIC,
            EnumScope::Private => crate::bindings::da::OPC_ENUM_PRIVATE,
            EnumScope::All => crate::bindings::da::OPC_ENUM_ALL,
        }
    }
}

/// Full attribute set of a single OPC item.
pub struct ItemAttributes {
    pub access_path: String,
    pub item_id: String,
    pub active: bool,
    pub client_handle: u32,
    pub server_handle: u32,
    pub access_rights: u32,
    pub blob: Vec<u8>,
    pub requested_data_type: u16,
    pub canonical_data_type: u16,
    pub eu_type: EuType,
    pub eu_info: windows::Win32::System::Variant::VARIANT,
}

impl TryFromNative<crate::bindings::da::tagOPCITEMATTRIBUTES> for ItemAttributes {
    fn try_from_native(
        native: &crate::bindings::da::tagOPCITEMATTRIBUTES,
    ) -> windows::core::Result<Self> {
        Ok(Self {
            access_path: try_from_native!(&native.szAccessPath),
            item_id: try_from_native!(&native.szItemID),
            active: native.bActive.into(),
            client_handle: native.hClient,
            server_handle: native.hServer,
            access_rights: native.dwAccessRights,
            blob: RemoteArray::from_mut_ptr(native.pBlob, native.dwBlobSize)
                .as_slice()
                .to_vec(),
            requested_data_type: native.vtRequestedDataType,
            canonical_data_type: native.vtCanonicalDataType,
            eu_type: try_from_native!(&native.dwEUType),
            eu_info: native.vEUInfo.clone(),
        })
    }
}

/// Engineering Units (EU) classification type.
pub enum EuType {
    NoEnum,
    Analog,
    Enumerated,
}

impl TryFromNative<crate::bindings::da::tagOPCEUTYPE> for EuType {
    fn try_from_native(native: &crate::bindings::da::tagOPCEUTYPE) -> windows::core::Result<Self> {
        match *native {
            crate::bindings::da::OPC_NOENUM => Ok(EuType::NoEnum),
            crate::bindings::da::OPC_ANALOG => Ok(EuType::Analog),
            crate::bindings::da::OPC_ENUMERATED => Ok(EuType::Enumerated),
            unknown => Err(windows::core::Error::new(
                windows::Win32::Foundation::E_INVALIDARG,
                format!("Unknown EU type: {unknown:?}"),
            )),
        }
    }
}

/// Current state of a watched OPC item including value, quality, and time.
pub struct ItemState {
    pub client_handle: u32,
    pub timestamp: std::time::SystemTime,
    pub quality: u16,
    pub data_value: windows::Win32::System::Variant::VARIANT,
}

impl TryFromNative<crate::bindings::da::tagOPCITEMSTATE> for ItemState {
    fn try_from_native(
        native: &crate::bindings::da::tagOPCITEMSTATE,
    ) -> windows::core::Result<Self> {
        Ok(Self {
            client_handle: native.hClient,
            timestamp: try_from_native!(&native.ftTimeStamp),
            quality: native.wQuality,
            data_value: native.vDataValue.clone(),
        })
    }
}

/// Reading source preference (Cache or Device).
pub enum DataSourceTarget {
    ForceCache,
    ForceDevice,
    WithMaxAge(u32),
}

impl DataSourceTarget {
    pub fn max_age(&self) -> u32 {
        match self {
            DataSourceTarget::WithMaxAge(max_age) => *max_age,
            DataSourceTarget::ForceCache => u32::MAX,
            DataSourceTarget::ForceDevice => 0,
        }
    }
}

impl TryFromNative<crate::bindings::da::tagOPCDATASOURCE> for DataSourceTarget {
    fn try_from_native(
        native: &crate::bindings::da::tagOPCDATASOURCE,
    ) -> windows::core::Result<Self> {
        match *native {
            crate::bindings::da::OPC_DS_CACHE => Ok(DataSourceTarget::ForceCache),
            crate::bindings::da::OPC_DS_DEVICE => Ok(DataSourceTarget::ForceDevice),
            unknown => Err(windows::core::Error::new(
                windows::Win32::Foundation::E_INVALIDARG,
                format!("Unknown data source: {unknown:?}"),
            )),
        }
    }
}

impl TryToNative<crate::bindings::da::tagOPCDATASOURCE> for DataSourceTarget {
    fn try_to_native(&self) -> windows::core::Result<crate::bindings::da::tagOPCDATASOURCE> {
        match self {
            DataSourceTarget::ForceCache => Ok(crate::bindings::da::OPC_DS_CACHE),
            DataSourceTarget::ForceDevice => Ok(crate::bindings::da::OPC_DS_DEVICE),
            DataSourceTarget::WithMaxAge(_) => Err(windows::core::Error::new(
                windows::Win32::Foundation::E_INVALIDARG,
                "MaxAge data source requires a value",
            )),
        }
    }
}

/// Full read value result carrying value, quality, and timestamp.
pub struct ItemValue {
    pub value: windows::Win32::System::Variant::VARIANT,
    pub quality: u16,
    pub timestamp: std::time::SystemTime,
}

impl
    TryFromNative<(
        RemoteArray<windows::Win32::System::Variant::VARIANT>,
        RemoteArray<u16>,
        RemoteArray<windows::Win32::Foundation::FILETIME>,
        RemoteArray<windows::core::HRESULT>,
    )> for Vec<windows::core::Result<ItemValue>>
{
    fn try_from_native(
        native: &(
            RemoteArray<windows::Win32::System::Variant::VARIANT>,
            RemoteArray<u16>,
            RemoteArray<windows::Win32::Foundation::FILETIME>,
            RemoteArray<windows::core::HRESULT>,
        ),
    ) -> windows::core::Result<Self> {
        let (values, qualities, timestamps, errors) = native;

        if values.len() != qualities.len()
            || values.len() != timestamps.len()
            || values.len() != errors.len()
        {
            return Err(windows::core::Error::new(
                windows::Win32::Foundation::E_INVALIDARG,
                "Arrays have different lengths",
            ));
        }

        Ok(values
            .as_slice()
            .iter()
            .zip(qualities.as_slice())
            .zip(timestamps.as_slice())
            .zip(errors.as_slice())
            .map(|(((value, quality), timestamp), error)| {
                if error.is_ok() {
                    Ok(ItemValue {
                        value: value.clone(),
                        quality: *quality,
                        timestamp: try_from_native!(timestamp),
                    })
                } else {
                    Err((*error).into())
                }
            })
            .collect())
    }
}

/// Item value struct for writes or partial updates.
pub struct ItemPartialValue {
    pub value: windows::Win32::System::Variant::VARIANT,
    pub quality: Option<u16>,
    pub timestamp: Option<std::time::SystemTime>,
}

// try to native
impl TryToNative<crate::bindings::da::tagOPCITEMVQT> for ItemPartialValue {
    fn try_to_native(&self) -> windows::core::Result<crate::bindings::da::tagOPCITEMVQT> {
        Ok(crate::bindings::da::tagOPCITEMVQT {
            vDataValue: self.value.clone(),
            bQualitySpecified: self.quality.is_some().into(),
            wQuality: self.quality.unwrap_or_default(),
            bTimeStampSpecified: self.timestamp.is_some().into(),
            ftTimeStamp: self
                .timestamp
                .map(|t| t.try_to_native())
                .transpose()?
                .unwrap_or_default(),
            wReserved: 0,
            dwReserved: 0,
        })
    }
}

/// Filter type for navigating the namespace (Branch, Leaf, Flat).
pub enum BrowseType {
    Branch,
    Leaf,
    Flat,
}

impl TryFromNative<crate::bindings::da::tagOPCBROWSETYPE> for BrowseType {
    fn try_from_native(
        native: &crate::bindings::da::tagOPCBROWSETYPE,
    ) -> windows::core::Result<Self> {
        match *native {
            crate::bindings::da::OPC_BRANCH => Ok(BrowseType::Branch),
            crate::bindings::da::OPC_LEAF => Ok(BrowseType::Leaf),
            crate::bindings::da::OPC_FLAT => Ok(BrowseType::Flat),
            unknown => Err(windows::core::Error::new(
                windows::Win32::Foundation::E_INVALIDARG,
                format!("Unknown browse type: {unknown:?}"),
            )),
        }
    }
}

impl ToNative<crate::bindings::da::tagOPCBROWSETYPE> for BrowseType {
    fn to_native(&self) -> crate::bindings::da::tagOPCBROWSETYPE {
        match self {
            BrowseType::Branch => crate::bindings::da::OPC_BRANCH,
            BrowseType::Leaf => crate::bindings::da::OPC_LEAF,
            BrowseType::Flat => crate::bindings::da::OPC_FLAT,
        }
    }
}

/// Granular filter for enumeration results.
pub enum BrowseFilter {
    All,
    Branches,
    Items,
}

impl TryFromNative<crate::bindings::da::tagOPCBROWSEFILTER> for BrowseFilter {
    fn try_from_native(
        native: &crate::bindings::da::tagOPCBROWSEFILTER,
    ) -> windows::core::Result<Self> {
        match *native {
            crate::bindings::da::OPC_BROWSE_FILTER_ALL => Ok(BrowseFilter::All),
            crate::bindings::da::OPC_BROWSE_FILTER_BRANCHES => Ok(BrowseFilter::Branches),
            crate::bindings::da::OPC_BROWSE_FILTER_ITEMS => Ok(BrowseFilter::Items),
            unknown => Err(windows::core::Error::new(
                windows::Win32::Foundation::E_INVALIDARG,
                format!("Unknown browse filter: {unknown:?}"),
            )),
        }
    }
}

impl ToNative<crate::bindings::da::tagOPCBROWSEFILTER> for BrowseFilter {
    fn to_native(&self) -> crate::bindings::da::tagOPCBROWSEFILTER {
        match self {
            BrowseFilter::All => crate::bindings::da::OPC_BROWSE_FILTER_ALL,
            BrowseFilter::Branches => crate::bindings::da::OPC_BROWSE_FILTER_BRANCHES,
            BrowseFilter::Items => crate::bindings::da::OPC_BROWSE_FILTER_ITEMS,
        }
    }
}

/// Event types dispatched by asynchronous COM callbacks.
#[derive(Debug, Clone, PartialEq)]
pub enum DataCallbackEvent {
    DataChange(DataChangeEvent),
    ReadComplete(ReadCompleteEvent),
    WriteComplete(WriteCompleteEvent),
    CancelComplete(CancelCompleteEvent),
}

/// Payload for data change synchronous/asynchronous callbacks.
#[derive(Debug, Clone, PartialEq)]
pub struct DataChangeEvent {
    pub transaction_id: u32,
    pub group_handle: u32,
    pub master_quality: windows_core::HRESULT,
    pub master_error: windows_core::HRESULT,
    pub client_items: RemoteArray<u32>,
    pub values: RemoteArray<windows::Win32::System::Variant::VARIANT>,
    pub qualities: RemoteArray<u16>,
    pub timestamps: RemoteArray<windows::Win32::Foundation::FILETIME>,
    pub errors: RemoteArray<windows_core::HRESULT>,
}

/// Payload for async read completion.
#[derive(Debug, Clone, PartialEq)]
pub struct ReadCompleteEvent {
    pub transaction_id: u32,
    pub group_handle: u32,
    pub master_quality: windows_core::HRESULT,
    pub master_error: windows_core::HRESULT,
    pub client_items: RemoteArray<u32>,
    pub values: RemoteArray<windows::Win32::System::Variant::VARIANT>,
    pub qualities: RemoteArray<u16>,
    pub timestamps: RemoteArray<windows::Win32::Foundation::FILETIME>,
    pub errors: RemoteArray<windows_core::HRESULT>,
}

/// Payload for async write completion.
#[derive(Debug, Clone, PartialEq)]
pub struct WriteCompleteEvent {
    pub transaction_id: u32,
    pub group_handle: u32,
    pub master_error: windows_core::HRESULT,
    pub client_handles: RemoteArray<u32>,
    pub errors: RemoteArray<windows_core::HRESULT>,
}

/// Payload for async cancel completion.
#[derive(Debug, Clone, PartialEq)]
pub struct CancelCompleteEvent {
    pub transaction_id: u32,
    pub group_handle: u32,
}

/// Typology of the server's address space.
pub enum NamespaceType {
    Flat,
    Hierarchy,
}

impl TryFromNative<crate::bindings::da::tagOPCNAMESPACETYPE> for NamespaceType {
    fn try_from_native(
        native: &crate::bindings::da::tagOPCNAMESPACETYPE,
    ) -> windows::core::Result<Self> {
        match *native {
            crate::bindings::da::OPC_NS_HIERARCHIAL => Ok(NamespaceType::Hierarchy),
            crate::bindings::da::OPC_NS_FLAT => Ok(NamespaceType::Flat),
            unknown => Err(windows::core::Error::new(
                windows::Win32::Foundation::E_INVALIDARG,
                format!("Unknown namespace type: {unknown:?}"),
            )),
        }
    }
}

impl ToNative<crate::bindings::da::tagOPCNAMESPACETYPE> for NamespaceType {
    fn to_native(&self) -> crate::bindings::da::tagOPCNAMESPACETYPE {
        match self {
            NamespaceType::Hierarchy => crate::bindings::da::OPC_NS_HIERARCHIAL,
            NamespaceType::Flat => crate::bindings::da::OPC_NS_FLAT,
        }
    }
}

// COSERVERINFO
/// Information defining how to connect to a remote server.
#[derive(Debug, Clone, PartialEq)]
pub struct ServerInfo {
    pub name: String,
    pub auth_info: AuthInfo,
}

/// FFI-safe bridge for `ServerInfo` (COSERVERINFO).
pub struct ServerInfoBridge {
    pub name: LocalPointer<Vec<u16>>,
    pub auth_info: AuthInfoBridge,
}

impl IntoBridge<ServerInfoBridge> for ServerInfo {
    fn into_bridge(self) -> ServerInfoBridge {
        ServerInfoBridge {
            name: LocalPointer::from(&self.name),
            auth_info: self.auth_info.into_bridge(),
        }
    }
}

impl TryToNative<windows::Win32::System::Com::COSERVERINFO> for ServerInfoBridge {
    fn try_to_native(&self) -> windows::core::Result<windows::Win32::System::Com::COSERVERINFO> {
        Ok(windows::Win32::System::Com::COSERVERINFO {
            dwReserved1: 0,
            dwReserved2: 0,
            pwszName: self.name.as_pwstr(),
            pAuthInfo: &self.auth_info.try_to_native()? as *const _ as *mut _,
        })
    }
}

/// Authentication and authorization settings for DCOM.
#[derive(Debug, Clone, PartialEq)]
pub struct AuthInfo {
    pub authn_svc: u32,
    pub authz_svc: u32,
    pub server_principal_name: String,
    pub authn_level: u32,
    pub impersonation_level: u32,
    pub auth_identity_data: AuthIdentity,
    pub capabilities: u32,
}

/// FFI-safe bridge for `AuthInfo` (COAUTHINFO).
pub struct AuthInfoBridge {
    pub authn_svc: u32,
    pub authz_svc: u32,
    pub server_principal_name: LocalPointer<Vec<u16>>,
    pub authn_level: u32,
    pub impersonation_level: u32,
    pub auth_identity_data: AuthIdentityBridge,
    pub capabilities: u32,
}

impl IntoBridge<AuthInfoBridge> for AuthInfo {
    fn into_bridge(self) -> AuthInfoBridge {
        AuthInfoBridge {
            authn_svc: self.authn_svc,
            authz_svc: self.authz_svc,
            server_principal_name: LocalPointer::from(&self.server_principal_name),
            authn_level: self.authn_level,
            impersonation_level: self.impersonation_level,
            auth_identity_data: self.auth_identity_data.into_bridge(),
            capabilities: self.capabilities,
        }
    }
}

impl TryToNative<windows::Win32::System::Com::COAUTHINFO> for AuthInfoBridge {
    fn try_to_native(&self) -> windows::core::Result<windows::Win32::System::Com::COAUTHINFO> {
        Ok(windows::Win32::System::Com::COAUTHINFO {
            dwAuthnSvc: self.authn_svc,
            dwAuthzSvc: self.authz_svc,
            pwszServerPrincName: self.server_principal_name.as_pwstr(),
            dwAuthnLevel: self.authn_level,
            dwImpersonationLevel: self.impersonation_level,
            pAuthIdentityData: &self.auth_identity_data.try_to_native()? as *const _ as *mut _,
            dwCapabilities: self.capabilities,
        })
    }
}

/// DCOM authentication credentials.
#[derive(Debug, Clone, PartialEq)]
pub struct AuthIdentity {
    pub user: String,
    pub domain: String,
    pub password: String,
    pub flags: u32,
}

/// FFI-safe bridge for `AuthIdentity` (COAUTHIDENTITY).
pub struct AuthIdentityBridge {
    pub user: LocalPointer<Vec<u16>>,
    pub domain: LocalPointer<Vec<u16>>,
    pub password: LocalPointer<Vec<u16>>,
    pub flags: u32,
}

impl IntoBridge<AuthIdentityBridge> for AuthIdentity {
    fn into_bridge(self) -> AuthIdentityBridge {
        AuthIdentityBridge {
            user: LocalPointer::from(&self.user),
            domain: LocalPointer::from(&self.domain),
            password: LocalPointer::from(&self.password),
            flags: self.flags,
        }
    }
}

impl TryToNative<windows::Win32::System::Com::COAUTHIDENTITY> for AuthIdentityBridge {
    fn try_to_native(&self) -> windows::core::Result<windows::Win32::System::Com::COAUTHIDENTITY> {
        Ok(windows::Win32::System::Com::COAUTHIDENTITY {
            User: self.user.as_pwstr().0,
            UserLength: self.user.len().try_into().map_err(|_| {
                windows::core::Error::new(
                    windows::Win32::Foundation::E_INVALIDARG,
                    "User name exceeds u32 maximum length",
                )
            })?,
            Domain: self.domain.as_pwstr().0,
            DomainLength: self.domain.len().try_into().map_err(|_| {
                windows::core::Error::new(
                    windows::Win32::Foundation::E_INVALIDARG,
                    "Domain name exceeds u32 maximum length",
                )
            })?,
            Password: self.password.as_pwstr().0,
            PasswordLength: self.password.len().try_into().map_err(|_| {
                windows::core::Error::new(
                    windows::Win32::Foundation::E_INVALIDARG,
                    "Password exceeds u32 maximum length",
                )
            })?,
            Flags: self.flags,
        })
    }
}

/// COM instantiation context flags (CLSCTX).
#[derive(Debug, Clone, PartialEq)]
pub enum ClassContext {
    All,
    InProcServer,
    InProcHandler,
    LocalServer,
    InProcServer16,
    RemoteServer,
    InProcHandler16,
    NoCodeDownload,
    NoCustomMarshal,
    EnableCodeDownload,
    NoFailureLog,
    DisableAAA,
    EnableAAA,
    FromDefaultContext,
    ActivateX86Server,
    Activate32BitServer,
    Activate64BitServer,
    EnableCloaking,
    AppContainer,
    ActivateAAAAsIU,
    ActivateARM32Server,
    AllowLowerTrustRegistration,
    PsDll,
}

impl ToNative<windows::Win32::System::Com::CLSCTX> for ClassContext {
    fn to_native(&self) -> windows::Win32::System::Com::CLSCTX {
        match self {
            ClassContext::All => windows::Win32::System::Com::CLSCTX_ALL,
            ClassContext::InProcServer => windows::Win32::System::Com::CLSCTX_INPROC_SERVER,
            ClassContext::InProcHandler => windows::Win32::System::Com::CLSCTX_INPROC_HANDLER,
            ClassContext::LocalServer => windows::Win32::System::Com::CLSCTX_LOCAL_SERVER,
            ClassContext::InProcServer16 => windows::Win32::System::Com::CLSCTX_INPROC_SERVER16,
            ClassContext::RemoteServer => windows::Win32::System::Com::CLSCTX_REMOTE_SERVER,
            ClassContext::InProcHandler16 => windows::Win32::System::Com::CLSCTX_INPROC_HANDLER16,
            ClassContext::NoCodeDownload => windows::Win32::System::Com::CLSCTX_NO_CODE_DOWNLOAD,
            ClassContext::NoCustomMarshal => windows::Win32::System::Com::CLSCTX_NO_CUSTOM_MARSHAL,
            ClassContext::EnableCodeDownload => {
                windows::Win32::System::Com::CLSCTX_ENABLE_CODE_DOWNLOAD
            }
            ClassContext::NoFailureLog => windows::Win32::System::Com::CLSCTX_NO_FAILURE_LOG,
            ClassContext::DisableAAA => windows::Win32::System::Com::CLSCTX_DISABLE_AAA,
            ClassContext::EnableAAA => windows::Win32::System::Com::CLSCTX_ENABLE_AAA,
            ClassContext::FromDefaultContext => {
                windows::Win32::System::Com::CLSCTX_FROM_DEFAULT_CONTEXT
            }
            ClassContext::ActivateX86Server => {
                windows::Win32::System::Com::CLSCTX_ACTIVATE_X86_SERVER
            }
            ClassContext::Activate32BitServer => {
                windows::Win32::System::Com::CLSCTX_ACTIVATE_32_BIT_SERVER
            }
            ClassContext::Activate64BitServer => {
                windows::Win32::System::Com::CLSCTX_ACTIVATE_64_BIT_SERVER
            }
            ClassContext::EnableCloaking => windows::Win32::System::Com::CLSCTX_ENABLE_CLOAKING,
            ClassContext::AppContainer => windows::Win32::System::Com::CLSCTX_APPCONTAINER,
            ClassContext::ActivateAAAAsIU => windows::Win32::System::Com::CLSCTX_ACTIVATE_AAA_AS_IU,
            ClassContext::ActivateARM32Server => {
                windows::Win32::System::Com::CLSCTX_ACTIVATE_ARM32_SERVER
            }
            ClassContext::AllowLowerTrustRegistration => {
                windows::Win32::System::Com::CLSCTX_ALLOW_LOWER_TRUST_REGISTRATION
            }
            ClassContext::PsDll => windows::Win32::System::Com::CLSCTX_PS_DLL,
        }
    }
}