Skip to content

Commit

Permalink
RDSK-1750 Add sensor support and implement a moisture sensor
Browse files Browse the repository at this point in the history
  • Loading branch information
acmorrow committed Feb 1, 2023
1 parent b3ef260 commit d2d9cdc
Show file tree
Hide file tree
Showing 5 changed files with 175 additions and 0 deletions.
15 changes: 15 additions & 0 deletions src/common/grpc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -162,6 +162,9 @@ impl GrpcServer {
"/viam.robot.v1.RobotService/ResourceNames" => self.resource_names(payload),
"/viam.robot.v1.RobotService/GetStatus" => self.robot_status(payload),
"/proto.rpc.v1.AuthService/Authenticate" => self.auth_service_authentificate(payload),
"/viam.component.sensor.v1.SensorService/GetReadings" => {
self.sensor_get_readings(payload)
}
_ => anyhow::bail!("unimplemented method"),
}
}
Expand Down Expand Up @@ -301,6 +304,18 @@ impl GrpcServer {
self.encode_message(resp)
}

fn sensor_get_readings(&mut self, message: &[u8]) -> anyhow::Result<()> {
let req = component::sensor::v1::GetReadingsRequest::decode(message)?;
let sensor = match self.robot.lock().unwrap().get_sensor_by_name(req.name) {
Some(b) => b,
None => return Err(anyhow::anyhow!("resource not found")),
};

let readings = sensor.lock().unwrap().get_generic_readings()?;
let resp = component::sensor::v1::GetReadingsResponse { readings };
self.encode_message(resp)
}

fn base_move_straight(&mut self, _message: &[u8]) -> anyhow::Result<()> {
anyhow::bail!("unimplemented: base_move_straight")
}
Expand Down
48 changes: 48 additions & 0 deletions src/common/moisture_sensor.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
use crate::common::analog::AnalogReader;
use crate::common::sensor::GenericReadingsResult;
use crate::common::sensor::Sensor;
use crate::common::sensor::SensorResult;
use crate::common::sensor::SensorT;
use crate::common::sensor::TypedReadingsResult;
use crate::common::status::Status;
use std::cell::RefCell;
use std::collections::BTreeMap;
use std::collections::HashMap;
use std::rc::Rc;

pub struct MoistureSensor {
analog: Rc<RefCell<dyn AnalogReader<u16, Error = anyhow::Error>>>,
}

impl MoistureSensor {
pub fn new(analog: Rc<RefCell<dyn AnalogReader<u16, Error = anyhow::Error>>>) -> Self {
MoistureSensor { analog }
}
}

impl Sensor for MoistureSensor {
fn get_generic_readings(&self) -> anyhow::Result<GenericReadingsResult> {
Ok(self
.get_readings()?
.into_iter()
.map(|v| (v.0, SensorResult::<f64> { value: v.1 }.into()))
.collect())
}
}

impl SensorT<f64> for MoistureSensor {
fn get_readings(&self) -> anyhow::Result<TypedReadingsResult<f64>> {
let reading = self.analog.borrow_mut().read()?;
let mut x = HashMap::new();
x.insert("millivolts".to_string(), reading as f64);
Ok(x)
}
}

