qslib 0.14.0

QSlib QuantStudio qPCR machine library
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
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
use env_logger::Builder;
use log::{debug, error, info, warn};
use qslib::parser::{MessageResponse, Value};
use rustls::ServerConfig;
use rustls_pki_types::pem::PemObject;
use std::net::SocketAddr;
use std::sync::Arc;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::TcpListener;
use tokio::time::{interval, Duration};
use tokio_rustls::TlsAcceptor;
use tokio_stream::StreamExt;

use qslib::com::*;
use qslib::commands::*;

fn setup_logging() {
    let _ = Builder::from_env("RUST_LOG")
        .format_timestamp_millis()
        .is_test(true)
        .try_init();
}

async fn setup_mock_server(
    port: Option<u16>,
    stay_open: bool,
) -> (SocketAddr, tokio::task::JoinHandle<()>) {
    // Bind to a random available port
    let listener = TcpListener::bind(format!("127.0.0.1:{}", port.unwrap_or(0)))
        .await
        .unwrap();
    let addr = listener.local_addr().unwrap();
    info!("Mock server listening on {}", addr);

    // Spawn server task
    let handle = tokio::spawn(async move {
        let mut power_status = true; // Start with power ON

        loop {
            let (mut socket, _) = listener.accept().await.unwrap();

            // Send ready message
            let ready_msg = "READy -session=474800 -product=QuantStudio3_5 -version=1.3.0 -build=001 -capabilities=Index\n";
            socket.write_all(ready_msg.as_bytes()).await.unwrap();

            // Create a periodic timer for log messages
            let mut interval = interval(Duration::from_millis(100));

            // Buffer for accumulating partial lines
            let mut line_buffer = String::new();
            let mut buf = [0; 1024];

            loop {
                tokio::select! {
                    _ = interval.tick() => {
                        // First send a log message that won't be read
                        let log_msg = "MESSage NonStatus Test status message\n";
                        if socket.write_all(log_msg.as_bytes()).await.is_err() {
                            break;
                        }

                        // Send a log message
                        let log_msg = "MESSage Status Test status message\n";
                        if socket.write_all(log_msg.as_bytes()).await.is_err() {
                            break;
                        }
                    }
                    result = socket.read(&mut buf) => {
                        match result {
                            Ok(0) => break, // Connection was closed
                            Ok(n) => {
                                // Add new data to line buffer
                                line_buffer.push_str(&String::from_utf8_lossy(&buf[..n]));

                                // Process complete lines
                                while let Some(pos) = line_buffer.find('\n') {
                                    let line = line_buffer[..pos].trim().to_string();
                                    line_buffer = line_buffer[pos + 1..].to_string();

                                    debug!("Processing command: {}", line);

                                    // Handle power commands
                                    if line.ends_with("POW?") {
                                        // Query power status
                                        let status = if power_status { "ON" } else { "OFF" };
                                        let response = if let Some(ident) = line.split_whitespace().next() {
                                            if ident.parse::<u32>().is_ok() {
                                                format!("OK {} {}\n", ident, status)
                                            } else {
                                                format!("OK POW? {}\n", status)
                                            }
                                        } else {
                                            format!("OK POW? {}\n", status)
                                        };
                                        socket.write_all(response.as_bytes()).await.unwrap();
                                    } else if line.ends_with("POW ON") {
                                        // Set power ON
                                        power_status = true;
                                        let response = if let Some(ident) = line.split_whitespace().next() {
                                            if ident.parse::<u32>().is_ok() {
                                                format!("OK {}\n", ident)
                                            } else {
                                                "OK POW\n".to_string()
                                            }
                                        } else {
                                            "OK POW\n".to_string()
                                        };
                                        socket.write_all(response.as_bytes()).await.unwrap();
                                    } else if line.ends_with("POW OFF") {
                                        // Set power OFF
                                        power_status = false;
                                        let response = if let Some(ident) = line.split_whitespace().next() {
                                            if ident.parse::<u32>().is_ok() {
                                                format!("OK {}\n", ident)
                                            } else {
                                                "OK POW\n".to_string()
                                            }
                                        } else {
                                            "OK POW\n".to_string()
                                        };
                                        socket.write_all(response.as_bytes()).await.unwrap();
                                    } else if line.contains("CUSTOM") {
                                        // Extract the message identifier if present
                                        let response = if let Some(ident) = line.split_whitespace().next() {
                                            if ident.parse::<u32>().is_ok() {
                                                // Get the command part without the identifier
                                                let command = line.split_once(' ').map(|x| x.1).unwrap_or("");
                                                format!("OK {} -received=\"{}\" success", ident, command)
                                            } else {
                                                format!("OK CUSTOM -received=\"{}\" success", line)
                                            }
                                        } else {
                                            format!("OK CUSTOM -received=\"{}\" success", line)
                                        };
                                        socket.write_all(format!("{}\n", response).as_bytes()).await.unwrap();
                                    } else if line.contains("MULTILINE") {
                                        // Return a response with an XML-quoted multiline string
                                        let response = if let Some(ident) = line.split_whitespace().next() {
                                            if ident.parse::<u32>().is_ok() {
                                                format!("OK {} <quote>Line 1\nLine 2\nLine 3</quote>\n", ident)
                                            } else {
                                                "OK MULTILINE <quote>Line 1\nLine 2\nLine 3</quote>\n".to_string()
                                            }
                                        } else {
                                            "OK MULTILINE <quote>Line 1\nLine 2\nLine 3</quote>\n".to_string()
                                        };
                                        socket.write_all(response.as_bytes()).await.unwrap();
                                    } else if line.contains("BADXML1") {
                                        // Return a response with mismatched XML tags
                                        let response = if let Some(ident) = line.split_whitespace().next() {
                                            if ident.parse::<u32>().is_ok() {
                                                format!("OK {} <quote>Line 1\nLine 2\nLine 3</badquote>\n", ident)
                                            } else {
                                                "OK BADXML1 <quote>Line 1\nLine 2\nLine 3</badquote>\n".to_string()
                                            }
                                        } else {
                                            "OK BADXML1 <quote>Line 1\nLine 2\nLine 3</badquote>\n".to_string()
                                        };
                                        socket.write_all(response.as_bytes()).await.unwrap();
                                    } else if line.contains("BADXML2") {
                                        // Return a response with an unexpected close tag
                                        let response = if let Some(ident) = line.split_whitespace().next() {
                                            if ident.parse::<u32>().is_ok() {
                                                format!("OK {} </unexpected>Line 1\nLine 2\nLine 3</unexpected>\n", ident)
                                            } else {
                                                "OK BADXML2 </unexpected>Line 1\nLine 2\nLine 3</unexpected>\n".to_string()
                                            }
                                        } else {
                                            "OK BADXML2 </unexpected>Line 1\nLine 2\nLine 3</unexpected>\n".to_string()
                                        };
                                        socket.write_all(response.as_bytes()).await.unwrap();
                                    } else if line.contains("ANGLES") {
                                        // Return a response with angle brackets that aren't XML tags
                                        let response = if let Some(ident) = line.split_whitespace().next() {
                                            if ident.parse::<u32>().is_ok() {
                                                format!("OK {} Temperature < 37.5 and pH > 7.0\n", ident)
                                            } else {
                                                "OK ANGLES Temperature < 37.5 and pH > 7.0\n".to_string()
                                            }
                                        } else {
                                            "OK ANGLES Temperature < 37.5 and pH > 7.0\n".to_string()
                                        };
                                        socket.write_all(response.as_bytes()).await.unwrap();
                                    }
                                }
                                continue;
                            },
                            Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => {
                                tokio::time::sleep(Duration::from_millis(10)).await;
                            }
                            Err(_) => break, // Any other error, break the loop
                        }
                    }
                }
            }
            if !stay_open {
                break;
            }
        }
    });

    (addr, handle)
}

