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
use crate::{SMBiosStruct, UndefinedStruct};
use serde::{ser::SerializeStruct, Serialize, Serializer};
use std::fmt;
use std::ops::Deref;

/// # Portable Battery (Type 22)
///
/// This structure describes the attributes of the portable battery or batteries for the system. The structure
/// contains the static attributes for the group. Each structure describes a single battery pack’s attributes.
///
/// Compliant with:
/// DMTF SMBIOS Reference Specification 3.4.0 (DSP0134)
/// Document Date: 2020-07-17
pub struct SMBiosPortableBattery<'a> {
    parts: &'a UndefinedStruct,
}

impl<'a> SMBiosStruct<'a> for SMBiosPortableBattery<'a> {
    const STRUCT_TYPE: u8 = 22u8;

    fn new(parts: &'a UndefinedStruct) -> Self {
        Self { parts }
    }

    fn parts(&self) -> &'a UndefinedStruct {
        self.parts
    }
}

impl<'a> SMBiosPortableBattery<'a> {
    /// Identifies the location of the battery
    pub fn location(&self) -> Option<String> {
        self.parts.get_field_string(0x04)
    }

    /// Names the company that manufactured the battery
    pub fn manufacturer(&self) -> Option<String> {
        self.parts.get_field_string(0x05)
    }

    /// The date on which the battery was manufactured.
    ///
    /// Version 2.2+ implementations that use a Smart
    /// Battery set this field to 0 (no string) to indicate
    /// that the SBDS Manufacture Date field contains
    /// the information.
    pub fn manufacture_date(&self) -> Option<String> {
        self.parts.get_field_string(0x06)
    }

    /// The serial number for the battery
    ///
    /// Version 2.2+ implementations that use a Smart
    /// Battery set this field to 0 (no string) to indicate
    /// that the SBDS Serial Number field contains the
    /// information.
    pub fn serial_number(&self) -> Option<String> {
        self.parts.get_field_string(0x07)
    }

    /// Names the battery device
    ///
    /// EXAMPLE: "DR-36"
    pub fn device_name(&self) -> Option<String> {
        self.parts.get_field_string(0x08)
    }

    /// Identifies the battery chemistry
    ///
    /// Version 2.2+ implementations that use a Smart
    /// Battery set this field to 02h (Unknown) to
    /// indicate that the SBDS Device Chemistry field
    /// contains the information.
    pub fn device_chemistry(&self) -> Option<PortableBatteryDeviceChemistryData> {
        self.parts
            .get_field_byte(0x09)
            .map(|raw| PortableBatteryDeviceChemistryData::from(raw))
    }

    /// Design capacity of the battery in mWatt-hours
    ///
    /// If the value is unknown, the field contains 0.
    ///
    /// For version 2.2+ implementations, this value is
    /// multiplied by the 'design_capacity_multiplier' to
    /// produce the actual value.
    pub fn design_capacity(&self) -> Option<PortableBatteryDesignCapacity> {
        self.parts
            .get_field_word(0x0A)
            .map(|raw| PortableBatteryDesignCapacity::from(raw))
    }

    /// Design voltage of the battery in mVolts
    ///
    /// If the value is unknown, the field contains 0.
    pub fn design_voltage(&self) -> Option<PortableBatteryDesignVoltage> {
        self.parts
            .get_field_word(0x0C)
            .map(|raw| PortableBatteryDesignVoltage::from(raw))
    }

    /// Contains the Smart Battery Data Specification version number
    /// supported by this battery
    ///
    /// If the battery does not support the function, no
    /// string is supplied.
    pub fn sbds_version_number(&self) -> Option<String> {
        self.parts.get_field_string(0x0E)
    }

    /// Maximum error (as a percentage in the range 0
    /// to 100) in the Watt-hour data reported by the
    /// battery, indicating an upper bound on how much
    /// additional energy the battery might have above
    /// the energy it reports having
    ///
    /// If the value is unknown, the field contains FFh.
    pub fn maximum_error_in_battery_data(&self) -> Option<u8> {
        self.parts.get_field_byte(0x0F)
    }

    /// 16-bit value that identifies the battery’s serial
    /// number
    ///
    /// This value, when combined with the
    /// Manufacturer, Device Name, and Manufacture
    /// Date, uniquely identifies the battery. The Serial
    /// Number field must be set to 0 (no string) for this
    /// field to be valid.
    pub fn sbds_serial_number(&self) -> Option<u16> {
        self.parts.get_field_word(0x10)
    }

    /// Date the cell pack was manufactured, in packed
    /// format
    pub fn sbds_manufacture_date(&self) -> Option<u16> {
        self.parts.get_field_word(0x12)
    }

    /// Number of the string that identifies the battery
    /// chemistry (for example, “PbAc”)
    /// The Device Chemistry field must be set to 02h
    /// (Unknown) for this field to be valid.
    pub fn sbds_device_chemistry(&self) -> Option<String> {
        self.parts.get_field_string(0x14)
    }

