plc-comm-hostlink-rust 0.1.3

Async Rust Host Link client based on plc-comm-hostlink-dotnet
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
use encoding_rs::SHIFT_JIS;
use futures_util::{StreamExt, pin_mut};
use plc_comm_hostlink::{
    HostLinkClient, HostLinkConnectionOptions, HostLinkTransportMode, HostLinkValue,
    open_and_connect, read_comments, read_dwords_chunked, read_typed, write_dwords_chunked,
};
use std::sync::{Arc, Mutex};
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::{TcpListener, UdpSocket};

#[tokio::test]
async fn read_named_batches_contiguous_word_reads() {
    let (port, received) = start_scripted_server(|command| match command.as_str() {
        "RDS DM100.U 8" => "1025 65535 2 1 57920 1 0 16712".to_owned(),
        _ => "E1".to_owned(),
    })
    .await;

    let mut options = HostLinkConnectionOptions::new("127.0.0.1");
    options.port = port;
    let client = HostLinkClient::connect(options).await.unwrap();

    let result = client
        .read_named(&[
            "DM100", "DM100.0", "DM100.A", "DM101:S", "DM102:D", "DM104:L", "DM106:F",
        ])
        .await
        .unwrap();

    assert_eq!(result["DM100"], HostLinkValue::U16(1025));
    assert_eq!(result["DM100.0"], HostLinkValue::Bool(true));
    assert_eq!(result["DM100.A"], HostLinkValue::Bool(true));
    assert_eq!(result["DM101:S"], HostLinkValue::I16(-1));
    assert_eq!(result["DM102:D"], HostLinkValue::U32(65_538));
    assert_eq!(result["DM104:L"], HostLinkValue::I32(123_456));
    assert_eq!(result["DM106:F"], HostLinkValue::F32(12.5));

    assert_eq!(
        received.lock().unwrap().drain(..).collect::<Vec<_>>(),
        vec!["RDS DM100.U 8"]
    );
}

#[tokio::test]
async fn udp_send_raw_accepts_large_datagram_response() {
    let socket = UdpSocket::bind("127.0.0.1:0").await.unwrap();
    let port = socket.local_addr().unwrap().port();
    tokio::spawn(async move {
        let mut request = vec![0u8; 1024];
        let (_read, peer) = socket.recv_from(&mut request).await.unwrap();
        let mut response = "7".repeat(5000).into_bytes();
        response.extend_from_slice(b"\r\n");
        socket.send_to(&response, peer).await.unwrap();
    });

    let mut options = HostLinkConnectionOptions::new("127.0.0.1");
    options.transport = HostLinkTransportMode::Udp;
    options.port = port;
    let client = HostLinkClient::connect(options).await.unwrap();

    let response = client.send_raw("LARGE").await.unwrap();

    assert_eq!(response.len(), 5000);
    assert!(response.chars().all(|ch| ch == '7'));
}

#[tokio::test]
async fn read_typed_and_write_typed_support_float_suffix() {
    let (port, received) = start_scripted_server(|command| match command.as_str() {
        "RDS DM200.U 2" => "0 16712".to_owned(),
        "WRS DM200.U 2 0 16712" => "OK".to_owned(),
        _ => "E1".to_owned(),
    })
    .await;

    let mut options = HostLinkConnectionOptions::new("127.0.0.1");
    options.port = port;
    let client = HostLinkClient::connect(options).await.unwrap();

    let value = read_typed(&client, "DM200", "F").await.unwrap();
    client.write_typed("DM200", "F", 12.5f32).await.unwrap();

    assert_eq!(value, HostLinkValue::F32(12.5));
    assert_eq!(
        received.lock().unwrap().drain(..).collect::<Vec<_>>(),
        vec!["RDS DM200.U 2", "WRS DM200.U 2 0 16712"]
    );
}

