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
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
//! Commands sent to the device and their responses
//!
//! This module contains structs that can be serialized into commands being sent to the device.
//! Each command implements the `UnaryCommand` trait which specifies the response type as an
//! associated type.
//!
//! It's typical to use the [roundtrip] method in order to send the command to a transport and
//! obtained its parsed response.

use alloc::vec::Vec;
use core::{convert::TryInto, fmt, fmt::Debug, ops::Deref, str::FromStr};
use std::ops::DerefMut;

use anyhow::Result;
use bytes::{Buf, BufMut, Bytes, BytesMut};
#[cfg(feature = "use_serde")]
use serde::{Deserialize, Serialize};
#[cfg(feature = "debug")]
use thiserror::Error;

use super::DeviceInfo;
use crate::{
    eeprom, packet::ParseError, util::TryBuf, util::TryBufError, FixedPoint, MasterStatus,
};

/// Maximum number of floats that can be read in a single command
pub const READ_FLOATS_MAX: usize = 14;

#[derive(Clone)]
#[cfg_attr(feature = "debug", derive(Debug, Error))]
pub enum ProtocolError {
    #[cfg_attr(feature = "debug", error("bad cmd id"))]
    BadCommandId,

    #[cfg_attr(feature = "debug", error("unexpected response type"))]
    UnexpectedResponseType,

    #[cfg_attr(feature = "debug", error("parse error: {0}"))]
    ParseError(ParseError),

    #[cfg_attr(
        feature = "debug",
        error("the received hardware id was malformed or empty")
    )]
    MalformedHardwareId,

    #[cfg_attr(feature = "debug", error("parse error: {0}"))]
    DecodeError(#[from] TryBufError),
}

#[derive(Clone)]
pub struct BytesWrap(pub Bytes);
impl fmt::Debug for BytesWrap {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        Debug::fmt(self.0.as_ref(), f)
    }
}
impl Deref for BytesWrap {
    type Target = Bytes;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}
impl DerefMut for BytesWrap {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.0
    }
}

#[derive(Clone)]
pub enum Value {
    Unknown(Bytes),
    Float(f32),
    FixedPoint(FixedPoint),
    Int(u16),
    Int32(u32),
}

impl Default for Value {
    fn default() -> Self {
        Value::Float(0.)
    }
}

impl From<f32> for Value {
    fn from(f: f32) -> Self {
        Value::Float(f)
    }
}

impl From<FixedPoint> for Value {
    fn from(fp: FixedPoint) -> Self {
        Value::FixedPoint(fp)
    }
}

impl From<u16> for Value {
    fn from(x: u16) -> Self {
        Value::Int(x)
    }
}

impl Value {
    pub fn into_bytes(self) -> Bytes {
        match self {
            Value::Unknown(b) => b,
            Value::Float(f) => Bytes::copy_from_slice(&f.to_le_bytes()),
            Value::FixedPoint(fp) => Bytes::copy_from_slice(&fp.to_u32().to_be_bytes()),
            Value::Int(i) => {
                let mut b = BytesMut::with_capacity(4);
                b.put_u16_le(i);
                b.put_u16(0x00);
                b.freeze()
            }
            Value::Int32(i) => Bytes::copy_from_slice(&i.to_be_bytes()),
        }
    }

    pub fn from_bytes(mut b: Bytes) -> Result<Self, TryBufError> {
        Ok(
            if b.len() == 4 && ((b[0] != 0 || b[1] != 0) && b[2] == 0 && b[3] == 0) {
                Value::Int(b.try_get_u16_le()?)
            } else {
                Value::Unknown(b)
            },
        )
    }
}