    /// Multiplication factor of the Design Capacity
    /// value, which assures that the mWatt hours value
    /// does not overflow for SBDS implementations
    ///
    /// The multiplier default is 1, SBDS
    /// implementations use the value 10 to correspond
    /// to the data as returned from the SBDS Function
    /// 18h.
    pub fn design_capacity_multiplier(&self) -> Option<u8> {
        self.parts.get_field_byte(0x15)
    }

    /// Contains OEM- or BIOS vendor-specific
    /// information
    pub fn oem_specific(&self) -> Option<u32> {
        self.parts.get_field_dword(0x16)
    }
}

impl fmt::Debug for SMBiosPortableBattery<'_> {
    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt.debug_struct(std::any::type_name::<SMBiosPortableBattery<'_>>())
            .field("header", &self.parts.header)
            .field("location", &self.location())
            .field("manufacturer", &self.manufacturer())
            .field("manufacture_date", &self.manufacture_date())
            .field("serial_number", &self.serial_number())
            .field("device_name", &self.device_name())
            .field("device_chemistry", &self.device_chemistry())
            .field("design_capacity", &self.design_capacity())
            .field("design_voltage", &self.design_voltage())
            .field("sbds_version_number", &self.sbds_version_number())
            .field(
                "maximum_error_in_battery_data",
                &self.maximum_error_in_battery_data(),
            )
            .field("sbds_serial_number", &self.sbds_serial_number())
            .field("sbds_manufacture_date", &self.sbds_manufacture_date())
            .field("sbds_device_chemistry", &self.sbds_device_chemistry())
            .field(
                "design_capacity_multiplier",
                &self.design_capacity_multiplier(),
            )
            .field("oem_specific", &self.oem_specific())
            .finish()
    }
}

impl Serialize for SMBiosPortableBattery<'_> {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let mut state = serializer.serialize_struct("SMBiosPortableBattery", 16)?;
        state.serialize_field("header", &self.parts.header)?;
        state.serialize_field("location", &self.location())?;
        state.serialize_field("manufacturer", &self.manufacturer())?;
        state.serialize_field("manufacture_date", &self.manufacture_date())?;
        state.serialize_field("serial_number", &self.serial_number())?;
        state.serialize_field("device_name", &self.device_name())?;
        state.serialize_field("device_chemistry", &self.device_chemistry())?;
        state.serialize_field("design_capacity", &self.design_capacity())?;
        state.serialize_field("design_voltage", &self.design_voltage())?;
        state.serialize_field("sbds_version_number", &self.sbds_version_number())?;
        state.serialize_field(
            "maximum_error_in_battery_data",
            &self.maximum_error_in_battery_data(),
        )?;
        state.serialize_field("sbds_serial_number", &self.sbds_serial_number())?;
        state.serialize_field("sbds_manufacture_date", &self.sbds_manufacture_date())?;
        state.serialize_field("sbds_device_chemistry", &self.sbds_device_chemistry())?;
        state.serialize_field(
            "design_capacity_multiplier",
            &self.design_capacity_multiplier(),
        )?;
        state.serialize_field("oem_specific", &self.oem_specific())?;
        state.end()
    }
}

/// # Portable Battery - Device Chemistry Data
pub struct PortableBatteryDeviceChemistryData {
    /// Raw value
    ///
    /// _raw_ is most useful when _value_ is None.
    /// This is most likely to occur when the standard was updated but
    /// this library code has not been updated to match the current
    /// standard.
    pub raw: u8,
    /// The contained [PortableBatteryDeviceChemistry] value
    pub value: PortableBatteryDeviceChemistry,
}

impl fmt::Debug for PortableBatteryDeviceChemistryData {
    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt.debug_struct(std::any::type_name::<PortableBatteryDeviceChemistryData>())
            .field("raw", &self.raw)
            .field("value", &self.value)
            .finish()
    }
}

impl Serialize for PortableBatteryDeviceChemistryData {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let mut state = serializer.serialize_struct("PortableBatteryDeviceChemistryData", 2)?;
        state.serialize_field("raw", &self.raw)?;
        state.serialize_field("value", &self.value)?;
        state.end()
    }
}

impl Deref for PortableBatteryDeviceChemistryData {
    type Target = PortableBatteryDeviceChemistry;

    fn deref(&self) -> &Self::Target {
        &self.value
    }
}

/// # Portable Battery - Device Chemistry
#[derive(Serialize, Debug, PartialEq, Eq)]
pub enum PortableBatteryDeviceChemistry {
    /// Other
    Other,
    /// Unknown
    ///
    /// Version 2.2+ implementations that use a Smart Battery
    /// set this field to 02h (Unknown) to indicate that the
    /// 'sbds_device_chemistry' field contains the information.
    Unknown,
    /// Lead Acid
    LeadAcit,
    /// Nickel Cadmium
    NickelCadmium,
    /// Nickel metal hydride
    NickelMetalHydride,
    /// Lithium-ion
    LithiumIon,
    /// Zinc air
    ZincAir,
    /// Lithium Polymer
    LithiumPolymer,
    /// A value unknown to this standard, check the raw value
    None,
}