#[tokio::test]
async fn read_typed_timer_counter_composite_read_returns_set_value() {
    let (port, received) = start_scripted_server(|command| match command.as_str() {
        "RD T0.D" => "0,0000000010,0000000020".to_owned(),
        _ => "E1".to_owned(),
    })
    .await;

    let mut options = HostLinkConnectionOptions::new("127.0.0.1");
    options.port = port;
    let client = HostLinkClient::connect(options).await.unwrap();

    let value = read_typed(&client, "T0", "D").await.unwrap();

    assert_eq!(value, HostLinkValue::U32(20));
    assert_eq!(
        received.lock().unwrap().drain(..).collect::<Vec<_>>(),
        vec!["RD T0.D"]
    );
}

#[tokio::test]
async fn read_named_timer_counter_composite_read_returns_set_value() {
    let (port, received) = start_scripted_server(|command| match command.as_str() {
        "RD T10.D" => "0,0000000010,0000000020".to_owned(),
        "RD C10.D" => "0,0000000000,0000000030".to_owned(),
        _ => "E1".to_owned(),
    })
    .await;

    let mut options = HostLinkConnectionOptions::new("127.0.0.1");
    options.port = port;
    let client = HostLinkClient::connect(options).await.unwrap();

    let result = client.read_named(&["T10", "C10"]).await.unwrap();

    assert_eq!(result["T10"], HostLinkValue::U32(20));
    assert_eq!(result["C10"], HostLinkValue::U32(30));
    assert_eq!(
        received.lock().unwrap().drain(..).collect::<Vec<_>>(),
        vec!["RD T10.D", "RD C10.D"]
    );
}

#[tokio::test]
async fn read_timer_counter_returns_status_current_and_preset() {
    let (port, received) = start_scripted_server(|command| match command.as_str() {
        "RD T10.D" => "1,0000000010,0000000020".to_owned(),
        _ => "E1".to_owned(),
    })
    .await;

    let mut options = HostLinkConnectionOptions::new("127.0.0.1");
    options.port = port;
    let client = HostLinkClient::connect(options).await.unwrap();

    let result = client.read_timer_counter("T10").await.unwrap();

    assert_eq!(result.status, 1);
    assert_eq!(result.current, 10);
    assert_eq!(result.preset, 20);
    assert_eq!(
        received.lock().unwrap().drain(..).collect::<Vec<_>>(),
        vec!["RD T10.D"]
    );
}

#[tokio::test]
async fn read_named_direct_bits_use_unsuffixed_rd_commands() {
    let (port, received) = start_scripted_server(|command| match command.as_str() {
        "RDS R000 1" => "1".to_owned(),
        "RDS CR000 1" => "0".to_owned(),
        _ => "E1".to_owned(),
    })
    .await;

    let mut options = HostLinkConnectionOptions::new("127.0.0.1");
    options.port = port;
    let client = HostLinkClient::connect(options).await.unwrap();

    let result = client.read_named(&["R0", "CR0"]).await.unwrap();
    assert_eq!(result["R0"], HostLinkValue::Bool(true));
    assert_eq!(result["CR0"], HostLinkValue::Bool(false));
    assert_eq!(
        received.lock().unwrap().drain(..).collect::<Vec<_>>(),
        vec!["RDS R000 1", "RDS CR000 1"]
    );
}

#[tokio::test]
async fn read_named_batches_xym_direct_bits_with_hostlink_notation() {
    let (port, received) = start_scripted_server(|command| match command.as_str() {
        "RDS X100 2" => "1 0".to_owned(),
        _ => "E1".to_owned(),
    })
    .await;

    let mut options = HostLinkConnectionOptions::new("127.0.0.1");
    options.port = port;
    let client = HostLinkClient::connect(options).await.unwrap();

    let result = client.read_named(&["X100", "X101"]).await.unwrap();
    assert_eq!(result["X100"], HostLinkValue::Bool(true));
    assert_eq!(result["X101"], HostLinkValue::Bool(false));
    assert_eq!(
        received.lock().unwrap().drain(..).collect::<Vec<_>>(),
        vec!["RDS X100 2"]
    );
}