#[cfg(feature = "debug")]
impl fmt::Debug for Value {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let b = self.clone().into_bytes();
        match self {
            Value::Unknown(_) => {
                let float = if b.len() >= 4 {
                    Some(b.clone().get_f32_le())
                } else {
                    None
                };

                let u = if b.len() >= 4 {
                    Some(b.clone().get_u32())
                } else {
                    None
                };

                let fixed = if b.len() >= 4 {
                    Some(FixedPoint::from_u32(b.clone().get_u32()))
                } else {
                    None
                };

                let i = b[0];
                write!(
                    f,
                    "Value {{ Bytes: {:x?} (i: {:?} | i32: {:?} | f32: {:?} | fp: {:?}) }}",
                    b.as_ref(),
                    i,
                    u.unwrap_or_default(),
                    float.unwrap_or_default(),
                    fixed.unwrap_or_default()
                )
            }
            &Value::Float(val) => {
                write!(f, "Value {{ Bytes: {:x?} (f32: {:?}) }}", b.as_ref(), val)
            }
            &Value::FixedPoint(val) => {
                write!(
                    f,
                    "Value {{ Bytes: {:x?} (fp: {:?}) }}",
                    b.as_ref(),
                    val.to_f32(),
                )
            }
            &Value::Int(val) => {
                write!(f, "Value {{ Bytes: {:x?} (i: {:?}) }}", b.as_ref(), val)
            }
            &Value::Int32(val) => {
                write!(f, "Value {{ Bytes: {:x?} (i32: {:?}) }}", b.as_ref(), val)
            }
        }
    }
}

#[derive(Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "debug", derive(Debug))]
pub struct Addr {
    pub val: u32,
    pub len: u8,
    pub extra_bit: bool,
}

impl Addr {
    pub fn new(val: u16, len: u8) -> Self {
        Self {
            val: val as u32,
            len,
            extra_bit: true,
        }
    }

    pub fn new_with_extra_bit(val: u32, len: u8, extra_bit: bool) -> Self {
        Self {
            val,
            len,
            extra_bit,
        }
    }

    pub fn read(buf: &mut Bytes, len: u8) -> Result<Self, TryBufError> {
        match len {
            2 => Self::read_u16(buf),
            3 => Self::read_u24(buf),
            _ => panic!("invalid address len"),
        }
    }

    pub fn read_u16(buf: &mut Bytes) -> Result<Self, TryBufError> {
        let mut val = buf.try_get_u16()?;
        let extra_bit = (val & 0x80_00) != 0;

        val &= 0x0FFF;

        Ok(Self {
            val: val as _,
            len: 2,
            extra_bit,
        })
    }

    pub fn read_u24(buf: &mut Bytes) -> Result<Self, TryBufError> {
        let prefix = buf.try_get_u8()?;
        let extra_bit = (prefix & 0x80) != 0;
        let prefix = prefix & 0x0F;
        let addr = buf.try_get_u16()? as u32;
        let val = (prefix as u32) << 16 | addr;
        Ok(Self {
            val: val as _,
            len: 3,
            extra_bit,
        })
    }

    pub fn write(&self, buf: &mut BytesMut) {
        match self.len {
            2 => {
                let mut val = 0x80_00 | (self.val & 0x7F_FF);
                if !self.extra_bit {
                    val ^= 0x80_00;
                }
                buf.put_u16(val as _)
            }
            3 => {
                let mut val = 0x80_00_00 | (self.val & 0x7F_FF_FF);
                if !self.extra_bit {
                    val ^= 0x80_00_00;
                }
                buf.put_u8(((val >> 16) & 0xFF) as _);
                buf.put_u16(val as _);
            }
            _ => panic!("invalid address len"),
        }
    }
}

#[derive(Clone)]
#[cfg_attr(feature = "debug", derive(Debug))]
pub enum Commands {
    /// 0x31: Read hardware id
    ReadHardwareId,

    /// 0x14: Reads float data from a given base address. Max length is 14
    ReadFloats {
        addr: u16,
        len: u8,
    },

    /// 0x04: Writes byte data to the given address
    WriteMemory {
        addr: u16,
        data: BytesWrap,
    },

    /// 0x05: Reads byte data from the given address. Max read sizes are 61 bytes. (64 - crc - len - cmd)
    ReadMemory {
        addr: u16,
        size: u8,
    },

    /// 0x25: Sets the current configuration
    SetConfig {
        config: u8,
        reset: bool,
    },

    /// 0x34: Unary command to set the current source
    SetSource {
        source: u8,
    },

    /// 0x17 Unary command to set the master mute setting
    SetMute {
        value: bool,
    },

    /// 0x42: Set master volume
    SetVolume {
        value: Gain,
    },

    /// 0x30: Write biquad data
    WriteBiquad {
        addr: Addr,
        data: [Value; 5],
    },

    /// 0x19: Toggle biquad filter bypass
    WriteBiquadBypass {
        addr: Addr,
        value: bool,
    },