#[tokio::test]
async fn test_tcp_connection() {
    setup_logging();
    let (addr, _server) = setup_mock_server(None, true).await;

    info!("Testing TCP connection to {}", addr);
    let connection = QSConnection::connect("127.0.0.1", addr.port(), ConnectionType::TCP).await;

    match &connection {
        Ok(_) => info!("Connection established successfully"),
        Err(e) => error!("Connection failed: {:?}", e),
    }

    assert!(connection.is_ok());
    let connection = connection.unwrap();

    // Verify ready message
    assert_eq!(
        connection
            .ready_message
            .args
            .get("session")
            .unwrap()
            .to_string(),
        "474800"
    );
    assert_eq!(
        connection
            .ready_message
            .args
            .get("product")
            .unwrap()
            .to_string(),
        "QuantStudio3_5"
    );
    assert_eq!(
        connection
            .ready_message
            .args
            .get("version")
            .unwrap()
            .to_string(),
        "1.3.0"
    );
    assert_eq!(
        connection
            .ready_message
            .args
            .get("build")
            .unwrap()
            .to_string(),
        "1"
    );
    assert_eq!(
        connection
            .ready_message
            .args
            .get("capabilities")
            .unwrap()
            .to_string(),
        "Index"
    );

    info!("connection done");
    _server.abort();
}