#[tokio::test]
async fn read_named_batches_contiguous_direct_bit_reads() {
    let (port, received) = start_scripted_server(|command| match command.as_str() {
        "RDS R000 4" => "1 0 1 0".to_owned(),
        "RDS CR000 4" => "0 1 0 1".to_owned(),
        _ => "E1".to_owned(),
    })
    .await;

    let mut options = HostLinkConnectionOptions::new("127.0.0.1");
    options.port = port;
    let client = HostLinkClient::connect(options).await.unwrap();

    let result = client
        .read_named(&["R0", "R1", "R2", "R3", "CR0", "CR1", "CR2", "CR3"])
        .await
        .unwrap();

    assert_eq!(result["R0"], HostLinkValue::Bool(true));
    assert_eq!(result["R1"], HostLinkValue::Bool(false));
    assert_eq!(result["R2"], HostLinkValue::Bool(true));
    assert_eq!(result["R3"], HostLinkValue::Bool(false));
    assert_eq!(result["CR0"], HostLinkValue::Bool(false));
    assert_eq!(result["CR1"], HostLinkValue::Bool(true));
    assert_eq!(result["CR2"], HostLinkValue::Bool(false));
    assert_eq!(result["CR3"], HostLinkValue::Bool(true));
    assert_eq!(
        received.lock().unwrap().drain(..).collect::<Vec<_>>(),
        vec!["RDS R000 4", "RDS CR000 4"]
    );
}

#[tokio::test]
async fn read_named_batches_bit_bank_direct_bits_across_display_bank_boundary() {
    let (port, received) = start_scripted_server(|command| match command.as_str() {
        "RDS CR3614 4" => "0 1 0 1".to_owned(),
        _ => "E1".to_owned(),
    })
    .await;

    let mut options = HostLinkConnectionOptions::new("127.0.0.1");
    options.port = port;
    let client = HostLinkClient::connect(options).await.unwrap();

    let result = client
        .read_named(&["CR3614", "CR3615", "CR3700", "CR3701"])
        .await
        .unwrap();

    assert_eq!(result["CR3614"], HostLinkValue::Bool(false));
    assert_eq!(result["CR3615"], HostLinkValue::Bool(true));
    assert_eq!(result["CR3700"], HostLinkValue::Bool(false));
    assert_eq!(result["CR3701"], HostLinkValue::Bool(true));
    assert_eq!(
        received.lock().unwrap().drain(..).collect::<Vec<_>>(),
        vec!["RDS CR3614 4"]
    );
}

#[tokio::test]
async fn read_typed_empty_dtype_uses_device_default_format() {
    let (port, received) = start_scripted_server(|command| match command.as_str() {
        "RD CR000" => "1".to_owned(),
        "RD DM200.S" => "-12".to_owned(),
        _ => "E1".to_owned(),
    })
    .await;

    let mut options = HostLinkConnectionOptions::new("127.0.0.1");
    options.port = port;
    let client = HostLinkClient::connect(options).await.unwrap();

    assert_eq!(
        read_typed(&client, "CR0", "").await.unwrap(),
        HostLinkValue::Bool(true)
    );
    assert_eq!(
        read_typed(&client, "DM200.S", "").await.unwrap(),
        HostLinkValue::I16(-12)
    );
    assert_eq!(
        received.lock().unwrap().drain(..).collect::<Vec<_>>(),
        vec!["RD CR000", "RD DM200.S"]
    );
}

#[tokio::test]
async fn read_comments_helper_and_named_snapshot_support_comment_values() {
    let (port, received) = start_scripted_server(|command| match command.as_str() {
        "RDC DM150" => "MAIN COMMENT                    ".to_owned(),
        "RD DM100.U" => "321".to_owned(),
        "RDC DM101" => "ALARM COMMENT                   ".to_owned(),
        _ => "E1".to_owned(),
    })
    .await;

    let mut options = HostLinkConnectionOptions::new("127.0.0.1");
    options.port = port;
    let client = HostLinkClient::connect(options).await.unwrap();

    let comment = read_comments(&client, "DM150", true).await.unwrap();
    assert_eq!(comment, "MAIN COMMENT");

    let result = client
        .read_named(&["DM100", "DM101:COMMENT"])
        .await
        .unwrap();
    assert_eq!(result["DM100"], HostLinkValue::U16(321));
    assert_eq!(
        result["DM101:COMMENT"],
        HostLinkValue::Text("ALARM COMMENT".to_owned())
    );
    assert_eq!(
        received.lock().unwrap().drain(..).collect::<Vec<_>>(),
        vec!["RDC DM150", "RD DM100.U", "RDC DM101"]
    );
}