    /// 0x02: Read DSP data
    Read {
        addr: Addr,
        len: u8,
    },

    /// 0x13: Write dsp data
    Write {
        addr: Addr,
        value: Value,
    },

    /// 0x39: Start FIR load
    FirLoadStart {
        index: u8,
    },

    /// 0x3a: FIR Data
    FirLoadData {
        index: u8,
        data: Vec<f32>, // Max 15 floats
    },

    /// 0x3b: FIR Data Completed
    FirLoadEnd,

    // 0x3f: DIRAC bypass
    DiracBypass {
        value: u8,
    },

    // Speculative commands
    /// 0x12: Seen when restoring a configuration
    BulkLoad {
        // Initial payload:
        // 04 88 97 13 0f 00 00
        // 04: 4 | (Addr&0x0F0000 >> 12)
        // 88: (Addr&0xFF00 >> 8)
        // 97: (Addr&0xFF)
        // 13: constant
        // 0f: constant
        // 00: constant
        // 00: constant
        payload: BytesWrap,
    },

    /// 0x06: Seen after 0x12 in configuration restore
    BulkLoadFilterData {
        // Initial packet:
        // 02 05 (addr+3 u16)
        payload: BytesWrap,
    },

    // 0x07: Seen in configuration restore
    Unk07 {
        payload: u8,
    },

    SwitchMux {
        addr: Addr, //  start addr
        max: u8,    // mux max
        arg: bool,  // muxmax |= 0x80 if arg
        slot: u8,   // slot
    },

    Unknown {
        cmd_id: u8,
        payload: BytesWrap,
    },
}

impl Commands {
    pub fn from_bytes(mut frame: Bytes) -> Result<Commands, ProtocolError> {
        Ok(match frame.try_get_u8()? {
            0x02 => Commands::Read {
                addr: {
                    let len = if frame.len() >= 3 { 3 } else { 2 };
                    Addr::read(&mut frame, len)?
                },
                len: frame.try_get_u8()?,
            },
            0x04 => Commands::WriteMemory {
                addr: frame.try_get_u16()?,
                data: BytesWrap(frame),
            },
            0x05 => Commands::ReadMemory {
                addr: frame.try_get_u16()?,
                size: frame.try_get_u8()?,
            },
            0x06 => Commands::BulkLoadFilterData {
                payload: BytesWrap(frame),
            },
            0x07 => Commands::Unk07 {
                payload: frame.try_get_u8()?,
            },
            0x12 => Commands::BulkLoad {
                payload: BytesWrap(frame),
            },
            0x13 => {
                let len = if frame.len() >= 7 { 3 } else { 2 };
                Commands::Write {
                    addr: Addr::read(&mut frame, len)?,
                    value: Value::from_bytes(frame)?,
                }
            }
            0x14 => Commands::ReadFloats {
                addr: frame.try_get_u16()?,
                len: frame.try_get_u8()?,
            },
            0x17 => Commands::SetMute {
                value: frame.try_get_u8()? != 0,
            },
            0x19 => {
                let len = if frame.len() > 2 { 3 } else { 2 };
                let addr = Addr::read(&mut frame, len)?;

                Commands::WriteBiquadBypass {
                    value: addr.extra_bit,
                    addr,
                }
            }
            0x25 => Commands::SetConfig {
                config: frame.try_get_u8()?,
                reset: frame.try_get_u8()? != 0,
            },
            0x31 => Commands::ReadHardwareId {},
            0x29 => {
                let addr = Addr::read(&mut frame, 2)?;
                let mut max = frame.try_get_u8()?;
                let arg = max & 0x80 != 0;
                if arg {
                    max ^= 0x80;
                }
                let slot = frame.try_get_u8()?;

                Commands::SwitchMux {
                    addr,
                    max,
                    arg,
                    slot,
                }
            }
            0x30 => Commands::WriteBiquad {
                addr: {
                    let len = if frame.len() > 24 { 3 } else { 2 };
                    Addr::read(&mut frame, len)?
                },
                data: {
                    frame.try_get_u16()?;
                    let mut data: [Value; 5] = Default::default();
                    for f in data.iter_mut() {
                        *f = Value::Unknown(Bytes::copy_from_slice(&frame[0..4]));
                        frame.advance(4);
                    }
                    data
                },
            },
            0x34 => Commands::SetSource {
                source: frame.try_get_u8()?,
            },
            0x39 => Commands::FirLoadStart {
                index: frame.try_get_u8()?,
            },
            0x3a => Commands::FirLoadData {
                index: frame.try_get_u8()?,
                data: {
                    let mut data = Vec::with_capacity(15);
                    while frame.len() > 4 {
                        data.push(frame.try_get_f32_le()?);
                    }
                    data
                },
            },
            0x3b => Commands::FirLoadEnd,
            0x42 => Commands::SetVolume {
                value: frame.try_get_u8()?.into(),
            },
            cmd_id => Commands::Unknown {
                cmd_id,
                payload: BytesWrap(frame),
            },
        })
    }

