mbus-ffi 0.13.0

Native C FFI and browser WASM bindings for modbus-rs client APIs, with optional generated server bindings
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
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
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
//! Node.js bindings for the async Modbus TCP client.

use std::sync::{Arc, Mutex};
use std::time::Duration;

use napi::bindgen_prelude::*;
use napi_derive::napi;

use mbus_client_async::AsyncTcpClient;
use mbus_core::transport::UnitIdOrSlaveAddr;

#[cfg(feature = "file-record")]
use mbus_client_async::SubRequest;
#[cfg(feature = "diagnostics")]
use mbus_core::function_codes::public::DiagnosticSubFunction;
#[cfg(feature = "diagnostics")]
use mbus_core::models::diagnostic::{ObjectId, ReadDeviceIdCode};

use crate::nodejs::errors::{ERR_MODBUS_INVALID_ARGUMENT, from_async_error, to_napi_err};

unsafe fn extend_lifetime<'a, 'b, T>(p: PromiseRaw<'a, T>) -> PromiseRaw<'b, T> {
    unsafe { std::mem::transmute(p) }
}

// ── Option structs ───────────────────────────────────────────────────────────

/// Connection options for the TCP client.
#[napi(object)]
#[derive(Debug, Clone)]
pub struct TcpClientOptions {
    /// Target host address (IP or hostname).
    pub host: String,
    /// Target TCP port (typically 502).
    pub port: u16,
    /// Modbus unit ID (1-247).
    pub unit_id: u8,
    /// Per-request timeout in milliseconds (optional).
    pub timeout_ms: Option<u32>,
}

/// Options for reading registers.
#[napi(object)]
pub struct ReadRegistersOptions<'a> {
    /// Starting register address.
    pub address: u16,
    /// Number of registers to read.
    pub quantity: u16,
    /// Optional abort signal to cancel the request.
    pub signal: Option<Object<'a>>,
}

/// Options for writing a single register.
#[napi(object)]
pub struct WriteSingleRegisterOptions<'a> {
    /// Register address.
    pub address: u16,
    /// Value to write.
    pub value: u16,
    /// Optional abort signal to cancel the request.
    pub signal: Option<Object<'a>>,
}

/// Options for writing multiple registers.
#[napi(object)]
pub struct WriteMultipleRegistersOptions<'a> {
    /// Starting register address.
    pub address: u16,
    /// Values to write.
    pub values: Vec<u16>,
    /// Optional abort signal to cancel the request.
    pub signal: Option<Object<'a>>,
}

/// Options for read/write multiple registers (FC23).
#[napi(object)]
pub struct ReadWriteMultipleRegistersOptions<'a> {
    /// Starting address for read operation.
    pub read_address: u16,
    /// Number of registers to read.
    pub read_quantity: u16,
    /// Starting address for write operation.
    pub write_address: u16,
    /// Values to write.
    pub write_values: Vec<u16>,
    /// Optional abort signal to cancel the request.
    pub signal: Option<Object<'a>>,
}

/// Options for reading coils or discrete inputs.
#[napi(object)]
pub struct ReadBitsOptions<'a> {
    /// Starting address.
    pub address: u16,
    /// Number of bits to read.
    pub quantity: u16,
    /// Optional abort signal to cancel the request.
    pub signal: Option<Object<'a>>,
}

/// Options for writing a single coil.
#[napi(object)]
pub struct WriteSingleCoilOptions<'a> {
    /// Coil address.
    pub address: u16,
    /// Value to write.
    pub value: bool,
    /// Optional abort signal to cancel the request.
    pub signal: Option<Object<'a>>,
}

/// Options for writing multiple coils.
#[napi(object)]
pub struct WriteMultipleCoilsOptions<'a> {
    /// Starting coil address.
    pub address: u16,
    /// Values to write.
    pub values: Vec<bool>,
    /// Optional abort signal to cancel the request.
    pub signal: Option<Object<'a>>,
}

/// Options for reading FIFO queue.
#[napi(object)]
pub struct ReadFifoQueueOptions<'a> {
    /// FIFO pointer address.
    pub address: u16,
    /// Optional abort signal to cancel the request.
    pub signal: Option<Object<'a>>,
}

/// Response from reading FIFO queue.
#[napi(object)]
#[derive(Debug, Clone)]
pub struct FifoQueueResponse {
    /// Number of values in the queue.
    pub count: u16,
    /// Queue values.
    pub values: Vec<u16>,
}