impl From<u8> for PortableBatteryDeviceChemistryData {
    fn from(raw: u8) -> Self {
        PortableBatteryDeviceChemistryData {
            value: match raw {
                0x01 => PortableBatteryDeviceChemistry::Other,
                0x02 => PortableBatteryDeviceChemistry::Unknown,
                0x03 => PortableBatteryDeviceChemistry::LeadAcit,
                0x04 => PortableBatteryDeviceChemistry::NickelCadmium,
                0x05 => PortableBatteryDeviceChemistry::NickelMetalHydride,
                0x06 => PortableBatteryDeviceChemistry::LithiumIon,
                0x07 => PortableBatteryDeviceChemistry::ZincAir,
                0x08 => PortableBatteryDeviceChemistry::LithiumPolymer,
                _ => PortableBatteryDeviceChemistry::None,
            },
            raw,
        }
    }
}

/// # Portable Battery - Design Capacity
#[derive(Serialize, Debug, PartialEq, Eq)]
pub enum PortableBatteryDesignCapacity {
    /// Design capacity of the battery in mWatt-hours
    ///
    /// For version 2.2+ implementations, this value is
    /// multiplied by the 'design_capacity_multiplier' to
    /// produce the actual value.
    MilliWattHours(u16),
    /// Design capacity of the battery in mWatt-hours is unknown.
    Unknown,
}

impl From<u16> for PortableBatteryDesignCapacity {
    fn from(raw: u16) -> Self {
        match raw {
            0 => PortableBatteryDesignCapacity::Unknown,
            _ => PortableBatteryDesignCapacity::MilliWattHours(raw),
        }
    }
}

/// # Portable Battery - Design Voltage
#[derive(Serialize, Debug, PartialEq, Eq)]
pub enum PortableBatteryDesignVoltage {
    /// Design voltage of the battery in mVolts.
    MilliVolts(u16),
    /// Design voltage of the battery in mVolts is unknown.
    Unknown,
}

impl From<u16> for PortableBatteryDesignVoltage {
    fn from(raw: u16) -> Self {
        match raw {
            0 => PortableBatteryDesignVoltage::Unknown,
            _ => PortableBatteryDesignVoltage::MilliVolts(raw),
        }
    }
}

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

    #[test]
    fn unit_test() {
        let struct_type22 = vec![
            0x16, 0x1A, 0x2E, 0x00, 0x01, 0x02, 0x00, 0x00, 0x03, 0x02, 0xFB, 0x11, 0xD0, 0x39,
            0x04, 0xFF, 0xC7, 0x02, 0x7A, 0x42, 0x05, 0x0A, 0x00, 0x00, 0x00, 0x00, 0x52, 0x65,
            0x61, 0x72, 0x00, 0x53, 0x4D, 0x50, 0x00, 0x34, 0x35, 0x4E, 0x31, 0x30, 0x37, 0x31,
            0x00, 0x30, 0x33, 0x2E, 0x30, 0x31, 0x00, 0x4C, 0x69, 0x50, 0x00, 0x00,
        ];

        let parts = UndefinedStruct::new(&struct_type22);
        let test_struct = SMBiosPortableBattery::new(&parts);

        assert_eq!(test_struct.location(), Some("Rear".to_string()));
        assert_eq!(test_struct.manufacturer(), Some("SMP".to_string()));
        assert_eq!(test_struct.manufacture_date(), None);
        assert_eq!(test_struct.serial_number(), None);
        assert_eq!(test_struct.device_name(), Some("45N1071".to_string()));
        assert_eq!(
            *test_struct.device_chemistry().unwrap(),
            PortableBatteryDeviceChemistry::Unknown
        );
        match test_struct.design_capacity().unwrap() {
            PortableBatteryDesignCapacity::MilliWattHours(mwh) => assert_eq!(mwh, 4603),
            PortableBatteryDesignCapacity::Unknown => panic!("expected a value in mWH"),
        }
        match test_struct.design_voltage().unwrap() {
            PortableBatteryDesignVoltage::MilliVolts(mv) => assert_eq!(mv, 14800),
            PortableBatteryDesignVoltage::Unknown => panic!("expected a value in mWH"),
        }
        assert_eq!(test_struct.sbds_version_number(), Some("03.01".to_string()));
        assert_eq!(test_struct.maximum_error_in_battery_data(), Some(255));
        assert_eq!(test_struct.sbds_serial_number(), Some(711));
        assert_eq!(test_struct.sbds_manufacture_date(), Some(17018));
        assert_eq!(test_struct.sbds_device_chemistry(), Some("LiP".to_string()));
        assert_eq!(test_struct.design_capacity_multiplier(), Some(10));
        assert_eq!(test_struct.oem_specific(), Some(0));
    }
}