    pub fn to_bytes(&self) -> Bytes {
        let mut f = BytesMut::with_capacity(64);

        match self {
            Commands::ReadHardwareId => {
                f.put_u8(0x31);
            }
            &Commands::ReadFloats { addr, len } => {
                f.put_u8(0x14);
                f.put_u16(addr);
                f.put_u8(len);
            }
            &Commands::ReadMemory { addr, size } => {
                f.put_u8(0x05);
                f.put_u16(addr);
                f.put_u8(size);
            }
            &Commands::WriteMemory { addr, ref data } => {
                f.put_u8(0x04);
                f.put_u16(addr);
                f.put(data.0.clone());
            }
            &Commands::SetConfig { config, reset } => {
                f.put_u8(0x25);
                f.put_u8(config);
                f.put_u8(reset as u8);
            }
            &Commands::SetSource { source } => {
                f.put_u8(0x34);
                f.put_u8(source);
            }
            &Commands::SetMute { value } => {
                f.put_u8(0x17);
                f.put_u8(value as u8);
            }
            &Commands::SetVolume { value } => {
                f.put_u8(0x42);
                f.put_u8((value).into());
            }
            Commands::WriteBiquad { addr, data } => {
                f.put_u8(0x30);
                addr.write(&mut f);
                f.put_u16(0x0000);
                for coeff in data.iter() {
                    f.put(coeff.clone().into_bytes());
                }
            }
            &Commands::WriteBiquadBypass { mut addr, value } => {
                f.put_u8(0x19);
                addr.extra_bit = value;
                addr.write(&mut f);
            }
            &Commands::Read { addr, len } => {
                f.put_u8(0x2);
                addr.write(&mut f);
                f.put_u8(len);
            }
            &Commands::Write { addr, ref value } => {
                f.put_u8(0x13);
                addr.write(&mut f);
                f.put(value.clone().into_bytes());
            }

            &Commands::FirLoadStart { index } => {
                f.put_u8(0x39);
                f.put_u8(index);
            }
            &Commands::FirLoadData { index, ref data } => {
                f.put_u8(0x3a);
                f.put_u8(index);
                for &coeff in data {
                    f.put_f32_le(coeff);
                }
            }
            &Commands::FirLoadEnd => {
                f.put_u8(0x3b);
            }
            Commands::BulkLoad { payload } => {
                f.put_u8(0x12);
                f.put(payload.0.clone());
            }
            Commands::BulkLoadFilterData { payload } => {
                f.put_u8(0x06);
                f.put(payload.0.clone());
            }
            &Commands::DiracBypass { value } => {
                f.put_u8(0x3f);
                f.put_u8(value);
            }
            &Commands::SwitchMux {
                addr,
                mut max,
                arg,
                slot,
            } => {
                f.put_u8(0x29);
                addr.write(&mut f);
                if arg {
                    max |= 0x80;
                }
                f.put_u8(max);
                f.put_u8(slot);
            }
            &Commands::Unk07 { payload } => {
                f.put_u8(0x07);
                f.put_u8(payload);
            }
            &Commands::Unknown {
                cmd_id,
                ref payload,
            } => {
                f.put_u8(cmd_id);
                f.put(payload.0.clone());
            }
        }
        f.freeze()
    }