#[tokio::test]
async fn test_auto_connection() {
    let (addr, _server) = setup_mock_server(None, true).await;

    let connection = QSConnection::connect("127.0.0.1", addr.port(), ConnectionType::Auto).await;

    let connection = match connection {
        Ok(c) => c,
        Err(e) => {
            panic!("connection error: {:?}", e);
        }
    };

    // Verify ready message
    assert_eq!(
        connection
            .ready_message
            .args
            .get("session")
            .unwrap()
            .to_string(),
        "474800"
    );
    assert_eq!(
        connection
            .ready_message
            .args
            .get("product")
            .unwrap()
            .to_string(),
        "QuantStudio3_5"
    );
    assert_eq!(
        connection
            .ready_message
            .args
            .get("version")
            .unwrap()
            .to_string(),
        "1.3.0"
    );
    assert_eq!(
        connection
            .ready_message
            .args
            .get("build")
            .unwrap()
            .to_string(),
        "1"
    );
    assert_eq!(
        connection
            .ready_message
            .args
            .get("capabilities")
            .unwrap()
            .to_string(),
        "Index"
    );

    println!("connection done");
    _server.abort();
}

#[tokio::test]
async fn test_connection_refused() {
    // Try to connect to a port that's definitely not listening
    let connection = QSConnection::connect(
        "127.0.0.1",
        0, // Port 0 should never have a listener
        ConnectionType::TCP,
    )
    .await;

    assert!(connection.is_err());

    println!("connection done");
}

#[tokio::test]
async fn test_power_query_and_set() {
    let (addr, _server) = setup_mock_server(None, true).await;
    let connection = QSConnection::connect("127.0.0.1", addr.port(), ConnectionType::TCP)
        .await
        .unwrap();

    // Test initial power status (should be ON)
    let response = PowerQuery
        .send(&connection)
        .await
        .unwrap()
        .receive_response()
        .await;
    assert!(response.is_ok());
    assert_eq!(response.unwrap().unwrap(), PowerStatus::On);

    // Set power OFF
    let response = PowerSet(PowerStatus::Off)
        .send(&connection)
        .await
        .unwrap()
        .receive_response()
        .await;
    assert!(response.is_ok());

    // Verify power is OFF
    let response = PowerQuery
        .send(&connection)
        .await
        .unwrap()
        .receive_response()
        .await;
    assert!(response.is_ok());
    assert_eq!(response.unwrap().unwrap(), PowerStatus::Off);

    // Set power ON
    let response = PowerSet(PowerStatus::On)
        .send(&connection)
        .await
        .unwrap()
        .receive_response()
        .await;
    assert!(response.is_ok());

    // Verify power is ON
    let response = PowerQuery
        .send(&connection)
        .await
        .unwrap()
        .receive_response()
        .await;
    assert!(response.is_ok());
    assert_eq!(response.unwrap().unwrap(), PowerStatus::On);

    _server.abort();
}

#[tokio::test]
async fn test_log_messages() {
    let (addr, _server) = setup_mock_server(None, true).await;
    let connection = QSConnection::connect("127.0.0.1", addr.port(), ConnectionType::TCP)
        .await
        .unwrap();

    // Subscribe to Status messages
    let mut stream = connection.subscribe_log(&["Status"]).await;

    // Wait for and verify a log message
    let message = stream.next().await;
    assert!(message.is_some());

    if let Some((topic, result)) = message {
        assert_eq!(topic, "Status");
        let msg = result.unwrap();
        assert_eq!(msg.topic, "Status");
        assert_eq!(msg.message, "Test status message");
    }

    _server.abort();
}