#[tokio::test]
async fn read_comments_decodes_shift_jis_payloads() {
    let (port, received) = start_scripted_server_bytes(|command| match command.as_str() {
        "RDC DM20" => {
            let expected = "\u{904b}\u{8ee2}\u{8a31}\u{53ef}";
            let (encoded, _, _) = SHIFT_JIS.encode(expected);
            let mut bytes = encoded.into_owned();
            bytes.extend_from_slice(b"                    ");
            bytes
        }
        _ => b"E1".to_vec(),
    })
    .await;

    let mut options = HostLinkConnectionOptions::new("127.0.0.1");
    options.port = port;
    let client = HostLinkClient::connect(options).await.unwrap();

    let comment = read_comments(&client, "DM20", true).await.unwrap();

    assert_eq!(comment, "\u{904b}\u{8ee2}\u{8a31}\u{53ef}");
    assert_eq!(
        received.lock().unwrap().drain(..).collect::<Vec<_>>(),
        vec!["RDC DM20"]
    );
}

#[tokio::test]
async fn at_write_is_rejected_before_opening_connection() {
    let client = HostLinkClient::new(HostLinkConnectionOptions::new("127.0.0.1"));

    assert!(client.write("AT0", 3533, Some("D")).await.is_err());
    assert!(
        client
            .write_consecutive("AT0", &[3533, 5543], Some("D"))
            .await
            .is_err()
    );
}

#[tokio::test]
async fn open_and_connect_returns_queued_client_that_uses_helper_api() {
    let (port, received) = start_scripted_server(|command| match command.as_str() {
        "RD DM10.U" => "123".to_owned(),
        _ => "E1".to_owned(),
    })
    .await;

    let mut options = HostLinkConnectionOptions::new("127.0.0.1");
    options.port = port;
    let client = open_and_connect(options).await.unwrap();
    let value = client.read_typed("DM10", "U").await.unwrap();

    assert!(client.is_open().await);
    assert_eq!(value, HostLinkValue::U16(123));
    assert_eq!(
        received.lock().unwrap().drain(..).collect::<Vec<_>>(),
        vec!["RD DM10.U"]
    );
}

#[tokio::test]
async fn queued_client_supports_read_comments() {
    let (port, received) = start_scripted_server(|command| match command.as_str() {
        "RDC DM10" => "ALARM TEXT                      ".to_owned(),
        _ => "E1".to_owned(),
    })
    .await;

    let mut options = HostLinkConnectionOptions::new("127.0.0.1");
    options.port = port;
    let client = open_and_connect(options).await.unwrap();
    let comment = client.read_comments("DM10", true).await.unwrap();

    assert_eq!(comment, "ALARM TEXT");
    assert_eq!(
        received.lock().unwrap().drain(..).collect::<Vec<_>>(),
        vec!["RDC DM10"]
    );
}

#[tokio::test]
async fn read_comments_accepts_xym_alias_device_types() {
    let (port, received) = start_scripted_server(|command| match command.as_str() {
        "RDC D10" => "DM COMMENT                      ".to_owned(),
        "RDC M20" => "MR COMMENT                      ".to_owned(),
        _ => "E1".to_owned(),
    })
    .await;

    let mut options = HostLinkConnectionOptions::new("127.0.0.1");
    options.port = port;
    let client = HostLinkClient::connect(options).await.unwrap();
    let data_memory_comment = client.read_comments("D10", true).await.unwrap();
    let auxiliary_relay_comment = client.read_comments("M20", true).await.unwrap();

    assert_eq!(data_memory_comment, "DM COMMENT");
    assert_eq!(auxiliary_relay_comment, "MR COMMENT");
    assert_eq!(
        received.lock().unwrap().drain(..).collect::<Vec<_>>(),
        vec!["RDC D10", "RDC M20"]
    );
}