    pub fn matches_response(&self, response: &Responses) -> bool {
        match self {
            &Commands::ReadMemory { addr, size } => {
                if let Responses::MemoryData(data) = response {
                    data.base == addr && data.data.len() == size as usize
                } else {
                    false
                }
            }
            &Commands::ReadFloats { addr, len } => {
                if let Responses::FloatData(data) = response {
                    data.base == addr && data.data.len() == len as usize
                } else {
                    false
                }
            }
            Commands::ReadHardwareId => matches!(response, Responses::HardwareId { .. }),
            Commands::SetConfig { .. } => matches!(response, Responses::ConfigChanged),
            Commands::FirLoadStart { .. } => matches!(response, Responses::FirLoadSize { .. }),
            &Commands::Unk07 { .. } => matches!(response, Responses::Unk02 { .. }),
            &Commands::Read { .. } => matches!(response, Responses::Read { .. }),
            Commands::WriteMemory { .. }
            | Commands::SetSource { .. }
            | Commands::SetMute { .. }
            | Commands::SetVolume { .. }
            | Commands::WriteBiquad { .. }
            | Commands::WriteBiquadBypass { .. }
            | Commands::Write { .. }
            | Commands::FirLoadData { .. }
            | Commands::FirLoadEnd
            | Commands::BulkLoad { .. }
            | Commands::BulkLoadFilterData { .. }
            | Commands::DiracBypass { .. }
            | Commands::SwitchMux { .. } => matches!(response, Responses::Ack),
            Commands::Unknown { .. } => true,
        }
    }

    pub fn mute(addr: Addr, value: bool) -> Self {
        let value: u16 = if value {
            WriteInt::DISABLED
        } else {
            WriteInt::ENABLED
        };

        Commands::Write {
            addr,
            value: Value::Int(value),
        }
    }
}

#[derive(Clone)]
#[cfg_attr(feature = "debug", derive(Debug))]
pub enum Responses {
    Ack,
    Read {
        addr: Addr,
        data: Vec<Value>,
    },
    MemoryData(MemoryView),
    FloatData(FloatView),
    HardwareId {
        payload: BytesWrap,
    },
    FirLoadSize {
        size: u16,
    },

    /// Speculative commands
    ConfigChanged,

    // 0x02: Seen during configuration restore as a response to [`Commands::Unk07`]
    Unk02,

    Unknown {
        cmd_id: u8,
        payload: BytesWrap,
    },
}

impl Responses {
    pub fn from_bytes(mut frame: Bytes) -> Result<Responses, ProtocolError> {
        if frame.is_empty() {
            return Ok(Responses::Ack);
        }

        Ok(match frame[0] {
            0x02 => Responses::Read {
                addr: {
                    frame.try_get_u8()?;
                    Addr::read(&mut frame, 2)?
                },
                data: {
                    frame
                        .chunks(4)
                        .filter_map(|x| Value::from_bytes(Bytes::copy_from_slice(x)).ok())
                        .collect()
                },
            },
            0x05 => Responses::MemoryData(MemoryView::from_packet(frame)?),
            0x14 => Responses::FloatData(FloatView::from_packet(frame)?),
            0x31 => Responses::HardwareId {
                payload: {
                    frame.try_get_u8()?;
                    BytesWrap(frame)
                },
            },
            0x39 => Responses::FirLoadSize {
                size: {
                    frame.try_get_u8()?; // Consume command id
                    frame.try_get_u16()?
                },
            },
            0xab => Responses::ConfigChanged,
            cmd_id => Responses::Unknown {
                cmd_id,
                payload: BytesWrap(frame),
            },
        })
    }

    pub fn to_bytes(&self) -> Bytes {
        let mut f = BytesMut::with_capacity(64);
        match self {
            Responses::Ack => {}
            Responses::MemoryData(data) => {
                f.put_u8(0x05);
                f.put_u16(data.base);
                f.put(data.data.clone());
            }
            Responses::FloatData(data) => {
                f.put_u8(0x14);
                f.put_u16(data.base);

                for &item in &data.data {
                    f.put_f32_le(item);
                }
            }
            &Responses::Unknown {
                cmd_id,
                ref payload,
            } => {
                f.put_u8(cmd_id);
                f.put(payload.0.clone());
            }
            Responses::HardwareId { payload } => {
                f.put_u8(0x31);
                f.put(payload.0.clone());
            }
            &Responses::FirLoadSize { size } => {
                f.put_u8(0x39);
                f.put_u16(size);
            }
            Responses::ConfigChanged => {
                f.put_u8(0xab);
            }
            Responses::Read { addr, data } => {
                f.put_u8(0x02);
                addr.write(&mut f);
                for d in data {
                    f.put(d.clone().into_bytes())
                }
            }
            &Responses::Unk02 => {
                f.put_u8(0x02);
            }
        }
        f.freeze()
    }