#[tokio::test]
async fn test_send_command_bytes() {
    let (addr, _server) = setup_mock_server(None, true).await;
    let connection = QSConnection::connect("127.0.0.1", addr.port(), ConnectionType::TCP)
        .await
        .unwrap();

    // Send a custom command using raw bytes
    let command = "CUSTOM -option=value arg1 arg2 ";
    let mut response = connection
        .send_command_bytes(command.as_bytes())
        .await
        .unwrap();

    // Add handler for CUSTOM command in mock server
    let msg = response.recv().await.unwrap();

    match msg {
        MessageResponse::Ok { ident, message } => {
            println!("ident: {:?}", ident);
            println!("message: {:?}", message);
            assert_eq!(message.args[0].to_string(), "success");
            assert_eq!(
                message.options.get("received").unwrap().to_string(),
                "CUSTOM -option=value arg1 arg2"
            );
        }
        _ => panic!("Expected OK response"),
    }

    _server.abort();
}

fn generate_test_certificate() -> rcgen::CertifiedKey {
    // Generate a self-signed certificate for testing

    // Create Certificate and PrivateKey
    rcgen::generate_simple_self_signed(vec!["localhost".into()]).unwrap()
}

async fn setup_mock_ssl_server(
    port: Option<u16>,
    stay_open: bool,
) -> (SocketAddr, tokio::task::JoinHandle<()>) {
    // Generate certificate and create TLS config
    let cert = generate_test_certificate();

    let cert_pem = cert.cert.der().clone();
    let key_pem = cert.key_pair.serialize_pem();
    let rkey = rustls_pki_types::PrivateKeyDer::from_pem_slice(key_pem.as_bytes()).unwrap();
    println!("key_pem: {:?}", &rkey);

    let certs = vec![cert_pem];
    let key = rkey;

    let config = ServerConfig::builder()
        .with_no_client_auth()
        .with_single_cert(certs, key)
        .unwrap();
    let acceptor = TlsAcceptor::from(Arc::new(config));

    // Bind to a random available port
    let listener = TcpListener::bind(format!("127.0.0.1:{}", port.unwrap_or(0)))
        .await
        .unwrap();
    let addr = listener.local_addr().unwrap();

    // Spawn server task
    let handle = tokio::spawn(async move {
        let mut power_status = true;

        loop {
            let (stream, _) = listener.accept().await.unwrap();
            let acceptor = acceptor.clone();

            // Accept TLS connection
            let mut stream = acceptor.accept(stream).await.unwrap();

            // Send ready message
            let ready_msg = "READy -session=474800 -product=QuantStudio3_5 -version=1.3.0 -build=001 -capabilities=Index\n";
            stream.write_all(ready_msg.as_bytes()).await.unwrap();

            // Create a periodic timer for log messages
            let mut interval = interval(Duration::from_millis(100));

            // Buffer for accumulating partial lines
            let mut line_buffer = String::new();
            let mut buf = [0; 1024];

            loop {
                tokio::select! {
                    _ = interval.tick() => {
                        // First send a log message that won't be read
                        let log_msg = "MESSage NonStatus Test status message\n";
                        if stream.write_all(log_msg.as_bytes()).await.is_err() {
                            break;
                        }

                        // Send a log message
                        let log_msg = "MESSage Status Test status message\n";
                        if stream.write_all(log_msg.as_bytes()).await.is_err() {
                            break;
                        }
                    }
                    result = stream.read(&mut buf) => {
                        match result {
                            Ok(0) => break,
                            Ok(n) => {
                                // Add new data to line buffer
                                line_buffer.push_str(&String::from_utf8_lossy(&buf[..n]));

                                // Process complete lines
                                while let Some(pos) = line_buffer.find('\n') {
                                    let line = line_buffer[..pos].trim().to_string();
                                    line_buffer = line_buffer[pos + 1..].to_string();

                                    debug!("Processing SSL command: {}", line);

                                    // Handle power commands
                                    if line.ends_with("POW?") {
                                        // Query power status
                                        let status = if power_status { "ON" } else { "OFF" };
                                        let response = if let Some(ident) = line.split_whitespace().next() {
                                            if ident.parse::<u32>().is_ok() {
                                                format!("OK {} {}\n", ident, status)
                                            } else {
                                                format!("OK POW? {}\n", status)
                                            }
                                        } else {
                                            format!("OK POW? {}\n", status)
                                        };
                                        stream.write_all(response.as_bytes()).await.unwrap();
                                    } else if line.ends_with("POW ON") {
                                        // Set power ON
                                        power_status = true;
                                        let response = if let Some(ident) = line.split_whitespace().next() {
                                            if ident.parse::<u32>().is_ok() {
                                                format!("OK {}\n", ident)
                                            } else {
                                                "OK POW\n".to_string()
                                            }
                                        } else {
                                            "OK POW\n".to_string()
                                        };
                                        stream.write_all(response.as_bytes()).await.unwrap();
                                    } else if line.ends_with("POW OFF") {
                                        // Set power OFF
                                        power_status = false;
                                        let response = if let Some(ident) = line.split_whitespace().next() {
                                            if ident.parse::<u32>().is_ok() {
                                                format!("OK {}\n", ident)
                                            } else {
                                                "OK POW\n".to_string()
                                            }
                                        } else {
                                            "OK POW\n".to_string()
                                        };
                                        stream.write_all(response.as_bytes()).await.unwrap();
                                    } else if line.contains("CUSTOM") {
                                        // Extract the message identifier if present
                                        let response = if let Some(ident) = line.split_whitespace().next() {
                                            if ident.parse::<u32>().is_ok() {
                                                // Get the command part without the identifier
                                                let command = line.split_once(' ').map(|x| x.1).unwrap_or("");
                                                format!("OK {} -received=\"{}\" success", ident, command)
                                            } else {
                                                format!("OK CUSTOM -received=\"{}\" success", line)
                                            }
                                        } else {
                                            format!("OK CUSTOM -received=\"{}\" success", line)
                                        };
                                        stream.write_all(format!("{}\n", response).as_bytes()).await.unwrap();
                                    } else if line.contains("MULTILINE") {
                                        // Return a response with an XML-quoted multiline string
                                        let response = if let Some(ident) = line.split_whitespace().next() {
                                            if ident.parse::<u32>().is_ok() {
                                                format!("OK {} <quote>Line 1\nLine 2\nLine 3</quote>\n", ident)
                                            } else {
                                                "OK MULTILINE <quote>Line 1\nLine 2\nLine 3</quote>\n".to_string()
                                            }
                                        } else {
                                            "OK MULTILINE <quote>Line 1\nLine 2\nLine 3</quote>\n".to_string()
                                        };
                                        stream.write_all(response.as_bytes()).await.unwrap();
                                    } else if line.contains("BADXML1") {
                                        // Return a response with mismatched XML tags
                                        let response = if let Some(ident) = line.split_whitespace().next() {
                                            if ident.parse::<u32>().is_ok() {
                                                format!("OK {} <quote>Line 1\nLine 2\nLine 3</badquote>\n", ident)
                                            } else {
                                                "OK BADXML1 <quote>Line 1\nLine 2\nLine 3</badquote>\n".to_string()
                                            }
                                        } else {
                                            "OK BADXML1 <quote>Line 1\nLine 2\nLine 3</badquote>\n".to_string()
                                        };
                                        stream.write_all(response.as_bytes()).await.unwrap();
                                    } else if line.contains("BADXML2") {
                                        // Return a response with an unexpected close tag
                                        let response = if let Some(ident) = line.split_whitespace().next() {
                                            if ident.parse::<u32>().is_ok() {
                                                format!("OK {} </unexpected>Line 1\nLine 2\nLine 3</unexpected>\n", ident)
                                            } else {
                                                "OK BADXML2 </unexpected>Line 1\nLine 2\nLine 3</unexpected>\n".to_string()
                                            }
                                        } else {
                                            "OK BADXML2 </unexpected>Line 1\nLine 2\nLine 3</unexpected>\n".to_string()
                                        };
                                        stream.write_all(response.as_bytes()).await.unwrap();
                                    } else if line.contains("ANGLES") {
                                        // Return a response with angle brackets that aren't XML tags
                                        let response = if let Some(ident) = line.split_whitespace().next() {
                                            if ident.parse::<u32>().is_ok() {
                                                format!("OK {} Temperature < 37.5 and pH > 7.0\n", ident)
                                            } else {
                                                "OK ANGLES Temperature < 37.5 and pH > 7.0\n".to_string()
                                            }
                                        } else {
                                            "OK ANGLES Temperature < 37.5 and pH > 7.0\n".to_string()
                                        };
                                        stream.write_all(response.as_bytes()).await.unwrap();
                                    }
                                }
                                continue;
                            },
                            Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => {
                                tokio::time::sleep(Duration::from_millis(10)).await;
                            }
                            Err(_) => break,
                        }
                    }
                }
            }
            if !stay_open {
                break;
            }
        }
    });

    (addr, handle)
}