/// A single file record read sub-request.
#[napi(object)]
#[derive(Debug, Clone)]
pub struct FileRecordReadRequest {
    /// File number (1-65535).
    pub file_number: u16,
    /// Starting record number.
    pub record_number: u16,
    /// Number of records to read.
    pub record_length: u16,
}

/// Options for reading file records.
#[napi(object)]
pub struct ReadFileRecordOptions<'a> {
    /// Array of sub-requests.
    pub requests: Vec<FileRecordReadRequest>,
    /// Optional abort signal to cancel the request.
    pub signal: Option<Object<'a>>,
}

/// A single file record write sub-request.
#[napi(object)]
#[derive(Debug, Clone)]
pub struct FileRecordWriteRequest {
    /// File number (1-65535).
    pub file_number: u16,
    /// Starting record number.
    pub record_number: u16,
    /// Record data to write.
    pub record_data: Vec<u16>,
}

/// Options for writing file records.
#[napi(object)]
pub struct WriteFileRecordOptions<'a> {
    /// Array of sub-requests.
    pub requests: Vec<FileRecordWriteRequest>,
    /// Optional abort signal to cancel the request.
    pub signal: Option<Object<'a>>,
}

/// Options for device identification.
#[napi(object)]
pub struct ReadDeviceIdentificationOptions<'a> {
    /// Read device ID code (1=basic, 2=regular, 3=extended, 4=individual).
    pub read_device_id_code: u8,
    /// Starting object ID.
    pub object_id: u8,
    /// Optional abort signal to cancel the request.
    pub signal: Option<Object<'a>>,
}

/// Options for diagnostics request.
#[napi(object)]
pub struct DiagnosticsOptions<'a> {
    /// Diagnostic sub-function code.
    pub sub_function: u16,
    /// Data words for the request.
    pub data: Vec<u16>,
    /// Optional abort signal to cancel the request.
    pub signal: Option<Object<'a>>,
}

/// Response from diagnostics request.
#[napi(object)]
#[derive(Debug, Clone)]
pub struct DiagnosticsResponse {
    /// Echoed sub-function code.
    pub sub_function: u16,
    /// Response data words.
    pub data: Vec<u16>,
}

/// Device identification object.
#[napi(object)]
#[derive(Debug, Clone)]
pub struct DeviceIdentificationObject {
    /// Object ID.
    pub id: u8,
    /// Object value as string.
    pub value: String,
}

/// Response from device identification request.
#[napi(object)]
#[derive(Debug, Clone)]
pub struct DeviceIdentificationResponse {
    /// Conformity level.
    pub conformity_level: u8,
    /// Whether more objects follow.
    pub more_follows: bool,
    /// Next object ID if more follows.
    pub next_object_id: u8,
    /// Retrieved objects.
    pub objects: Vec<DeviceIdentificationObject>,
}

// ── AsyncTcpModbusClient ─────────────────────────────────────────────────────

/// Async Modbus TCP client.
///
/// All methods are async and return Promises. The client must be connected
/// before issuing Modbus requests.
#[napi]
pub struct AsyncTcpModbusClient {
    inner: Mutex<Option<Arc<AsyncTcpClient>>>,
    unit_id: u8,
}

#[napi]
impl AsyncTcpModbusClient {
    /// Creates and connects a new TCP client.
    ///
    /// @param opts - Connection options including host, port, unitId, and optional timeout.
    /// @returns A connected client instance.
    #[napi(factory)]
    pub async fn connect(opts: TcpClientOptions) -> Result<AsyncTcpModbusClient> {
        // Validate unit ID
        UnitIdOrSlaveAddr::new(opts.unit_id)
            .map_err(|e| to_napi_err(ERR_MODBUS_INVALID_ARGUMENT, e))?;

        let client = AsyncTcpClient::new(&opts.host, opts.port)
            .map_err(|e| to_napi_err(ERR_MODBUS_INVALID_ARGUMENT, e))?;

        client.connect().await.map_err(from_async_error)?;

        if let Some(timeout_ms) = opts.timeout_ms {
            client.set_request_timeout(Duration::from_millis(timeout_ms as u64));
        }

        Ok(AsyncTcpModbusClient {
            inner: Mutex::new(Some(Arc::new(client))),
            unit_id: opts.unit_id,
        })
    }