    pub fn is_memory_view(&self) -> bool {
        matches!(self, Responses::MemoryData(_))
    }

    pub fn into_memory_view(self) -> Result<MemoryView, ProtocolError> {
        match self {
            Responses::MemoryData(m) => Ok(m),
            _ => Err(ProtocolError::UnexpectedResponseType),
        }
    }

    pub fn is_float_view(&self) -> bool {
        matches!(self, Responses::FloatData(_))
    }

    pub fn into_float_view(self) -> Result<FloatView, ProtocolError> {
        match self {
            Responses::FloatData(m) => Ok(m),
            _ => Err(ProtocolError::UnexpectedResponseType),
        }
    }

    pub fn is_hardware_id(&self) -> bool {
        matches!(self, Responses::HardwareId { .. })
    }

    pub fn into_hardware_id(self) -> Result<u8, ProtocolError> {
        match self {
            Responses::HardwareId { payload } => {
                Ok(*payload.last().ok_or(ProtocolError::MalformedHardwareId)?)
            }
            _ => Err(ProtocolError::UnexpectedResponseType),
        }
    }

    pub fn is_ack(&self) -> bool {
        matches!(self, Responses::Ack)
    }

    pub fn into_ack(self) -> Result<(), ProtocolError> {
        match self {
            Responses::Ack => Ok(()),
            _ => Err(ProtocolError::UnexpectedResponseType),
        }
    }

    pub fn is_config_changed(&self) -> bool {
        matches!(self, Responses::ConfigChanged)
    }

    pub fn into_config_changed(self) -> Result<(), ProtocolError> {
        match self {
            Responses::ConfigChanged => Ok(()),
            _ => Err(ProtocolError::UnexpectedResponseType),
        }
    }

    pub fn is_fir_size(&self) -> bool {
        matches!(self, Responses::FirLoadSize { .. })
    }

    pub fn into_fir_size(self) -> Result<u16, ProtocolError> {
        match self {
            Responses::FirLoadSize { size } => Ok(size),
            _ => Err(ProtocolError::UnexpectedResponseType),
        }
    }
}

/// Parsable response type
pub trait UnaryResponse: Sized {
    fn from_packet(packet: Bytes) -> Result<Self, ProtocolError>;
}

#[derive(Copy, Clone, PartialEq, Default)]
#[cfg_attr(feature = "debug", derive(Debug))]
#[cfg_attr(
    feature = "serde",
    derive(Serialize, Deserialize, schemars::JsonSchema)
)]
/// A gain between the minimum and maximum allowed values
pub struct Gain(pub f32);

impl Gain {
    pub const MIN: f32 = -127.;
    pub const MAX: f32 = 0.;
}

impl From<Gain> for u8 {
    fn from(val: Gain) -> Self {
        (val.0.abs() * 2.) as u8
    }
}

impl From<u8> for Gain {
    fn from(val: u8) -> Self {
        Self(-0.5 * (val as f32))
    }
}

impl FromStr for Gain {
    type Err = <f32 as FromStr>::Err;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Ok(Gain(<f32 as FromStr>::from_str(s)?))
    }
}
/// Memory views can be extended with multiple contiguous reads
pub trait ExtendView {
    fn extend_with(&mut self, other: Self) -> Result<(), ExtendError>;
}

#[cfg_attr(feature = "debug", derive(Debug, Error))]
pub enum ExtendError {
    #[cfg_attr(feature = "debug", error("the corresponding bases do not align"))]
    MismatchingBases,
}

/// A contiguous view of floats read from the device
#[derive(Clone, Default)]
#[cfg_attr(feature = "debug", derive(Debug))]
pub struct FloatView {
    pub base: u16,
    pub data: Vec<f32>,
}

impl FloatView {
    pub fn get(&self, addr: u16) -> f32 {
        self.data[(addr - self.base) as usize]
    }
}