#[tokio::test]
async fn test_ssl_connection() {
    let (addr, _server) = setup_mock_ssl_server(None, true).await;

    let connection = QSConnection::connect("127.0.0.1", addr.port(), ConnectionType::SSL).await;

    assert!(connection.is_ok());
    let connection = connection.unwrap();

    // Verify ready message
    assert_eq!(
        connection
            .ready_message
            .args
            .get("session")
            .unwrap()
            .to_string(),
        "474800"
    );

    _server.abort();
}

#[tokio::test]
async fn test_auto_ssl_connection() {
    let (addr, _server) = setup_mock_ssl_server(None, true).await;

    let connection = QSConnection::connect("127.0.0.1", addr.port(), ConnectionType::Auto).await;

    assert!(connection.is_ok());
    let connection = connection.unwrap();

    // Verify ready message
    assert_eq!(
        connection
            .ready_message
            .args
            .get("session")
            .unwrap()
            .to_string(),
        "474800"
    );

    _server.abort();
}

#[tokio::test]
async fn test_choose_ssl_by_port_7443() {
    let (_, server) = setup_mock_ssl_server(Some(7443), false).await;
    let connection = QSConnection::connect("127.0.0.1", 7443, ConnectionType::Auto).await;
    assert!(connection.is_ok(), "Should have chosen SSL for port 7443");
    let connection = connection.unwrap();
    assert_eq!(connection.connection_type, ConnectionType::SSL);
    assert!(
        connection.is_connected().await,
        "Connection should be connected"
    );
    server.abort();
    assert!(server.await.is_err(), "Mock server didn't abort.");

    let (_, server) = setup_mock_server(Some(7443), false).await;
    let connection = QSConnection::connect("127.0.0.1", 7443, ConnectionType::Auto).await;
    assert!(connection.is_err(), "Should have chosen SSL for port 7443");
    server.abort();
}