    fn get_client(&self) -> Result<Arc<AsyncTcpClient>> {
        let guard = self
            .inner
            .lock()
            .map_err(|_| napi::Error::new(Status::GenericFailure, "Failed to acquire lock"))?;
        guard
            .clone()
            .ok_or_else(|| napi::Error::new(Status::GenericFailure, "Client is closed"))
    }

    /// Sets the per-request timeout in milliseconds.
    #[napi]
    pub fn set_request_timeout(&self, timeout_ms: u32) -> Result<()> {
        let client = self.get_client()?;
        client.set_request_timeout(Duration::from_millis(timeout_ms as u64));
        Ok(())
    }

    /// Clears the per-request timeout.
    #[napi]
    pub fn clear_request_timeout(&self) -> Result<()> {
        let client = self.get_client()?;
        client.clear_request_timeout();
        Ok(())
    }

    /// Returns whether there are pending requests.
    #[napi(getter)]
    pub fn pending_requests(&self) -> Result<bool> {
        let client = self.get_client()?;
        Ok(client.has_pending_requests())
    }

    /// Closes the client connection.
    #[napi]
    pub async fn close(&self) -> Result<()> {
        let client = {
            let mut guard = self
                .inner
                .lock()
                .map_err(|_| napi::Error::new(Status::GenericFailure, "Failed to acquire lock"))?;
            guard.take()
        };
        if let Some(inner) = client {
            let _ = inner.disconnect().await;
        }
        Ok(())
    }

    /// Reconnects the client after a disconnect.
    #[napi]
    pub async fn reconnect(&self) -> Result<()> {
        let client = self.get_client()?;
        client.connect().await.map_err(from_async_error)
    }

    // ── Register methods ─────────────────────────────────────────────────────

    /// Reads holding registers (FC03).
    #[napi(ts_return_type = "Promise<number[]>")]
    #[cfg(feature = "registers")]
    pub fn read_holding_registers(
        &self,
        env: Env,
        opts: ReadRegistersOptions<'_>,
    ) -> Result<PromiseRaw<'static, Vec<u16>>> {
        let client = self.get_client()?;
        let abort_rx = crate::nodejs::errors::setup_abort_listener(&env, opts.signal)?;
        let unit_id = self.unit_id;
        let address = opts.address;
        let quantity = opts.quantity;

