qslib 0.14.0-pre2

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
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
use std::{collections::VecDeque, future::Future, io::Write, marker::PhantomData};

use log::{info, warn};
use thiserror::Error;

use crate::{
    com::{QSConnection, QSConnectionError, ResponseReceiver, SendCommandError},
    parser::{ArgMap, Command, ErrorResponse, MessageResponse, OkResponse, ParseError, Value},
};

pub struct CommandReceiver<T: TryFrom<OkResponse>, E: From<ErrorResponse>> {
    pub message_content: Vec<u8>,
    pub response: ResponseReceiver,
    pub response_type: PhantomData<T>,
    pub error_type: PhantomData<E>,
}

#[derive(Debug, Error)]
pub enum OkParseError {
    #[error("Unexpected values: {1} ({0:?})")]
    UnexpectedValues(OkResponse, String),
    #[error("Parse error: {0:?}")]
    ParseError(#[from] ParseError),
}

#[derive(Debug, Error)]
pub enum ReceiveOkResponseError {
    #[error("Connection closed.")]
    ConnectionClosed,
    #[error("OK response parsing error: {0:?}")]
    ResponseParsingError(#[from] OkParseError),
}

#[derive(Debug, Error)]
pub enum ReceiveNextResponseError {
    #[error("Connection closed.")]
    ConnectionClosed,
    #[error("Unexpected OK response.")]
    UnexpectedOk(OkResponse),
    #[error("Unexpected error response.")]
    UnexpectedError(ErrorResponse),
}

impl<T: TryFrom<OkResponse, Error = OkParseError>, E: From<ErrorResponse>> CommandReceiver<T, E> {
    pub async fn receive_response(&mut self) -> Result<Result<T, E>, ReceiveOkResponseError> {
        loop {
            match self.response.recv().await {
                None => return Err(ReceiveOkResponseError::ConnectionClosed),
                Some(MessageResponse::Ok { message, .. }) => return Ok(Ok(message.try_into()?)),
                Some(MessageResponse::CommandError { error, .. }) => return Ok(Err(error.into())),
                Some(MessageResponse::Next { .. }) => (),
                Some(MessageResponse::Message(message)) => panic!(
                    "Message response to command should not be possible: {:?}",
                    message
                ),
            }
        }
    }

    pub async fn receive_next(&mut self) -> Result<Result<(), E>, ReceiveNextResponseError> {
        match self.response.recv().await {
            None => Err(ReceiveNextResponseError::ConnectionClosed),
            Some(MessageResponse::CommandError { error, .. }) => Ok(Err(error.into())),
            Some(MessageResponse::Next { .. }) => Ok(Ok(())),
            Some(MessageResponse::Ok { message, .. }) => {
                Err(ReceiveNextResponseError::UnexpectedOk(message))
            }
            Some(MessageResponse::Message(message)) => {
                panic!(
                    "Message response to command should not be possible: {:?}",
                    message
                )
            }
        }
    }
}

pub trait CommandBuilder: Clone + Send + Sync {
    const COMMAND: &'static [u8];
    fn args(&self) -> Option<Vec<Value>> {
        None
    }
    fn options(&self) -> Option<ArgMap> {
        None
    }
    fn write_command(&self, bytes: &mut impl Write) -> Result<(), QSConnectionError> {
        bytes.write_all(Self::COMMAND)?;
        if let Some(options) = self.options() {
            for (key, value) in options {
                bytes.write_all(b" -")?;
                bytes.write_all(key.as_bytes())?;
                bytes.write_all(b"=")?;
                value.write_bytes(bytes)?;
            }
        }
        if let Some(args) = self.args() {
            for arg in args {
                bytes.write_all(b" ")?;
                arg.write_bytes(bytes)?;
            }
        }
        Ok(())
    }

    fn to_bytes(&self) -> Vec<u8> {
        let mut v = Vec::new();
        self.write_command(&mut v).unwrap();
        v
    }

    // fn command(&self) -> Command {
    //     let mut c = Command::raw(Self::COMMAND);
    //     if let Some(args) = self.args() {
    //         for arg in args {
    //             c = c.with_arg(arg);
    //         }
    //     }
    //     if let Some(options) = self.options() {
    //         for (key, value) in options {
    //             c = c.with_option(&key, value);
    //         }
    //     }
    //     c
    // }

