Add the route to delete a relay
This commit is contained in:
@ -106,9 +106,9 @@ pub struct DeviceRelay {
|
||||
/// Optional minimal runtime requirements for this relay
|
||||
daily_runtime: Option<DailyMinRuntime>,
|
||||
/// Specify relay that must be turned on before this relay can be started
|
||||
depends_on: Vec<DeviceRelayID>,
|
||||
pub depends_on: Vec<DeviceRelayID>,
|
||||
/// Specify relays that must be turned off before this relay can be started
|
||||
conflicts_with: Vec<DeviceRelayID>,
|
||||
pub conflicts_with: Vec<DeviceRelayID>,
|
||||
}
|
||||
|
||||
impl DeviceRelay {
|
||||
|
@ -23,6 +23,8 @@ pub enum DevicesListError {
|
||||
DeviceNotFound,
|
||||
#[error("Requested device is not validated")]
|
||||
DeviceNotValidated,
|
||||
#[error("Failed to delete relay: {0}")]
|
||||
DeleteRelayFailed(&'static str),
|
||||
}
|
||||
|
||||
pub struct DevicesList(HashMap<DeviceId, Device>);
|
||||
@ -221,4 +223,48 @@ impl DevicesList {
|
||||
pub fn relay_get_single(&self, relay_id: DeviceRelayID) -> Option<DeviceRelay> {
|
||||
self.relays_list().into_iter().find(|i| i.id == relay_id)
|
||||
}
|
||||
|
||||
/// Get the device hosting a relay
|
||||
pub fn relay_get_device(&self, relay_id: DeviceRelayID) -> Option<Device> {
|
||||
self.0
|
||||
.iter()
|
||||
.find(|r| r.1.relays.iter().any(|r| r.id == relay_id))
|
||||
.map(|d| d.1.clone())
|
||||
}
|
||||
|
||||
/// Get all the relays that depends directly on a relay
|
||||
pub fn relay_get_direct_dependencies(&self, relay_id: DeviceRelayID) -> Vec<DeviceRelay> {
|
||||
self.relays_list()
|
||||
.into_iter()
|
||||
.filter(|d| d.depends_on.contains(&relay_id))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Delete a relay
|
||||
pub fn relay_delete(&mut self, relay_id: DeviceRelayID) -> anyhow::Result<()> {
|
||||
if !self.relay_get_direct_dependencies(relay_id).is_empty() {
|
||||
return Err(DevicesListError::DeleteRelayFailed(
|
||||
"At least one other relay depend on this relay!",
|
||||
)
|
||||
.into());
|
||||
}
|
||||
|
||||
// Delete the relay
|
||||
let device = self
|
||||
.relay_get_device(relay_id)
|
||||
.ok_or(DevicesListError::DeleteRelayFailed(
|
||||
"Relay does not exists!",
|
||||
))?;
|
||||
|
||||
let dev = self
|
||||
.0
|
||||
.get_mut(&device.id)
|
||||
.ok_or(DevicesListError::UpdateDeviceFailedDeviceNotFound)?;
|
||||
|
||||
dev.relays.retain(|r| r.id != relay_id);
|
||||
|
||||
self.persist_dev_config(&device.id)?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
Reference in New Issue
Block a user