| Line | Branch | Decision | Exec | Source |
|---|---|---|---|---|
| 1 | /** | |||
| 2 | * @file sensor_reader.h | |||
| 3 | * @brief Declaration for SensorReader, the class used to acquire readings from a sensor. | |||
| 4 | * | |||
| 5 | * @date September 12, 2019 | |||
| 6 | * @author Matthew Kennedy, (c) 2019 | |||
| 7 | */ | |||
| 8 | ||||
| 9 | #pragma once | |||
| 10 | ||||
| 11 | #include "sensor.h" | |||
| 12 | ||||
| 13 | /** | |||
| 14 | * @brief Provides an interface for reading sensors. | |||
| 15 | * | |||
| 16 | * Example usage: | |||
| 17 | * | |||
| 18 | * // Create a sensor reader for type MySensor, and fallback value 10.0 | |||
| 19 | * SensorReader<SensorType::MySensor> mySensorReader(10.0f); | |||
| 20 | * | |||
| 21 | * <later> | |||
| 22 | * | |||
| 23 | * // Returns the sensor value if valid, or 10.0 if invalid. | |||
| 24 | * float currentSensorValue = mySensorReader.getOrDefault(); | |||
| 25 | * alternatively, because we have implicit conversion: | |||
| 26 | * float currentSensorValue = mySensorReader; | |||
| 27 | * | |||
| 28 | * Simply calling the get() method returns the full SensorResult, should | |||
| 29 | * more complex logic be required in case of an invalid sensor reading. | |||
| 30 | */ | |||
| 31 | template <SensorType TSensorType> | |||
| 32 | class SensorReader final { | |||
| 33 | public: | |||
| 34 | using sensorValueType = float; | |||
| 35 | ||||
| 36 |
1/1✓ Decision 'true' taken 2 times.
|
2 | explicit SensorReader(sensorValueType defaultValue) | |
| 37 | 2 | : m_defaultValue(defaultValue) {} | ||
| 38 | ||||
| 39 | 7 | SensorResult get() const { | ||
| 40 | 7 | return Sensor::get(TSensorType); | ||
| 41 | } | |||
| 42 | ||||
| 43 | // Get the sensor's reading, or a default value. | |||
| 44 | // Inteded for applications where a default may be used silently, | |||
| 45 | // while elsewhere in the world the failed sensor is otherwise handled. | |||
| 46 | 2 | sensorValueType getOrDefault() const { | ||
| 47 | 2 | auto result = get(); | ||
| 48 | ||||
| 49 |
2/2✓ Branch 0 taken 1 time.
✓ Branch 1 taken 1 time.
|
2/2✓ Decision 'true' taken 1 time.
✓ Decision 'false' taken 1 time.
|
2 | if (result.Valid) { |
| 50 | 1 | return (sensorValueType)result.Value; | ||
| 51 | } else { | |||
| 52 | 1 | return m_defaultValue; | ||
| 53 | } | |||
| 54 | } | |||
| 55 | ||||
| 56 | // Implicit conversion operator | |||
| 57 | operator sensorValueType() const { | |||
| 58 | return getOrDefault(); | |||
| 59 | } | |||
| 60 | ||||
| 61 | private: | |||
| 62 | const sensorValueType m_defaultValue; | |||
| 63 | }; | |||
| 64 |