impl ExtendView for FloatView {
    fn extend_with(&mut self, other: Self) -> Result<(), ExtendError> {
        // Check that the `other` starts a the end of `self`
        let expected_start = self.base + (self.data.len() as u16);
        if other.base != expected_start {
            return Err(ExtendError::MismatchingBases);
        }

        self.data.extend(other.data.iter());

        Ok(())
    }
}

impl UnaryResponse for FloatView {
    fn from_packet(mut packet: Bytes) -> Result<Self, ProtocolError> {
        packet.try_get_u8()?; // Discard command id 0x14
        let base = packet.try_get_u16()?;
        let data = packet
            .chunks_exact(4)
            .map(|x| x.try_into().unwrap())
            .map(f32::from_le_bytes)
            .collect();

        Ok(FloatView { base, data })
    }
}

#[derive(Clone, Default)]
pub struct MemoryView {
    pub base: u16,
    pub data: Bytes,
}

impl MemoryView {
    pub fn read_at(&self, addr: u16, len: u8) -> Option<&'_ [u8]> {
        if addr < self.base || addr as usize > self.base as usize + self.data.len() {
            return None;
        }

        let start = (addr - self.base) as usize;
        let end = start + len as usize;

        if self.data.len() < end {
            return None;
        }

        Some(&self.data[start..end])
    }

    pub fn read_u8(&self, addr: u16) -> Option<u8> {
        Some(self.read_at(addr, 1)?[0])
    }

    pub fn read_u16(&self, addr: u16) -> Option<u16> {
        Some(u16::from_be_bytes(
            self.read_at(addr, 2)?.try_into().unwrap(),
        ))
    }
}

impl UnaryResponse for MemoryView {
    fn from_packet(mut packet: Bytes) -> Result<Self, ProtocolError> {
        packet.try_get_u8()?; // Discard command id 0x5
        let base = packet.try_get_u16()?;

        Ok(MemoryView { base, data: packet })
    }
}

#[cfg(feature = "debug")]
impl fmt::Debug for MemoryView {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "MemoryView {{ base: {:04x?}, data: {:02x?} }}",
            self.base,
            self.data.as_ref()
        )
    }
}

impl ExtendView for MemoryView {
    fn extend_with(&mut self, other: Self) -> Result<(), ExtendError> {
        // Check that the `other` starts a the end of `self`
        let expected_start = self.base + (self.data.len() as u16);
        if other.base != expected_start {
            return Err(ExtendError::MismatchingBases);
        }

        let mut data: BytesMut = BytesMut::with_capacity(self.data.len() + other.data.len());
        data.extend(self.data.iter());
        data.extend(other.data.iter());

        // Truncate anything past 0xFFFF since it's probably garbage
        data.truncate((u16::MAX as usize) - (self.base as usize));

        self.data = data.freeze();

        Ok(())
    }
}

/// 0x13: Write an integer value
#[derive(Clone, Default)]
#[cfg_attr(feature = "debug", derive(Debug))]
pub struct WriteInt;

impl WriteInt {
    pub const DISABLED: u16 = 1;
    pub const ENABLED: u16 = 2;
    pub const BYPASSED: u16 = 3;
}

/// Types that can be read from a contiguous memory representation
pub trait FromMemory<T: Sized>
where
    Self: Sized,
{
    fn from_memory(device_info: &DeviceInfo, view: &MemoryView) -> Result<Self>;
}

impl FromMemory<MasterStatus> for MasterStatus
where
    Self: Sized,
{
    fn from_memory(device_info: &DeviceInfo, view: &MemoryView) -> Result<Self> {
        Ok(Self {
            preset: view.read_u8(eeprom::PRESET),
            source: view
                .read_u8(eeprom::SOURCE)
                .or_else(|| view.read_u8(eeprom::SOURCE_ASYNC))
                .map(|id| super::Source::from_id(id, device_info)),
            volume: view.read_u8(eeprom::MASTER_VOLUME).map(Into::into),
            mute: view.read_u8(eeprom::MUTE).map(|x| x == 1),
            dirac: if device_info.supports_dirac() {
                view.read_u8(eeprom::DIRAC_BYPASS).map(|x| x == 0)
            } else {
                None
            },
        })
    }
}

#[cfg(test)]
mod test {
    use super::*;