    type Response: TryFrom<OkResponse>;
    type Error: From<ErrorResponse>;
    // fn send(&self) -> impl Future<Output = Result<CommandReceiver<Self::Response>, QSConnectionError>> + Send;
    fn send(
        self,
        connection: &QSConnection,
    ) -> impl Future<Output = Result<CommandReceiver<Self::Response, Self::Error>, SendCommandError>>
           + Send {
        let content = self.to_bytes();
        let r = connection.send_command(self);
        async move {
            let r = r.await?;
            Ok(CommandReceiver {
                message_content: content,
                response: r,
                response_type: PhantomData,
                error_type: PhantomData,
            })
        }
    }
}

impl TryFrom<OkResponse> for () {
    type Error = OkParseError;
    fn try_from(value: OkResponse) -> Result<Self, Self::Error> {
        // OkResponse has no data we care about, just return unit
        if value.args.is_empty() && value.options.is_empty() {
            Ok(())
        } else {
            Err(OkParseError::UnexpectedValues(
                value,
                "response should have been empty".to_string(),
            ))
        }
    }
}

#[derive(Debug, Clone)]
pub struct Subscribe(pub String);

impl CommandBuilder for Subscribe {
    const COMMAND: &'static [u8] = b"SUBS";
    type Response = ();
    type Error = ErrorResponse;
    fn args(&self) -> Option<Vec<Value>> {
        Some(vec![self.0.clone().into()])
    }
}

impl Subscribe {
    pub fn topic(topic: &str) -> Self {
        Self(topic.to_string())
    }
}

#[derive(Debug, Clone)]
pub enum AccessLevel {
    Guest,
    Observer,
    Controller,
    Administrator,
    Full,
}

impl From<AccessLevel> for String {
    fn from(level: AccessLevel) -> Self {
        match level {
            AccessLevel::Guest => "Guest".to_string(),
            AccessLevel::Observer => "Observer".to_string(),
            AccessLevel::Controller => "Controller".to_string(),
            AccessLevel::Administrator => "Administrator".to_string(),
            AccessLevel::Full => "Full".to_string(),
        }
    }
}

impl TryFrom<String> for AccessLevel {
    type Error = ();
    fn try_from(value: String) -> Result<Self, Self::Error> {
        match value.to_lowercase().as_str() {
            "guest" => Ok(AccessLevel::Guest),
            "observer" => Ok(AccessLevel::Observer),
            "controller" => Ok(AccessLevel::Controller),
            "administrator" => Ok(AccessLevel::Administrator),
            "full" => Ok(AccessLevel::Full),
            _ => Err(()),
        }
    }
}

impl TryFrom<OkResponse> for AccessLevel {
    type Error = OkParseError;
    fn try_from(value: OkResponse) -> Result<Self, Self::Error> {
        let level = value.args.first().unwrap().clone().try_into_string()?;
        AccessLevel::try_from(level).map_err(|_| {
            OkParseError::UnexpectedValues(value, "unexpected access level".to_string())
        })
    }
}

impl From<AccessLevel> for Value {
    fn from(level: AccessLevel) -> Self {
        Value::String(level.into())
    }
}

#[derive(Debug, Clone)]
pub struct AccessLevelSet(pub AccessLevel);

impl AccessLevelSet {
    pub fn level(level: AccessLevel) -> Self {
        Self(level)
    }
}

impl CommandBuilder for AccessLevelSet {
    type Response = ();
    type Error = ErrorResponse;
    const COMMAND: &'static [u8] = b"ACC";
    fn args(&self) -> Option<Vec<Value>> {
        Some(vec![self.0.clone().into()])
    }
}

#[derive(Debug, Clone)]
pub struct AccessLevelQuery;

impl CommandBuilder for AccessLevelQuery {
    type Response = AccessLevel;
    type Error = ErrorResponse;
    const COMMAND: &'static [u8] = b"ACC?";
}

#[derive(Debug, Clone)]

pub struct Unsubscribe(pub String);

impl CommandBuilder for Unsubscribe {
    type Response = ();
    type Error = ErrorResponse;
    const COMMAND: &'static [u8] = b"UNS";
    fn args(&self) -> Option<Vec<Value>> {
        Some(vec![self.0.clone().into()])
    }
}

impl Unsubscribe {
    pub fn topic(topic: &str) -> Self {
        Self(topic.to_string())
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PowerStatus {
    On,
    Off,
}

#[derive(Debug, Clone)]
pub struct PowerQuery;

impl CommandBuilder for PowerQuery {
    type Response = PowerStatus;
    type Error = ErrorResponse;
    const COMMAND: &'static [u8] = b"POW?";
}

impl TryFrom<OkResponse> for PowerStatus {
    type Error = OkParseError;
    fn try_from(value: OkResponse) -> Result<Self, Self::Error> {
        match value.args.first() {
            Some(Value::String(s)) if s.to_uppercase() == "ON" => Ok(PowerStatus::On),
            Some(Value::String(s)) if s.to_uppercase() == "OFF" => Ok(PowerStatus::Off),
            _ => Err(OkParseError::UnexpectedValues(
                value,
                "response should have been ON or OFF".to_string(),
            )),
        }
    }
}

#[derive(Debug, Clone)]
pub struct PowerSet(pub PowerStatus);

impl CommandBuilder for PowerSet {
    type Response = ();
    type Error = ErrorResponse;
    const COMMAND: &'static [u8] = b"POW";
    fn args(&self) -> Option<Vec<Value>> {
        Some(vec![self.0.into()])
    }
}

impl PowerSet {
    pub fn on() -> Self {
        Self(PowerStatus::On)
    }

    pub fn off() -> Self {
        Self(PowerStatus::Off)
    }

    pub fn set(power: impl Into<PowerStatus>) -> Self {
        Self(power.into())
    }
}

impl From<PowerStatus> for Value {
    fn from(power: PowerStatus) -> Self {
        match power {
            PowerStatus::On => Value::String("ON".to_string()),
            PowerStatus::Off => Value::String("OFF".to_string()),
        }
    }
}

impl From<PowerStatus> for bool {
    fn from(power: PowerStatus) -> Self {
        match power {
            PowerStatus::On => true,
            PowerStatus::Off => false,
        }
    }
}

impl From<bool> for PowerStatus {
    fn from(value: bool) -> Self {
        if value {
            PowerStatus::On
        } else {
            PowerStatus::Off
        }
    }
}

impl From<PowerSet> for Command {
    fn from(command: PowerSet) -> Self {
        Command::new("POW").with_arg(match command.0 {
            PowerStatus::On => "ON",
            PowerStatus::Off => "OFF",
        })
    }
}

// '-RunMode=- -Step=- -RunTitle=- -Cycle=- -Stage=-'
#[derive(Debug, Clone)]
pub struct RunProgress {
    pub run_mode: String,
    pub step: String,
    pub run_title: String,
    pub cycle: String,
    pub stage: String,
}

pub enum PossibleRunProgress {
    Running(RunProgress),
    NotRunning(RunProgress),
}

impl TryFrom<OkResponse> for PossibleRunProgress {
    type Error = OkParseError;
    fn try_from(value: OkResponse) -> Result<Self, Self::Error> {
        let rp = RunProgress {
            run_mode: value
                .options
                .get("RunMode")
                .ok_or_else(|| {
                    OkParseError::UnexpectedValues(value.clone(), "missing RunMode".to_string())
                })?
                .to_string(),
            step: value
                .options
                .get("Step")
                .ok_or_else(|| {
                    OkParseError::UnexpectedValues(value.clone(), "missing Step".to_string())
                })?
                .to_string(),
            run_title: value
                .options
                .get("RunTitle")
                .ok_or_else(|| {
                    OkParseError::UnexpectedValues(value.clone(), "missing RunTitle".to_string())
                })?
                .to_string(),
            cycle: value
                .options
                .get("Cycle")
                .ok_or_else(|| {
                    OkParseError::UnexpectedValues(value.clone(), "missing Cycle".to_string())
                })?
                .to_string(),
            stage: value
                .options
                .get("Stage")
                .ok_or_else(|| {
                    OkParseError::UnexpectedValues(value.clone(), "missing Stage".to_string())
                })?
                .to_string(),
        };

        if rp.run_mode == "-" {
            if rp.step != "-" || rp.run_title != "-" || rp.cycle != "-" || rp.stage != "-" {
                warn!("Not running but some fields were not empty: {:?}", value);
            }
            return Ok(PossibleRunProgress::NotRunning(rp));
        }

        if !value.args.is_empty() {
            return Err(OkParseError::UnexpectedValues(
                value,
                "unexpected arguments".to_string(),
            ));
        }
        if rp.step == "-" || rp.run_title == "-" || rp.cycle == "-" || rp.stage == "-" {
            return Err(OkParseError::UnexpectedValues(
                value,
                "running but some fields were empty".to_string(),
            ));
        }
        for (key, _) in value.options.iter() {
            if !["RunMode", "Step", "RunTitle", "Cycle", "Stage"].contains(&key.as_str()) {
                return Err(OkParseError::UnexpectedValues(
                    value.clone(),
                    format!("unexpected option {}", key),
                ));
            }
        }

        Ok(PossibleRunProgress::Running(rp))
    }
}

#[derive(Debug, Clone)]
pub struct RunProgressQuery;

impl CommandBuilder for RunProgressQuery {
    type Response = PossibleRunProgress;
    type Error = ErrorResponse;
    const COMMAND: &'static [u8] = b"RUN?";
}

impl From<RunProgressQuery> for Command {
    fn from(_command: RunProgressQuery) -> Self {
        Command::new("RunProgress?")
    }
}

#[derive(Debug, Clone)]
pub enum DrawerStatus {
    Closed,
    Open,
}

#[derive(Debug, Clone)]
pub enum CoverPosition {
    Up,
    Down,
    Unknown,
}

#[derive(Debug, Clone)]
pub struct CoverPositionQuery;

impl CommandBuilder for CoverPositionQuery {
    type Response = CoverPosition;
    type Error = ErrorResponse;
    const COMMAND: &'static [u8] = b"eng?";
}

impl TryFrom<OkResponse> for CoverPosition {
    type Error = OkParseError;
    fn try_from(value: OkResponse) -> Result<Self, Self::Error> {
        match value
            .args
            .first()
            .unwrap()
            .clone()
            .try_into_string()?
            .to_lowercase()
            .as_str()
        {
            "up" => Ok(CoverPosition::Up),
            "down" => Ok(CoverPosition::Down),
            _ => {
                warn!(
                    "Unexpected cover position: {}",
                    value.args.first().unwrap().clone().try_into_string()?
                );
                Ok(CoverPosition::Unknown)
            }
        }
    }
}

#[derive(Debug, Clone)]
pub struct CoverHeatStatus {
    pub on: bool,
    pub temperature: f64,
}

// drawer?
// OK drawer? Closed

impl TryFrom<OkResponse> for DrawerStatus {
    type Error = OkParseError;
    fn try_from(value: OkResponse) -> Result<Self, Self::Error> {
        match value.args.first() {
            Some(Value::String(s)) if s == "Closed" => Ok(DrawerStatus::Closed),
            Some(Value::String(s)) if s == "Open" => Ok(DrawerStatus::Open),
            _ => Err(OkParseError::UnexpectedValues(
                value.clone(),
                "unexpected drawer status".to_string(),
            )),
        }
    }
}

#[derive(Debug, Clone)]
struct DrawerStatusQuery;

impl CommandBuilder for DrawerStatusQuery {
    type Response = DrawerStatus;
    type Error = ErrorResponse;
    const COMMAND: &'static [u8] = b"drawer?";
}

// cover?
// OK cover? UP 105.0

impl TryFrom<OkResponse> for CoverHeatStatus {
    type Error = OkParseError;
    fn try_from(value: OkResponse) -> Result<Self, Self::Error> {
        let position = value.args.first().unwrap().clone().try_into_string()?;
        let on = match position.to_lowercase().as_str() {
            "up" | "on" | "true" => true, // FIXME
            "down" | "off" | "false" => false,
            _ => {
                return Err(OkParseError::UnexpectedValues(
                    value.clone(),
                    "unexpected cover position".to_string(),
                ))
            }
        };
        let temperature = value.args.get(1).unwrap().clone().try_into_f64()?;
        Ok(CoverHeatStatus { on, temperature })
    }
}

#[derive(Debug, Clone)]
struct CoverHeatStatusQuery;

impl CommandBuilder for CoverHeatStatusQuery {
    type Response = CoverHeatStatus;
    type Error = ErrorResponse;
    const COMMAND: &'static [u8] = b"cover?";
}

pub struct QuickStatus {
    pub power: PowerStatus,
    pub drawer: DrawerStatus,
    pub cover: CoverHeatStatus,
    pub temperature_control: TemperatureControlStatus,
    pub sample_temperatures: Vec<f64>,
    pub block_temperatures: Vec<f64>,
    pub set_temperatures: SetTemperatures,
    pub runprogress: PossibleRunProgress,
}

impl TryFrom<OkResponse> for QuickStatus {
    type Error = OkParseError;
    fn try_from(value: OkResponse) -> Result<Self, Self::Error> {
        let args = value.args.into_iter();
        let mut args_deque = args.into_iter().collect::<VecDeque<_>>();
        info!("args_deque: {:?}", args_deque);

        fn into_okresponse(value: Value) -> Result<OkResponse, OkParseError> {
            let x = OkResponse::try_from(value.try_into_string()?)?;
            Ok(x)
        }

        let power = into_okresponse(args_deque.pop_front().unwrap())?.try_into()?;
        let drawer = into_okresponse(args_deque.pop_front().unwrap())?.try_into()?;
        let cover = into_okresponse(args_deque.pop_front().unwrap())?.try_into()?;
        let set_temperatures = into_okresponse(args_deque.pop_front().unwrap())?.try_into()?;
        let temperature_control = into_okresponse(args_deque.pop_front().unwrap())?.try_into()?;
        let sample_temperatures = into_okresponse(args_deque.pop_front().unwrap())?.try_into()?;
        let block_temperatures = into_okresponse(args_deque.pop_front().unwrap())?.try_into()?;
        let runprogress = into_okresponse(args_deque.pop_front().unwrap())?.try_into()?;

        Ok(QuickStatus {
            power,
            drawer,
            cover,
            temperature_control,
            sample_temperatures,
            block_temperatures,
            set_temperatures,
            runprogress,
        })
    }
}


impl std::fmt::Display for QuickStatus {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "Power: {:?}\nDrawer: {:?}\nCover: {:?}\nSample Temperatures: {:?}\nBlock Temperatures: {:?}",
            self.power,
            self.drawer,
            self.cover,
            self.sample_temperatures,
            self.block_temperatures,
        )
    }
}

impl QuickStatus {
    pub fn to_html(&self) -> String {
        format!(
            "<ul>
<li>Power: {:?} | Drawer: {:?} | Cover: {:?} ({:.1}°C)</li>
<li>Set Temperatures: {} {} Cover: {}</li>
<li>Current Temperatures - Sample: {} | Block: {}</li>
<li>Run Status: {}</li>
</ul>",
            self.power,
            self.drawer,
            {
                if self.cover.on {
                    "<span style=\"color: red\">on</span>"
                } else {
                    "<span style=\"color: blue\">off</span>"
                }
            },
            if self.cover.on {
                format!(
                    "<span style=\"color: red\">{:.1}</span>",
                    self.cover.temperature
                )
            } else {
                format!(
                    "<span style=\"color: gray\">{:.1}</span>",
                    self.cover.temperature
                )
            },
            self.set_temperatures
                .zones
                .iter()
                .zip(self.temperature_control.zones.iter())
                .enumerate()
                .map(|(i, (temp, enabled))| format!(
                    "Zone{}: {}{:.1}°C{}",
                    i + 1,
                    if *enabled { "<b>" } else { "<i>" },
                    temp,
                    if *enabled { "</b>" } else { "</i>" }
                ))
                .collect::<Vec<_>>()
                .join(" "),
            self.set_temperatures
                .fans
                .iter()
                .zip(self.temperature_control.fans.iter())
                .enumerate()
                .map(|(i, (temp, enabled))| format!(
                    "Fan{}: {}{:.1}°C{}",
                    i + 1,
                    if *enabled { "<b>" } else { "<i>" },
                    temp,
                    if *enabled { "</b>" } else { "</i>" }
                ))
                .collect::<Vec<_>>()
                .join(" "),
            if self.temperature_control.cover {
                format!("<b>{:.1}°C</b>", self.set_temperatures.cover)
            } else {
                format!("<i>{:.1}°C</i>", self.set_temperatures.cover)
            },
            self.sample_temperatures
                .iter()
                .map(|t| format!("{:.1}°C", t))
                .collect::<Vec<_>>()
                .join(", "),
            self.block_temperatures
                .iter()
                .map(|t| format!("{:.1}°C", t))
                .collect::<Vec<_>>()
                .join(", "),
            match &self.runprogress {
                PossibleRunProgress::Running(progress) => format!(
                    "Running {}: Stage {}, Cycle {}, Step {}",
                    progress.run_title, progress.stage, progress.cycle, progress.step
                ),
                PossibleRunProgress::NotRunning(_) => "Not Running".to_string(),
            }
        )
    }
}

#[derive(Debug, Clone)]
pub struct QuickStatusQuery;

impl CommandBuilder for QuickStatusQuery {
    type Response = QuickStatus;
    type Error = ErrorResponse;
    const COMMAND: &'static [u8] = b"RET $(POW?) $(drawer?) $(cover?) $(TBC:SETT?) $(TBC:CONT?) $(TBC:SampleTemperatures?) $(TBC:BlockTemperatures?) $(RunProgress?)";