#[tokio::test]
async fn test_choose_tcp_by_port_7000() {
    let (_, server) = setup_mock_server(Some(7000), false).await;
    let connection = QSConnection::connect("127.0.0.1", 7000, ConnectionType::Auto).await;
    assert!(connection.is_ok());
    let connection = connection.unwrap();
    assert_eq!(connection.connection_type, ConnectionType::TCP);
    server.abort();
}

#[tokio::test]
async fn test_ssl_power_query_and_set() {
    let (addr, _server) = setup_mock_ssl_server(None, true).await;
    let connection = QSConnection::connect("127.0.0.1", addr.port(), ConnectionType::SSL)
        .await
        .unwrap();

    // Test initial power status (should be ON)
    let response = PowerQuery
        .send(&connection)
        .await
        .unwrap()
        .receive_response()
        .await;
    assert!(response.is_ok());
    assert_eq!(response.unwrap().unwrap(), PowerStatus::On);

    // Set power OFF
    let response = PowerSet(PowerStatus::Off)
        .send(&connection)
        .await
        .unwrap()
        .receive_response()
        .await;
    assert!(response.is_ok());

    // Verify power is OFF
    let response = PowerQuery
        .send(&connection)
        .await
        .unwrap()
        .receive_response()
        .await;
    assert!(response.is_ok());
    assert_eq!(response.unwrap().unwrap(), PowerStatus::Off);

    _server.abort();
}

