Skip to content

Commit

Permalink
backup
Browse files Browse the repository at this point in the history
  • Loading branch information
RaulTrombin committed Aug 1, 2024
1 parent 7e938aa commit 1a18531
Show file tree
Hide file tree
Showing 5 changed files with 207 additions and 14 deletions.
1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ udp-stream = "0.0.12"
uuid = { version = "1.8", features = ["serde"] }
validator = "0.18.1"
thiserror = "1.0.61"
ts-rs = { version = "9.0.1" , features = ["serde-compat", "uuid-impl"] }

[build-dependencies]
vergen-gix = { version = "1.0.0-beta.2", default-features = false, features = ["build", "cargo"] }
23 changes: 19 additions & 4 deletions src/device/devices.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ use bluerobotics_ping::device::PingDevice;
use serde::{Deserialize, Serialize};
use tokio::sync::{mpsc, oneshot};
use tracing::{error, trace, warn};
use ts_rs::TS;

pub struct DeviceActor {
pub receiver: mpsc::Receiver<DeviceActorRequest>,
Expand Down Expand Up @@ -267,7 +268,7 @@ pub enum UpgradeResult {
Ping360,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[derive(Debug, Clone, Serialize, Deserialize, TS)]
pub enum PingRequest {
Ping1D(Ping1DRequest),
Ping360(Ping360Request),
Expand All @@ -277,7 +278,7 @@ pub enum PingRequest {
Stop,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[derive(Debug, Clone, Serialize, Deserialize, TS)]
pub enum Ping1DRequest {
DeviceID,
ModeAuto,
Expand All @@ -296,33 +297,47 @@ pub enum Ping1DRequest {
GainSetting,
PingEnable,
DistanceSimple,
#[ts(skip)]
SetDeviceId(bluerobotics_ping::ping1d::SetDeviceIdStruct),
#[ts(skip)]
SetModeAuto(bluerobotics_ping::ping1d::SetModeAutoStruct),
#[ts(skip)]
SetPingInterval(bluerobotics_ping::ping1d::SetPingIntervalStruct),
#[ts(skip)]
SetPingEnable(bluerobotics_ping::ping1d::SetPingEnableStruct),
#[ts(skip)]
SetSpeedOfSound(bluerobotics_ping::ping1d::SetSpeedOfSoundStruct),
#[ts(skip)]
SetRange(bluerobotics_ping::ping1d::SetRangeStruct),
#[ts(skip)]
SetGainSetting(bluerobotics_ping::ping1d::SetGainSettingStruct),
#[ts(skip)]
ContinuousStart(bluerobotics_ping::ping1d::ContinuousStartStruct),
#[ts(skip)]
ContinuousStop(bluerobotics_ping::ping1d::ContinuousStopStruct),
GotoBootloader,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[derive(Debug, Clone, Serialize, Deserialize, TS)]
pub enum Ping360Request {
MotorOff,
DeviceData,
AutoDeviceData,
#[ts(skip)]
SetDeviceId(bluerobotics_ping::ping360::SetDeviceIdStruct),
#[ts(skip)]
Transducer(bluerobotics_ping::ping360::TransducerStruct),
#[ts(skip)]
Reset(bluerobotics_ping::ping360::ResetStruct),
#[ts(skip)]
AutoTransmit(bluerobotics_ping::ping360::AutoTransmitStruct),
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[derive(Debug, Clone, Serialize, Deserialize, TS)]
pub enum PingCommonRequest {
DeviceInformation,
ProtocolVersion,
#[ts(skip)]
SetDeviceId(bluerobotics_ping::common::SetDeviceIdStruct),
}

Expand Down
110 changes: 110 additions & 0 deletions src/device/helpers/device_handling.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
use tracing::{error, trace, warn};
use uuid::Uuid;

use crate::device::{
devices::{self, DeviceActorHandler},
manager::{Answer, Device, DeviceManager, DeviceSelection, DeviceStatus, ManagerError},
};

impl DeviceManager {
pub fn check_device_uuid(&self, device_id: Uuid) -> Result<(), ManagerError> {
if self.device.contains_key(&device_id) {
return Ok(());
}
error!(
"Getting device handler for device: {:?} : Error, device doesn't exist",
device_id
);
Err(ManagerError::DeviceNotExist(device_id))
}

pub fn get_device(&self, device_id: Uuid) -> Result<&Device, ManagerError> {
let device = self
.device
.get(&device_id)
.ok_or(ManagerError::DeviceNotExist(device_id))?;
Ok(device)
}

pub async fn get_device_handler(&self, device_id: Uuid) -> Result<Answer, ManagerError> {
self.check_device_uuid(device_id)?;

trace!(
"Getting device handler for device: {:?} : Success",
device_id
);

// Fail-fast if device is stopped
self.check_device_status(
device_id,
&[DeviceStatus::ContinuousMode, DeviceStatus::Running],
)?;

let handler: DeviceActorHandler = self.get_device(device_id)?.handler.clone();

Ok(Answer::InnerDeviceHandler(handler))
}

pub fn check_device_status(
&self,
device_id: Uuid,
valid_statuses: &[DeviceStatus],
) -> Result<(), ManagerError> {
let status = &self.get_device(device_id)?.status;
if !valid_statuses.contains(status) {
return Err(ManagerError::DeviceStatus(status.clone(), device_id));
}
Ok(())
}

pub fn get_mut_device(&mut self, device_id: Uuid) -> Result<&mut Device, ManagerError> {
let device = self
.device
.get_mut(&device_id)
.ok_or(ManagerError::DeviceNotExist(device_id))?;
Ok(device)
}

pub fn get_device_type(&self, device_id: Uuid) -> Result<DeviceSelection, ManagerError> {
let device_type = self.device.get(&device_id).unwrap().device_type.clone();
Ok(device_type)
}

pub fn extract_handler(
&self,
device_handler: Answer,
) -> Result<DeviceActorHandler, ManagerError> {
match device_handler {
Answer::InnerDeviceHandler(handler) => Ok(handler),
answer => Err(ManagerError::Other(format!(
"Unreachable: extract_handler helper, detail: {answer:?}"
))),
}
}

pub async fn get_subscriber(
&self,
device_id: Uuid,
) -> Result<
tokio::sync::broadcast::Receiver<bluerobotics_ping::message::ProtocolMessage>,
ManagerError,
> {
let handler_request = self.get_device_handler(device_id).await?;
let handler = self.extract_handler(handler_request)?;

let subscriber = handler
.send(devices::PingRequest::GetSubscriber)
.await
.map_err(|err| {
warn!("Something went wrong while executing get_subscriber, details: {err:?}");
ManagerError::DeviceError(err)
})?;

match subscriber {
devices::PingAnswer::Subscriber(subscriber) => Ok(subscriber),
_ => Err(ManagerError::Other(
"Unreachable: get_subscriber helper".to_string(),
)),
}
}
}
17 changes: 9 additions & 8 deletions src/device/manager.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ use std::{
use tokio::sync::{mpsc, oneshot};
use tokio_serial::{SerialPort, SerialPortBuilderExt, SerialStream};
use tracing::{error, info, trace, warn};
use ts_rs::TS;
use udp_stream::UdpStream;
use uuid::Uuid;

Expand Down Expand Up @@ -56,15 +57,15 @@ impl Drop for Device {
}
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
pub enum DeviceSelection {
Common,
Ping1D,
Ping360,
Auto,
}

#[derive(Debug, Clone, Deserialize, Serialize, Hash)]
#[derive(Debug, Clone, Deserialize, Serialize, Hash, TS)]
pub enum SourceSelection {
UdpStream(SourceUdpStruct),
SerialStream(SourceSerialStruct),
Expand All @@ -75,13 +76,13 @@ enum SourceType {
Serial(SerialStream),
}

#[derive(Clone, Debug, Deserialize, Serialize, Hash, Apiv2Schema)]
#[derive(Clone, Debug, Deserialize, Serialize, Hash, Apiv2Schema, TS)]
pub struct SourceUdpStruct {
pub ip: Ipv4Addr,
pub port: u16,
}

#[derive(Clone, Debug, Deserialize, Serialize, Hash, Apiv2Schema)]
#[derive(Clone, Debug, Deserialize, Serialize, Hash, Apiv2Schema, TS)]
pub struct SourceSerialStruct {
pub path: String,
pub baudrate: u32,
Expand Down Expand Up @@ -137,7 +138,7 @@ pub struct DeviceAnswer {
pub device_id: Uuid,
}

#[derive(Debug, Clone, Serialize, Deserialize, Apiv2Schema)]
#[derive(Debug, Clone, Serialize, Deserialize, Apiv2Schema, TS)]
#[serde(tag = "type", content = "payload")]
pub enum Request {
Create(CreateStruct),
Expand All @@ -151,7 +152,7 @@ pub enum Request {
DisableContinuousMode(UuidWrapper),
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[derive(Debug, Clone, Serialize, Deserialize, TS)]
pub struct UuidWrapper {
pub uuid: Uuid,
}
Expand All @@ -174,13 +175,13 @@ impl From<UuidWrapper> for Uuid {
}
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[derive(Debug, Clone, Serialize, Deserialize, TS)]
pub struct CreateStruct {
pub source: SourceSelection,
pub device_selection: DeviceSelection,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[derive(Debug, Clone, Serialize, Deserialize, TS)]
pub struct DeviceRequestStruct {
pub uuid: Uuid,
pub device_request: crate::device::devices::PingRequest,
Expand Down
70 changes: 68 additions & 2 deletions src/main.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,9 @@


use device::manager::{CreateStruct, DeviceRequestStruct, UuidWrapper};
use serde::{Deserialize, Serialize};
use tracing::info;
use ts_rs::TS;

#[macro_use]
extern crate lazy_static;
Expand All @@ -9,16 +14,23 @@ mod device;
mod logger;
mod server;

#[derive(Debug, Clone, Serialize, Deserialize)]
#[derive(Debug, Clone, Serialize, Deserialize, TS)]
#[ts(export, export_to = "RequestModels.ts")]
pub struct Command {
pub command: CommandType,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[derive(Debug, Clone, Serialize, Deserialize, TS)]
#[serde(tag = "module")]
pub enum CommandType {
DeviceManager(device::manager::Request),
}

// #[derive(Debug, Clone, Serialize, Deserialize)]
// pub enum Command {
// DeviceManager(device::manager::Request),
// }

#[tokio::main]
async fn main() {
// CLI should be started before logger to allow control over verbosity
Expand All @@ -34,6 +46,60 @@ async fn main() {
"DeviceManager initialized with following devices: {:?}",
handler.send(crate::device::manager::Request::List).await
);
use serde_json::json;
use uuid::Uuid;

// Define your requests
let requests = vec![
crate::device::manager::Request::Ping(DeviceRequestStruct {
uuid: Uuid::parse_str("00000000-0000-0000-001e-10da679f8cee").unwrap(),
device_request: crate::device::devices::PingRequest::Ping360(
crate::device::devices::Ping360Request::Transducer(
bluerobotics_ping::ping360::TransducerStruct {
mode: 1,
gain_setting: 2,
angle: 0,
transmit_duration: 500,
sample_period: 80,
transmit_frequency: 700,
number_of_samples: 1200,
transmit: 1,
reserved: 1,
},
),
),
}),
crate::device::manager::Request::EnableContinuousMode(UuidWrapper {
uuid: Uuid::parse_str("00000000-0000-0000-001e-10da679f8cee").unwrap(),
}),
crate::device::manager::Request::List,
crate::device::manager::Request::Create(CreateStruct {
source: device::manager::SourceSelection::SerialStream(
device::manager::SourceSerialStruct {
path: "/dev/ttyUSB0".to_string(),
baudrate: 115200,
},
),
device_selection: device::manager::DeviceSelection::Auto,
}),
crate::device::manager::Request::Create(CreateStruct {
source: device::manager::SourceSelection::UdpStream(device::manager::SourceUdpStruct {
ip: "192.168.0.1".parse().unwrap(),
port: 9092,
}),
device_selection: device::manager::DeviceSelection::Auto,
}),
];

// Print each request as JSON
for request in requests {
println!(
"{}",
json!(Command {
command: CommandType::DeviceManager(request)
})
);
}

server::manager::run(&cli::manager::server_address(), handler)
.await
Expand Down

0 comments on commit 1a18531

Please sign in to comment.