#[tokio::test]
async fn poll_reuses_compiled_plan_for_each_cycle() {
    let responses = Arc::new(Mutex::new(0usize));
    let state = Arc::clone(&responses);
    let (port, received) = start_scripted_server(move |command| {
        assert_eq!(command, "RDS DM100.U 3");
        let mut counter = state.lock().unwrap();
        let response = if *counter == 0 {
            "1 0 16320"
        } else {
            "3 0 16416"
        };
        *counter += 1;
        response.to_owned()
    })
    .await;

    let mut options = HostLinkConnectionOptions::new("127.0.0.1");
    options.port = port;
    let client = HostLinkClient::connect(options).await.unwrap();

    let stream = plc_comm_hostlink::poll(
        &client,
        &["DM100", "DM100.0", "DM101:F"],
        std::time::Duration::from_millis(1),
    );
    pin_mut!(stream);
    let first = stream.next().await.unwrap().unwrap();
    let second = stream.next().await.unwrap().unwrap();

    assert_eq!(first["DM100"], HostLinkValue::U16(1));
    assert_eq!(first["DM100.0"], HostLinkValue::Bool(true));
    assert_eq!(first["DM101:F"], HostLinkValue::F32(1.5));
    assert_eq!(second["DM100"], HostLinkValue::U16(3));
    assert_eq!(second["DM100.0"], HostLinkValue::Bool(true));
    assert_eq!(second["DM101:F"], HostLinkValue::F32(2.5));
    assert_eq!(
        received.lock().unwrap().drain(..).collect::<Vec<_>>(),
        vec!["RDS DM100.U 3", "RDS DM100.U 3"]
    );
}

#[tokio::test]
async fn read_dwords_chunked_advances_by_whole_dword_boundaries() {
    let (port, received) = start_scripted_server(|command| match command.as_str() {
        "RDS DM200.U 2" => "1 1".to_owned(),
        "RDS DM202.U 2" => "2 2".to_owned(),
        "RDS DM204.U 2" => "3 3".to_owned(),
        _ => "E1".to_owned(),
    })
    .await;

    let mut options = HostLinkConnectionOptions::new("127.0.0.1");
    options.port = port;
    let client = HostLinkClient::connect(options).await.unwrap();
    let values = read_dwords_chunked(&client, "DM200", 3, 1).await.unwrap();

    assert_eq!(values, vec![65_537, 131_074, 196_611]);
    assert_eq!(
        received.lock().unwrap().drain(..).collect::<Vec<_>>(),
        vec!["RDS DM200.U 2", "RDS DM202.U 2", "RDS DM204.U 2"]
    );
}

#[tokio::test]
async fn write_dwords_chunked_advances_by_whole_dword_boundaries() {
    let (port, received) = start_scripted_server(|command| match command.as_str() {
        "WRS DM200.U 2 1 1" => "OK".to_owned(),
        "WRS DM202.U 2 2 2" => "OK".to_owned(),
        "WRS DM204.U 2 3 3" => "OK".to_owned(),
        _ => "E1".to_owned(),
    })
    .await;

    let mut options = HostLinkConnectionOptions::new("127.0.0.1");
    options.port = port;
    let client = HostLinkClient::connect(options).await.unwrap();
    write_dwords_chunked(&client, "DM200", &[65_537, 131_074, 196_611], 1)
        .await
        .unwrap();

    assert_eq!(
        received.lock().unwrap().drain(..).collect::<Vec<_>>(),
        vec![
            "WRS DM200.U 2 1 1",
            "WRS DM202.U 2 2 2",
            "WRS DM204.U 2 3 3"
        ]
    );
}

#[tokio::test]
async fn read_rejects_32_bit_device_end_crossing_before_send() {
    let (port, received) = start_scripted_server(|_| "OK".to_owned()).await;

    let mut options = HostLinkConnectionOptions::new("127.0.0.1");
    options.port = port;
    let client = HostLinkClient::connect(options).await.unwrap();
    let error = read_typed(&client, "DM65534", "D").await.unwrap_err();

    assert!(error.to_string().contains("Device span out of range"));
    assert!(received.lock().unwrap().is_empty());
}