    #[test]
    fn test_addr() {
        let tests: &[(&[u8], Addr)] = &[
            // Should trim the prefixed 0x80
            (
                &[0x80, 0x10],
                Addr {
                    extra_bit: true,
                    val: 0x10,
                    len: 2,
                },
            ),
            // Should trim the prefixed 0x80
            (
                &[0x80, 0x10, 0x00],
                Addr {
                    extra_bit: true,
                    val: 0x10_00,
                    len: 3,
                },
            ),
            (
                &[0x8F, 0x10],
                Addr {
                    extra_bit: true,
                    val: 0xF10,
                    len: 2,
                },
            ),
            (
                &[0x8F, 0x10, 0x00],
                Addr {
                    extra_bit: true,
                    val: 0x0F_10_00,
                    len: 3,
                },
            ),
        ];

        for (bytes, addr) in tests {
            let data = Bytes::from_static(bytes);
            let parsed = Addr::read(&mut data.clone(), data.len() as _).unwrap();
            assert_eq!(addr, &parsed);

            let mut written_bytes = BytesMut::new();
            addr.write(&mut written_bytes);
            assert_eq!(&written_bytes, bytes);
        }
    }

    #[test]
    fn test_read_reg() {
        let cmd = Commands::ReadMemory {
            addr: 0xffda,
            size: 4,
        };

        let mut req_packet = cmd.to_bytes();
        assert_eq!(req_packet.get_u8(), 0x05);
        assert_eq!(req_packet.get_u16(), 0xffda);
        assert_eq!(req_packet.get_u8(), 4);
        assert_eq!(req_packet.remaining(), 0);

        let response = Bytes::from_static(&[0x5, 0xff, 0xda, 0x1, 0x2, 0x3, 0x4, 0x0]);
        let memory = Responses::from_bytes(response)
            .ok()
            .unwrap()
            .into_memory_view()
            .ok()
            .unwrap();
        let data = memory.read_at(0xffda, 4);

        assert_eq!(data.unwrap(), &[0x1, 0x2, 0x3, 0x4]);
        assert_eq!(memory.read_u16(0xFFDA), Some(0x0102));
    }

    #[test]
    fn test_master_status() {
        let cmd = Commands::ReadMemory {
            addr: 0xffd8,
            size: 9,
        };

        let mut req_packet = cmd.to_bytes();
        assert_eq!(req_packet.get_u8(), 0x05);
        assert_eq!(req_packet.get_u16(), 0xffd8);
        assert_eq!(req_packet.get_u8(), 9);
        assert_eq!(req_packet.remaining(), 0);

        let response = Bytes::from_static(&[
            0x5, 0xff, 0xd8, 0x0, 0x1, 0x4f, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
        ]);
        let memory = Responses::from_bytes(response)
            .ok()
            .unwrap()
            .into_memory_view()
            .ok()
            .unwrap();

        let device_info = DeviceInfo {
            hw_id: 10,
            dsp_version: 100,
            serial: 0,
        };
        let status = MasterStatus::from_memory(&device_info, &memory).unwrap();
        assert!(status.eq(&MasterStatus {
            preset: Some(0),
            source: Some(crate::Source::Toslink),
            volume: Some(Gain(-39.5)),
            mute: Some(false),
            dirac: None,
        }));
    }

    #[test]
    fn test_combine() {
        let mut f1 = FloatView {
            base: 0,
            data: (0u16..10).map(|x| x.into()).collect(),
        };

        let f2 = FloatView {
            base: 10,
            data: (10u16..20).map(|x| x.into()).collect(),
        };

        f1.extend_with(f2).ok().unwrap();
        assert_eq!(f1.base, 0);
        assert_eq!(f1.data.len(), 20);
        assert!(f1
            .data
            .into_iter()
            .eq((0u16..20).into_iter().map(|x| -> f32 { x.into() })));

        let mut m1 = MemoryView {
            base: 0,
            data: (0u8..10).collect(),
        };

        let m2 = MemoryView {
            base: 10,
            data: (10u8..20).collect(),
        };

        m1.extend_with(m2).ok().unwrap();
        assert_eq!(m1.base, 0);
        assert_eq!(m1.data.len(), 20);
        assert!(m1.data.into_iter().eq((0u8..20).into_iter()));
    }
}