        let promise = env.spawn_future(async move {
            let fut = client.read_holding_registers(unit_id, address, quantity);
            let regs = if let Some(mut rx) = abort_rx {
                tokio::select! {
                    res = fut => { res.map_err(from_async_error)? }
                    _ = &mut rx => {
                        return Err(napi::Error::new(Status::Cancelled, "The operation was aborted."));
                    }
                }
            } else {
                fut.await.map_err(from_async_error)?
            };
            Ok(regs.values()[..regs.quantity() as usize].to_vec())
        })?;
        Ok(unsafe { extend_lifetime(promise) })
    }

    /// Reads input registers (FC04).
    #[napi(ts_return_type = "Promise<number[]>")]
    #[cfg(feature = "registers")]
    pub fn read_input_registers(
        &self,
        env: Env,
        opts: ReadRegistersOptions<'_>,
    ) -> Result<PromiseRaw<'static, Vec<u16>>> {
        let client = self.get_client()?;
        let abort_rx = crate::nodejs::errors::setup_abort_listener(&env, opts.signal)?;
        let unit_id = self.unit_id;
        let address = opts.address;
        let quantity = opts.quantity;

        let promise = env.spawn_future(async move {
            let fut = client.read_input_registers(unit_id, address, quantity);
            let regs = if let Some(mut rx) = abort_rx {
                tokio::select! {
                    res = fut => { res.map_err(from_async_error)? }
                    _ = &mut rx => {
                        return Err(napi::Error::new(Status::Cancelled, "The operation was aborted."));
                    }
                }
            } else {
                fut.await.map_err(from_async_error)?
            };
            Ok(regs.values()[..regs.quantity() as usize].to_vec())
        })?;
        Ok(unsafe { extend_lifetime(promise) })
    }

    /// Writes a single register (FC06).
    #[napi(ts_return_type = "Promise<void>")]
    #[cfg(feature = "registers")]
    pub fn write_single_register(
        &self,
        env: Env,
        opts: WriteSingleRegisterOptions<'_>,
    ) -> Result<PromiseRaw<'static, ()>> {
        let client = self.get_client()?;
        let abort_rx = crate::nodejs::errors::setup_abort_listener(&env, opts.signal)?;
        let unit_id = self.unit_id;
        let address = opts.address;
        let value = opts.value;

        let promise = env.spawn_future(async move {
            let fut = client.write_single_register(unit_id, address, value);
            if let Some(mut rx) = abort_rx {
                tokio::select! {
                    res = fut => { res.map_err(from_async_error)? }
                    _ = &mut rx => {
                        return Err(napi::Error::new(Status::Cancelled, "The operation was aborted."));
                    }
                }
            } else {
                fut.await.map_err(from_async_error)?
            };
            Ok(())
        })?;
        Ok(unsafe { extend_lifetime(promise) })
    }

    /// Writes multiple registers (FC16).
    #[napi(ts_return_type = "Promise<void>")]
    #[cfg(feature = "registers")]
    pub fn write_multiple_registers(
        &self,
        env: Env,
        opts: WriteMultipleRegistersOptions<'_>,
    ) -> Result<PromiseRaw<'static, ()>> {
        let client = self.get_client()?;
        let abort_rx = crate::nodejs::errors::setup_abort_listener(&env, opts.signal)?;
        let unit_id = self.unit_id;
        let address = opts.address;
        let values = opts.values;

        let promise = env.spawn_future(async move {
            let fut = client.write_multiple_registers(unit_id, address, &values);
            if let Some(mut rx) = abort_rx {
                tokio::select! {
                    res = fut => { res.map_err(from_async_error)? }
                    _ = &mut rx => {
                        return Err(napi::Error::new(Status::Cancelled, "The operation was aborted."));
                    }
                }
            } else {
                fut.await.map_err(from_async_error)?
            };
            Ok(())
        })?;
        Ok(unsafe { extend_lifetime(promise) })
    }

    /// Reads and writes multiple registers atomically (FC23).
    #[napi(ts_return_type = "Promise<number[]>")]
    #[cfg(feature = "registers")]
    pub fn read_write_multiple_registers(
        &self,
        env: Env,
        opts: ReadWriteMultipleRegistersOptions<'_>,
    ) -> Result<PromiseRaw<'static, Vec<u16>>> {
        let client = self.get_client()?;
        let abort_rx = crate::nodejs::errors::setup_abort_listener(&env, opts.signal)?;
        let unit_id = self.unit_id;
        let read_address = opts.read_address;
        let read_quantity = opts.read_quantity;
        let write_address = opts.write_address;
        let write_values = opts.write_values;

        let promise = env.spawn_future(async move {
            let fut = client.read_write_multiple_registers(
                unit_id,
                read_address,
                read_quantity,
                write_address,
                &write_values,
            );
            let regs = if let Some(mut rx) = abort_rx {
                tokio::select! {
                    res = fut => { res.map_err(from_async_error)? }
                    _ = &mut rx => {
                        return Err(napi::Error::new(Status::Cancelled, "The operation was aborted."));
                    }
                }
            } else {
                fut.await.map_err(from_async_error)?
            };
            Ok(regs.values()[..regs.quantity() as usize].to_vec())
        })?;
        Ok(unsafe { extend_lifetime(promise) })
    }

    // ── Coil methods ─────────────────────────────────────────────────────────

    /// Reads coils (FC01).
    #[napi(ts_return_type = "Promise<boolean[]>")]
    #[cfg(feature = "coils")]
    pub fn read_coils(
        &self,
        env: Env,
        opts: ReadBitsOptions<'_>,
    ) -> Result<PromiseRaw<'static, Vec<bool>>> {
        let client = self.get_client()?;
        let abort_rx = crate::nodejs::errors::setup_abort_listener(&env, opts.signal)?;
        let unit_id = self.unit_id;
        let address = opts.address;
        let quantity = opts.quantity;

        let promise = env.spawn_future(async move {
            let fut = client.read_multiple_coils(unit_id, address, quantity);
            let coils = if let Some(mut rx) = abort_rx {
                tokio::select! {
                    res = fut => { res.map_err(from_async_error)? }
                    _ = &mut rx => {
                        return Err(napi::Error::new(Status::Cancelled, "The operation was aborted."));
                    }
                }
            } else {
                fut.await.map_err(from_async_error)?
            };

            let mut result = Vec::with_capacity(quantity as usize);
            for i in 0..quantity {
                result.push(coils.value(address + i).unwrap_or(false));
            }
            Ok(result)
        })?;
        Ok(unsafe { extend_lifetime(promise) })
    }

    /// Writes a single coil (FC05).
    #[napi(ts_return_type = "Promise<void>")]
    #[cfg(feature = "coils")]
    pub fn write_single_coil(
        &self,
        env: Env,
        opts: WriteSingleCoilOptions<'_>,
    ) -> Result<PromiseRaw<'static, ()>> {
        let client = self.get_client()?;
        let abort_rx = crate::nodejs::errors::setup_abort_listener(&env, opts.signal)?;
        let unit_id = self.unit_id;
        let address = opts.address;
        let value = opts.value;

        let promise = env.spawn_future(async move {
            let fut = client.write_single_coil(unit_id, address, value);
            if let Some(mut rx) = abort_rx {
                tokio::select! {
                    res = fut => { res.map_err(from_async_error)? }
                    _ = &mut rx => {
                        return Err(napi::Error::new(Status::Cancelled, "The operation was aborted."));
                    }
                }
            } else {
                fut.await.map_err(from_async_error)?
            };
            Ok(())
        })?;
        Ok(unsafe { extend_lifetime(promise) })
    }

    /// Writes multiple coils (FC15).
    #[napi(ts_return_type = "Promise<void>")]
    #[cfg(feature = "coils")]
    pub fn write_multiple_coils(
        &self,
        env: Env,
        opts: WriteMultipleCoilsOptions<'_>,
    ) -> Result<PromiseRaw<'static, ()>> {
        use mbus_core::models::coil::Coils;

        let client = self.get_client()?;
        let abort_rx = crate::nodejs::errors::setup_abort_listener(&env, opts.signal)?;
        let unit_id = self.unit_id;
        let address = opts.address;
        let values = opts.values;

        // Build Coils from bool array synchronously
        let qty = values.len() as u16;
        let mut coils =
            Coils::new(address, qty).map_err(|e| to_napi_err(ERR_MODBUS_INVALID_ARGUMENT, e))?;

        for (i, &value) in values.iter().enumerate() {
            coils
                .set_value(address + i as u16, value)
                .map_err(|e| to_napi_err(ERR_MODBUS_INVALID_ARGUMENT, e))?;
        }

        let promise = env.spawn_future(async move {
            let fut = client.write_multiple_coils(unit_id, address, &coils);
            if let Some(mut rx) = abort_rx {
                tokio::select! {
                    res = fut => { res.map_err(from_async_error)? }
                    _ = &mut rx => {
                        return Err(napi::Error::new(Status::Cancelled, "The operation was aborted."));
                    }
                }
            } else {
                fut.await.map_err(from_async_error)?
            };
            Ok(())
        })?;
        Ok(unsafe { extend_lifetime(promise) })
    }

    // ── Discrete inputs ──────────────────────────────────────────────────────

    /// Reads discrete inputs (FC02).
    #[napi(ts_return_type = "Promise<boolean[]>")]
    #[cfg(feature = "discrete-inputs")]
    pub fn read_discrete_inputs(
        &self,
        env: Env,
        opts: ReadBitsOptions<'_>,
    ) -> Result<PromiseRaw<'static, Vec<bool>>> {
        let client = self.get_client()?;
        let abort_rx = crate::nodejs::errors::setup_abort_listener(&env, opts.signal)?;
        let unit_id = self.unit_id;
        let address = opts.address;
        let quantity = opts.quantity;

        let promise = env.spawn_future(async move {
            let fut = client.read_discrete_inputs(unit_id, address, quantity);
            let inputs = if let Some(mut rx) = abort_rx {
                tokio::select! {
                    res = fut => { res.map_err(from_async_error)? }
                    _ = &mut rx => {
                        return Err(napi::Error::new(Status::Cancelled, "The operation was aborted."));
                    }
                }
            } else {
                fut.await.map_err(from_async_error)?
            };

            let mut result = Vec::with_capacity(quantity as usize);
            for i in 0..quantity {
                result.push(inputs.value(address + i).unwrap_or(false));
            }
            Ok(result)
        })?;
        Ok(unsafe { extend_lifetime(promise) })
    }

    // ── FIFO ─────────────────────────────────────────────────────────────────

    /// Reads FIFO queue (FC24).
    #[napi(ts_return_type = "Promise<FifoQueueResponse>")]
    #[cfg(feature = "fifo")]
    pub fn read_fifo_queue(
        &self,
        env: Env,
        opts: ReadFifoQueueOptions<'_>,
    ) -> Result<PromiseRaw<'static, FifoQueueResponse>> {
        let client = self.get_client()?;
        let abort_rx = crate::nodejs::errors::setup_abort_listener(&env, opts.signal)?;
        let unit_id = self.unit_id;
        let address = opts.address;

        let promise = env.spawn_future(async move {
            let fut = client.read_fifo_queue(unit_id, address);
            let fifo = if let Some(mut rx) = abort_rx {
                tokio::select! {
                    res = fut => { res.map_err(from_async_error)? }
                    _ = &mut rx => {
                        return Err(napi::Error::new(Status::Cancelled, "The operation was aborted."));
                    }
                }
            } else {
                fut.await.map_err(from_async_error)?
            };
            let values = fifo.queue().to_vec();
            let count = values.len() as u16;
            Ok(FifoQueueResponse { count, values })
        })?;
        Ok(unsafe { extend_lifetime(promise) })
    }

    // ── File record ──────────────────────────────────────────────────────────

    /// Reads file records (FC20).
    #[napi(ts_return_type = "Promise<number[][]>")]
    #[cfg(feature = "file-record")]
    pub fn read_file_record(
        &self,
        env: Env,
        opts: ReadFileRecordOptions<'_>,
    ) -> Result<PromiseRaw<'static, Vec<Vec<u16>>>> {
        let client = self.get_client()?;
        let abort_rx = crate::nodejs::errors::setup_abort_listener(&env, opts.signal)?;
        let unit_id = self.unit_id;

        // Build SubRequest from options
        let mut sub_request = SubRequest::new();
        for req in &opts.requests {
            sub_request
                .add_read_sub_request(req.file_number, req.record_number, req.record_length)
                .map_err(|e| {
                    napi::Error::new(Status::InvalidArg, format!("File record error: {:?}", e))
                })?;
        }

        let promise = env.spawn_future(async move {
            let fut = client.read_file_record(unit_id, &sub_request);
            let result = if let Some(mut rx) = abort_rx {
                tokio::select! {
                    res = fut => { res.map_err(from_async_error)? }
                    _ = &mut rx => {
                        return Err(napi::Error::new(Status::Cancelled, "The operation was aborted."));
                    }
                }
            } else {
                fut.await.map_err(from_async_error)?
            };

            // Convert each sub-response to Vec<u16>
            let mut output: Vec<Vec<u16>> = Vec::new();
            for params in result {
                let words: Vec<u16> = params
                    .record_data
                    .map(|v| v.into_iter().collect())
                    .unwrap_or_default();
                output.push(words);
            }
            Ok(output)
        })?;
        Ok(unsafe { extend_lifetime(promise) })
    }

    /// Writes file records (FC21).
    #[napi(ts_return_type = "Promise<void>")]
    #[cfg(feature = "file-record")]
    pub fn write_file_record(
        &self,
        env: Env,
        opts: WriteFileRecordOptions<'_>,
    ) -> Result<PromiseRaw<'static, ()>> {
        use mbus_core::data_unit::common::MAX_PDU_DATA_LEN;

        let client = self.get_client()?;
        let abort_rx = crate::nodejs::errors::setup_abort_listener(&env, opts.signal)?;
        let unit_id = self.unit_id;

        // Build SubRequest with data
        let mut sub_request = SubRequest::new();
        for req in &opts.requests {
            let record_data: heapless::Vec<u16, MAX_PDU_DATA_LEN> =
                heapless::Vec::from_slice(&req.record_data)
                    .map_err(|_| napi::Error::new(Status::InvalidArg, "Record data too large"))?;

            sub_request
                .add_write_sub_request(
                    req.file_number,
                    req.record_number,
                    req.record_data.len() as u16,
                    record_data,
                )
                .map_err(|e| {
                    napi::Error::new(Status::InvalidArg, format!("File record error: {:?}", e))
                })?;
        }

        let promise = env.spawn_future(async move {
            let fut = client.write_file_record(unit_id, &sub_request);
            if let Some(mut rx) = abort_rx {
                tokio::select! {
                    res = fut => { res.map_err(from_async_error)? }
                    _ = &mut rx => {
                        return Err(napi::Error::new(Status::Cancelled, "The operation was aborted."));
                    }
                }
            } else {
                fut.await.map_err(from_async_error)?
            };
            Ok(())
        })?;
        Ok(unsafe { extend_lifetime(promise) })
    }

    // ── Diagnostics ──────────────────────────────────────────────────────────

    /// Reads exception status (FC07).
    #[napi]
    #[cfg(feature = "diagnostics")]
    pub async fn read_exception_status(&self) -> Result<u8> {
        let client = self.get_client()?;
        client
            .read_exception_status(self.unit_id)
            .await
            .map_err(from_async_error)
    }

    /// Sends a diagnostics request (FC08).
    #[napi(ts_return_type = "Promise<DiagnosticsResponse>")]
    #[cfg(feature = "diagnostics")]
    pub fn diagnostics(
        &self,
        env: Env,
        opts: DiagnosticsOptions<'_>,
    ) -> Result<PromiseRaw<'static, DiagnosticsResponse>> {
        let client = self.get_client()?;
        let abort_rx = crate::nodejs::errors::setup_abort_listener(&env, opts.signal)?;
        let unit_id = self.unit_id;

        let sub_function = DiagnosticSubFunction::try_from(opts.sub_function).map_err(|_| {
            napi::Error::new(
                Status::InvalidArg,
                format!(
                    "Invalid diagnostic sub-function code: {}",
                    opts.sub_function
                ),
            )
        })?;
        let data = opts.data;

        let promise = env.spawn_future(async move {
            let fut = client.diagnostics(unit_id, sub_function, &data);
            let result = if let Some(mut rx) = abort_rx {
                tokio::select! {
                    res = fut => { res.map_err(from_async_error)? }
                    _ = &mut rx => {
                        return Err(napi::Error::new(Status::Cancelled, "The operation was aborted."));
                    }
                }
            } else {
                fut.await.map_err(from_async_error)?
            };

            Ok(DiagnosticsResponse {
                sub_function: u16::from(result.sub_function),
                data: result.data,
            })
        })?;
        Ok(unsafe { extend_lifetime(promise) })
    }

    /// Reads device identification (FC43/MEI14).
    #[napi(ts_return_type = "Promise<DeviceIdentificationResponse>")]
    #[cfg(feature = "diagnostics")]
    pub fn read_device_identification(
        &self,
        env: Env,
        opts: ReadDeviceIdentificationOptions<'_>,
    ) -> Result<PromiseRaw<'static, DeviceIdentificationResponse>> {
        use mbus_core::models::diagnostic::ConformityLevel;

        let client = self.get_client()?;
        let abort_rx = crate::nodejs::errors::setup_abort_listener(&env, opts.signal)?;
        let unit_id = self.unit_id;

        let read_device_id_code =
            ReadDeviceIdCode::try_from(opts.read_device_id_code).map_err(|_| {
                napi::Error::new(
                    Status::InvalidArg,
                    format!("Invalid read device ID code: {}", opts.read_device_id_code),
                )
            })?;
        let object_id = ObjectId::from(opts.object_id);

        let promise = env.spawn_future(async move {
            let fut = client.read_device_identification(unit_id, read_device_id_code, object_id);
            let result = if let Some(mut rx) = abort_rx {
                tokio::select! {
                    res = fut => { res.map_err(from_async_error)? }
                    _ = &mut rx => {
                        return Err(napi::Error::new(Status::Cancelled, "The operation was aborted."));
                    }
                }
            } else {
                fut.await.map_err(from_async_error)?
            };

            let objects: Vec<DeviceIdentificationObject> = result
                .objects()
                .filter_map(|obj_result| obj_result.ok())
                .map(|obj| DeviceIdentificationObject {
                    id: u8::from(obj.object_id),
                    value: String::from_utf8_lossy(&obj.value).to_string(),
                })
                .collect();

            let conformity_level: u8 = match result.conformity_level {
                ConformityLevel::BasicStreamOnly => 0x01,
                ConformityLevel::RegularStreamOnly => 0x02,
                ConformityLevel::ExtendedStreamOnly => 0x03,
                ConformityLevel::BasicStreamAndIndividual => 0x81,
                ConformityLevel::RegularStreamAndIndividual => 0x82,
                ConformityLevel::ExtendedStreamAndIndividual => 0x83,
            };

            Ok(DeviceIdentificationResponse {
                conformity_level,
                more_follows: result.more_follows,
                next_object_id: u8::from(result.next_object_id),
                objects,
            })
        })?;
        Ok(unsafe { extend_lifetime(promise) })
    }
}