#[tokio::test]
async fn expansion_unit_buffer_uses_address_suffix_command_form() {
    let (port, received) = start_scripted_server(|command| match command.as_str() {
        "URD 01 100.U 2" => "123 456".to_owned(),
        "UWR 02 200.S 2 7 8" => "OK".to_owned(),
        _ => "E1".to_owned(),
    })
    .await;

    let mut options = HostLinkConnectionOptions::new("127.0.0.1");
    options.port = port;
    let client = HostLinkClient::connect(options).await.unwrap();

    let values = client
        .read_expansion_unit_buffer(1, 100, 2, None)
        .await
        .unwrap();
    client
        .write_expansion_unit_buffer(2, 200, &[7_i16, 8_i16], Some("S"))
        .await
        .unwrap();

    assert_eq!(values, vec!["123".to_owned(), "456".to_owned()]);
    assert_eq!(
        received.lock().unwrap().drain(..).collect::<Vec<_>>(),
        vec!["URD 01 100.U 2", "UWR 02 200.S 2 7 8"]
    );
}

#[tokio::test]
async fn read_expansion_unit_buffer_rejects_32_bit_buffer_end_crossing_before_send() {
    let (port, received) = start_scripted_server(|_| "OK".to_owned()).await;

    let mut options = HostLinkConnectionOptions::new("127.0.0.1");
    options.port = port;
    let client = HostLinkClient::connect(options).await.unwrap();
    let error = client
        .read_expansion_unit_buffer(1, 59_999, 1, Some("D"))
        .await
        .unwrap_err();

    assert!(
        error
            .to_string()
            .contains("Expansion buffer span out of range")
    );
    assert!(received.lock().unwrap().is_empty());
}

#[tokio::test]
async fn read_device_range_catalog_resolves_query_model_into_range_catalog() {
    let (port, received) = start_scripted_server(|command| match command.as_str() {
        "?K" => "58".to_owned(),
        _ => "E1".to_owned(),
    })
    .await;

    let mut options = HostLinkConnectionOptions::new("127.0.0.1");
    options.port = port;
    let client = HostLinkClient::connect(options).await.unwrap();
    let catalog = client.read_device_range_catalog().await.unwrap();

    assert_eq!(catalog.model, "KV-8000");
    assert_eq!(catalog.model_code, "58");
    assert!(catalog.has_model_code);
    assert_eq!(catalog.requested_model, "KV-8000A");
    assert_eq!(catalog.resolved_model, "KV-8000");
    assert_eq!(
        catalog.entry("DM").unwrap().address_range.as_deref(),
        Some("DM00000-DM65534")
    );
    assert_eq!(
        received.lock().unwrap().drain(..).collect::<Vec<_>>(),
        vec!["?K"]
    );
}

async fn start_scripted_server<F>(response_factory: F) -> (u16, Arc<Mutex<Vec<String>>>)
where
    F: Fn(String) -> String + Send + Sync + 'static,
{
    start_scripted_server_bytes(move |command| response_factory(command).into_bytes()).await
}

async fn start_scripted_server_bytes<F>(response_factory: F) -> (u16, Arc<Mutex<Vec<String>>>)
where
    F: Fn(String) -> Vec<u8> + Send + Sync + 'static,
{
    let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
    let port = listener.local_addr().unwrap().port();
    let received = Arc::new(Mutex::new(Vec::new()));
    let queue = Arc::clone(&received);
    let response_factory = Arc::new(response_factory);

    tokio::spawn(async move {
        let (mut stream, _) = listener.accept().await.unwrap();
        let mut buffer = [0u8; 4096];
        let mut partial = Vec::new();
        loop {
            let read = stream.read(&mut buffer).await.unwrap();
            if read == 0 {
                break;
            }
            for byte in &buffer[..read] {
                if matches!(byte, b'\r' | b'\n') {
                    if partial.is_empty() {
                        continue;
                    }
                    let command = String::from_utf8(std::mem::take(&mut partial)).unwrap();
                    queue.lock().unwrap().push(command.clone());
                    let response = response_factory(command);
                    let mut frame = response;
                    frame.extend_from_slice(b"\r\n");
                    stream.write_all(&frame).await.unwrap();
                } else {
                    partial.push(*byte);
                }
            }
        }
    });
    (port, received)
}