#[tokio::test]
async fn test_multiline_response() {
    let (addr, _server) = setup_mock_server(None, true).await;
    let connection = QSConnection::connect("127.0.0.1", addr.port(), ConnectionType::TCP)
        .await
        .unwrap();

    // Send a command that triggers a multiline response
    let command = "MULTILINE";
    let mut response = connection
        .send_command_bytes(command.as_bytes())
        .await
        .unwrap();

    // Get and verify the response
    let msg = response.recv().await.unwrap();

    match msg {
        MessageResponse::Ok { message, .. } => {
            assert_eq!(
                message.args[0],
                Value::XmlString {
                    value: "Line 1\nLine 2\nLine 3".into(),
                    tag: "quote".to_string()
                }
            );
        }
        _ => panic!("Expected OK response with multiline string"),
    }

    _server.abort();
}

#[tokio::test]
async fn test_mismatched_xml_tags() {
    setup_logging();
    let (addr, _server) = setup_mock_server(None, true).await;

    info!("Testing mismatched XML tags handling");
    let connection = QSConnection::connect("127.0.0.1", addr.port(), ConnectionType::TCP)
        .await
        .unwrap();

    // Send a command that triggers a mismatched XML tag response
    let command = "BADXML1";
    debug!("Sending command: {}", command);
    let _ = connection
        .send_command_bytes(command.as_bytes())
        .await
        .unwrap();

    // Send another command to verify connection still works
    let command = "CUSTOM -option=value arg1 arg2";
    debug!("Sending verification command: {}", command);
    let mut response = connection
        .send_command_bytes(command.as_bytes())
        .await
        .unwrap();
    let msg = response.recv().await.unwrap();

    match &msg {
        MessageResponse::Ok { message, .. } => {
            info!("Received OK response: {:?}", message);
        }
        _ => warn!("Unexpected response type: {:?}", msg),
    }

    _server.abort();
}

#[tokio::test]
async fn test_unexpected_close_tag() {
    setup_logging();
    let (addr, _server) = setup_mock_server(None, true).await;
    let connection = QSConnection::connect("127.0.0.1", addr.port(), ConnectionType::TCP)
        .await
        .unwrap();

    // Send a command that triggers an unexpected close tag response
    let command = "BADXML2";
    let _ = connection
        .send_command_bytes(command.as_bytes())
        .await
        .unwrap();

    // Send another command to verify connection still works
    let command = "CUSTOM -option=value arg1 arg2";
    let mut response = connection
        .send_command_bytes(command.as_bytes())
        .await
        .unwrap();
    let msg = response.recv().await.unwrap();

    match msg {
        MessageResponse::Ok { message, .. } => {
            assert_eq!(message.args[0].to_string(), "success");
        }
        _ => panic!("Expected OK response"),
    }

    _server.abort();
}

#[tokio::test]
async fn test_angle_brackets_in_response() {
    setup_logging();
    let (addr, _server) = setup_mock_server(None, true).await;
    let connection = QSConnection::connect("127.0.0.1", addr.port(), ConnectionType::TCP)
        .await
        .unwrap();

    // Send a command that triggers a response with angle brackets
    let command = "ANGLES";
    debug!("Sending command: {}", command);
    let mut response = connection
        .send_command_bytes(command.as_bytes())
        .await
        .unwrap();

    // Get and verify the response
    let msg = response.recv().await.unwrap();

    match msg {
        MessageResponse::Ok { message, .. } => {
            // The angle brackets should be treated as plain text, not XML
            assert_eq!(message.args[0], Value::String("Temperature".into()));
            assert_eq!(message.args[1], Value::String("<".into()));
            assert_eq!(message.args[2], Value::Float(37.5));
            assert_eq!(message.args[3], Value::String("and".into()));
            assert_eq!(message.args[4], Value::String("pH".into()));
            assert_eq!(message.args[5], Value::String(">".into()));
            assert_eq!(message.args[6], Value::Float(7.0));
        }
        _ => panic!("Expected OK response with angle brackets"),
    }

    _server.abort();
}