spaceapi_server/sensors.rs
1//! Sensor related stuff.
2
3use std::sync::Arc;
4
5use quick_error::quick_error;
6use redis::Commands;
7use redis::RedisError;
8
9use crate::api::sensors;
10use crate::types::RedisPool;
11
12/// A specification of a sensor.
13///
14/// The ``template`` field contains the static data of a sensor and
15/// the ``data_key`` says how to find the sensor value in Redis.
16pub(crate) struct SensorSpec {
17 /// A reference to an instantiated sensor template
18 pub(crate) template: Box<dyn sensors::SensorTemplate>,
19 /// The data key that is used to store and update the sensor value
20 pub(crate) data_key: String,
21}
22
23quick_error! {
24 /// A ``SensorError`` wraps problems that can occur when reading or updating sensor values.
25 ///
26 /// This type is only used for internal purposes and should not be used by third party code.
27 ///
28 /// TODO: Make pub(crate) when https://github.com/tailhook/quick-error/issues/48 is fixed
29 #[derive(Debug)]
30 pub enum SensorError {
31 /// Sensor `data_key` not known
32 UnknownSensor(err: String) {
33 display("Unknown sensor: {}", err)
34 }
35 /// Redis error
36 Redis(err: RedisError) {
37 from()
38 source(err)
39 }
40 /// R2d2 connection pool error
41 R2d2(err: r2d2::Error) {
42 from()
43 source(err)
44 }
45 }
46}
47
48/// A vector of sensor specs, wrapped in an Arc. Safe for use in multithreaded situations.
49pub(crate) type SafeSensorSpecs = Arc<Vec<SensorSpec>>;
50
51impl SensorSpec {
52 /// Retrieve sensor value from Redis.
53 pub(crate) fn get_sensor_value(&self, redis_pool: &RedisPool) -> Result<String, SensorError> {
54 let mut conn = redis_pool.get()?;
55 let value: String = conn.get(&*self.data_key)?;
56 Ok(value)
57 }
58
59 /// Set sensor value in Redis.
60 pub(crate) fn set_sensor_value(&self, redis_pool: &RedisPool, value: &str) -> Result<(), SensorError> {
61 let mut conn = redis_pool.get()?;
62 let _: String = conn.set(&*self.data_key, value)?;
63 Ok(())
64 }
65}