    fn write_command(&self, bytes: &mut impl Write) -> Result<(), QSConnectionError> {
        bytes.write_all(Self::COMMAND)?;
        Ok(())
    }
}

// TBC:SETT?
// OK TBC:SETT? -Zone1=25.0 -Zone2=25.0 -Zone3=25.0 -Zone4=25.0 -Zone5=25.0 -Zone6=25.0 -Fan1=44.0 -Cover=30.0
#[derive(Debug, Clone)]
pub struct SetTemperaturesQuery;

#[derive(Debug, Clone)]
pub struct SetTemperatures {
    pub zones: Vec<f64>,
    pub fans: Vec<f64>,
    pub cover: f64,
}

impl TryFrom<OkResponse> for SetTemperatures {
    type Error = OkParseError;
    fn try_from(resp: OkResponse) -> Result<Self, Self::Error> {
        let mut zones = Vec::new();
        let mut fans = Vec::new();
        let mut cover = 0.0;

        for (key, value) in resp.options.iter() {
            if let Some(zone_num) = key.strip_prefix("Zone") {
                let zone_num = zone_num.parse::<usize>().unwrap();
                if zone_num != zones.len() + 1 {
                    return Err(OkParseError::UnexpectedValues(
                        resp.clone(),
                        format!("Zone {} is out of range", zone_num),
                    ));
                }
                zones.push(value.clone().try_into_f64().unwrap());
            } else if let Some(fan_num) = key.strip_prefix("Fan") {
                let fan_num = fan_num.parse::<usize>().unwrap();
                if fan_num != fans.len() + 1 {
                    return Err(OkParseError::UnexpectedValues(
                        resp.clone(),
                        format!("Fan {} is out of range", fan_num),
                    ));
                }
                fans.push(value.clone().try_into_f64().unwrap());
            } else if key == "Cover" {
                cover = value.clone().try_into_f64().unwrap();
            }
        }

        Ok(SetTemperatures { zones, fans, cover })
    }
}

impl CommandBuilder for SetTemperaturesQuery {
    type Response = SetTemperatures;
    type Error = ErrorResponse;
    const COMMAND: &'static [u8] = b"TBC:SETT?";
}
// TBC:SampleTemperatures?
// OK TBC:SampleTemperatures? 21.1804 21.1467 21.1609 21.1917 21.1596 21.1843

#[derive(Debug, Clone)]
pub struct SampleTemperaturesQuery;

impl CommandBuilder for SampleTemperaturesQuery {
    type Response = Vec<f64>;
    type Error = ErrorResponse;
    const COMMAND: &'static [u8] = b"TBC:SampleTemperatures?";
}

// TBC:CONT?
// OK TBC:CONT? -Zone1=False -Zone2=False -Zone3=False -Zone4=False -Zone5=False -Zone6=False -Fan1=False -Cover=False

#[derive(Debug, Clone)]
pub struct TemperatureControlStatus {
    pub zones: Vec<bool>,
    pub fans: Vec<bool>,
    pub cover: bool,
}

impl TryFrom<OkResponse> for TemperatureControlStatus {
    type Error = OkParseError;
    fn try_from(resp: OkResponse) -> Result<Self, Self::Error> {
        let mut zones = Vec::new();
        let mut fans = Vec::new();
        let mut cover = false;

        for (key, value) in resp.options.iter() {
            if let Some(zone_num) = key.strip_prefix("Zone") {
                let zone_num = zone_num.parse::<usize>().unwrap();
                if zone_num != zones.len() + 1 {
                    return Err(OkParseError::UnexpectedValues(
                        resp.clone(),
                        format!("Zone {} is out of range", zone_num),
                    ));
                }
                zones.push(value.clone().try_into_bool().unwrap());
            } else if let Some(fan_num) = key.strip_prefix("Fan") {
                let fan_num = fan_num.parse::<usize>().unwrap();
                if fan_num != fans.len() + 1 {
                    return Err(OkParseError::UnexpectedValues(
                        resp.clone(),
                        format!("Fan {} is out of range", fan_num),
                    ));
                }
                fans.push(value.clone().try_into_bool().unwrap());
            } else if key == "Cover" {
                cover = value.clone().try_into_bool().unwrap();
            }
        }

        Ok(TemperatureControlStatus { zones, fans, cover })
    }
}

#[derive(Debug, Clone)]
struct TemperatureControlStatusQuery;

impl CommandBuilder for TemperatureControlStatusQuery {
    type Response = TemperatureControlStatus;
    type Error = ErrorResponse;
    const COMMAND: &'static [u8] = b"TBC:CONT?";
}

#[derive(Debug, Clone)]
pub struct BlockTemperaturesQuery;

impl CommandBuilder for BlockTemperaturesQuery {
    type Response = Vec<f64>;
    type Error = ErrorResponse;
    const COMMAND: &'static [u8] = b"TBC:BlockTemperatures?";
}

impl TryFrom<OkResponse> for Vec<f64> {
    type Error = OkParseError;
    fn try_from(value: OkResponse) -> Result<Self, Self::Error> {
        let mut result = Vec::new();
        for v in &value.args {
            match v.clone().try_into_f64() {
                Ok(f) => result.push(f),
                Err(_) => {
                    return Err(OkParseError::UnexpectedValues(
                        value.clone(),
                        "not a float".to_string(),
                    ))
                }
            }
        }
        Ok(result)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::parser::{OkResponse, Value};

    #[test]
    fn test_sample_temperatures_response() {
        let ok_response = OkResponse {
            args: vec![
                Value::Float(21.1804),
                Value::Float(21.1467),
                Value::Float(21.1609),
                Value::Float(21.1917),
                Value::Float(21.1596),
                Value::Float(21.1843),
            ],
            options: ArgMap::new(),
        };

        let temps = Vec::<f64>::try_from(ok_response).unwrap();
        assert_eq!(
            temps,
            vec![21.1804, 21.1467, 21.1609, 21.1917, 21.1596, 21.1843]
        );
    }

    #[test]
    fn test_sample_temperatures_invalid_response() {
        let ok_response = OkResponse {
            args: vec![Value::Float(21.1804), Value::String("invalid".to_string())],
            options: ArgMap::new(),
        };

        let result = Vec::<f64>::try_from(ok_response);
        assert!(result.is_err());
    }

    #[test]
    fn test_set_temperatures_valid() {
        let ok_response = OkResponse {
            args: vec![],
            options: ArgMap::new()
                .with("Zone1", Value::Float(25.0))
                .with("Zone2", Value::Float(26.0))
                .with("Zone3", Value::Float(27.0))
                .with("Fan1", Value::Float(44.0))
                .with("Cover", Value::Float(30.0)),
        };

        let set_temps = SetTemperatures::try_from(ok_response).unwrap();
        assert_eq!(set_temps.zones, vec![25.0, 26.0, 27.0]);
        assert_eq!(set_temps.fans, vec![44.0]);
        assert_eq!(set_temps.cover, 30.0);
    }

    #[test]
    fn test_set_temperatures_out_of_order_zones() {
        let mut options = ArgMap::new();
        options.insert("Zone2", Value::Float(26.0));
        options.insert("Zone1", Value::Float(25.0));
        options.insert("Cover", Value::Float(30.0));

        let ok_response = OkResponse {
            args: vec![],
            options,
        };

        let result = SetTemperatures::try_from(ok_response);
        assert!(result.is_err());
        assert!(result
            .unwrap_err()
            .to_string()
            .contains("Zone 2 is out of range"));
    }

    #[test]
    fn test_set_temperatures_out_of_order_fans() {
        let ok_response = OkResponse {
            args: vec![],
            options: ArgMap::new()
                .with("Fan2", Value::Float(45.0))
                .with("Cover", Value::Float(30.0)),
        };

        let result = SetTemperatures::try_from(ok_response);
        assert!(result.is_err());
        assert!(result
            .unwrap_err()
            .to_string()
            .contains("Fan 2 is out of range"));
    }

    #[test]
    fn test_set_temperatures_empty() {
        let ok_response = OkResponse {
            args: vec![],
            options: ArgMap::new(),
        };

        let set_temps = SetTemperatures::try_from(ok_response).unwrap();
        assert!(set_temps.zones.is_empty());
        assert!(set_temps.fans.is_empty());
        assert_eq!(set_temps.cover, 0.0);
    }
}