impl Status for MoistureSensor {
fn get_status(&self) -> anyhow::Result<Option<prost_types::Struct>> {
Ok(Some(prost_types::Struct {
fields: BTreeMap::new(),
}))
}
}
29 changes: 29 additions & 0 deletions src/common/robot.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ use crate::{
common::base::Base,
common::board::Board,
common::motor::Motor,
common::sensor::Sensor,
common::status::Status,
proto::{
common::{self, v1::ResourceName},
Expand All @@ -22,6 +23,7 @@ pub enum ResourceType {
Motor(Arc<Mutex<dyn Motor>>),
Board(Arc<Mutex<dyn Board>>),
Base(Arc<Mutex<dyn Base>>),
Sensor(Arc<Mutex<dyn Sensor>>),
#[cfg(feature = "camera")]
Camera(Arc<Mutex<dyn Camera>>),
}
Expand Down Expand Up @@ -65,6 +67,13 @@ impl LocalRobot {
status,
});
}
ResourceType::Sensor(b) => {
let status = b.get_status()?;
vec.push(robot::v1::Status {
name: Some(name.clone()),
status,
});
}
#[cfg(feature = "camera")]
_ => continue,
};
Expand Down Expand Up @@ -98,6 +107,13 @@ impl LocalRobot {
status,
});
}
ResourceType::Sensor(b) => {
let status = b.get_status()?;
vec.push(robot::v1::Status {
name: Some(name),
status,
});
}
#[cfg(feature = "camera")]
_ => continue,
};
Expand Down Expand Up @@ -167,4 +183,17 @@ impl LocalRobot {
None => None,
}
}
pub fn get_sensor_by_name(&self, name: String) -> Option<Arc<Mutex<dyn Sensor>>> {
let name = ResourceName {
namespace: "rdk".to_string(),
r#type: "component".to_string(),
subtype: "sensor".to_string(),
name,
};
match self.resources.get(&name) {
Some(ResourceType::Sensor(r)) => Some(r.clone()),
Some(_) => None,
None => None,
}
}
}
75 changes: 75 additions & 0 deletions src/common/sensor.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
#![allow(dead_code)]

use crate::common::status::Status;
use std::collections::BTreeMap;
use std::collections::HashMap;

pub type GenericReadingsResult =
::std::collections::HashMap<::prost::alloc::string::String, ::prost_types::Value>;

pub type TypedReadingsResult<T> = ::std::collections::HashMap<String, T>;

pub trait Sensor: Status {
fn get_generic_readings(&self) -> anyhow::Result<GenericReadingsResult>;
}

pub trait SensorT<T>: Sensor {
fn get_readings(&self) -> anyhow::Result<TypedReadingsResult<T>>;
}

// A local wrapper type we can use to specialize `From` for `prost_types::Value``
pub struct SensorResult<T> {
pub value: T,
}

impl From<SensorResult<f64>> for ::prost_types::Value {
fn from(value: SensorResult<f64>) -> ::prost_types::Value {
prost_types::Value {
kind: Some(::prost_types::value::Kind::NumberValue(value.value)),
}
}
}

pub struct FakeSensor {
fake_reading: f64,
}

impl FakeSensor {
pub fn new() -> Self {
FakeSensor {
fake_reading: 42.42,
}
}
}

impl Default for FakeSensor {
fn default() -> Self {
Self::new()
}
}

impl Sensor for FakeSensor {
fn get_generic_readings(&self) -> anyhow::Result<GenericReadingsResult> {
Ok(self
.get_readings()?
.into_iter()
.map(|v| (v.0, SensorResult::<f64> { value: v.1 }.into()))
.collect())
}
}

impl SensorT<f64> for FakeSensor {
fn get_readings(&self) -> anyhow::Result<TypedReadingsResult<f64>> {
let mut x = HashMap::new();
x.insert("fake_sensor".to_string(), self.fake_reading);
Ok(x)
}
}

impl Status for FakeSensor {
fn get_status(&self) -> anyhow::Result<Option<prost_types::Struct>> {
Ok(Some(prost_types::Struct {
fields: BTreeMap::new(),
}))
}
}
8 changes: 8 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,10 @@ pub mod common {
pub mod board;
pub mod camera;
pub mod grpc;
pub mod moisture_sensor;
pub mod motor;
pub mod robot;
pub mod sensor;
pub mod status;
}

Expand Down Expand Up @@ -87,5 +89,11 @@ pub mod proto {
include!("gen/viam.component.base.v1.rs");
}
}
pub mod sensor {
pub mod v1 {
#![allow(clippy::derive_partial_eq_without_eq)]
include!("gen/viam.component.sensor.v1.rs");
}
}
}
}

0 comments on commit d2d9cdc

Please sign in to comment.