diff --git a/crates/core/tedge_api/src/mqtt_topics.rs b/crates/core/tedge_api/src/mqtt_topics.rs index 31e69b243df..1bf05bc5bd4 100644 --- a/crates/core/tedge_api/src/mqtt_topics.rs +++ b/crates/core/tedge_api/src/mqtt_topics.rs @@ -188,9 +188,37 @@ impl MqttSchema { pub fn error_topic(&self) -> Topic { Topic::new_unchecked(&format!("{0}/errors", self.root)) } -} -impl MqttSchema { + /// Extract the entity identifier from a topic + /// + /// Note this function is not related to a specific topic root prefix + pub fn get_entity_id(topic: impl AsRef) -> Option { + match topic.as_ref().split('/').collect::>()[..] { + [_, t1, t2, t3, t4, ..] => Some(format!("{t1}/{t2}/{t3}/{t4}")), + _ => None, + } + } + + /// Extract the operation name from a command topic + /// + /// Note this function is not related to a specific topic root prefix + pub fn get_operation_name(topic: impl AsRef) -> Option { + match topic.as_ref().split('/').collect::>()[..] { + [_, _, _, _, _, "cmd", op, ..] => Some(op.to_string()), + _ => None, + } + } + + /// Extract the command instance identifier from a command topic + /// + /// Note this function is not related to a specific topic root prefix + pub fn get_command_id(topic: impl AsRef) -> Option { + match topic.as_ref().split('/').collect::>()[..] { + [_, _, _, _, _, "cmd", _, id] => Some(id.to_string()), + _ => None, + } + } + fn parse(&self, topic: &str) -> Result<(EntityTopicId, Channel), EntityTopicError> { let (root, topic) = topic.split_once('/').ok_or(EntityTopicError::Root { expected: self.root.to_string(), diff --git a/crates/core/tedge_api/src/workflow/state.rs b/crates/core/tedge_api/src/workflow/state.rs index fbbafee424b..93db2490239 100644 --- a/crates/core/tedge_api/src/workflow/state.rs +++ b/crates/core/tedge_api/src/workflow/state.rs @@ -248,18 +248,15 @@ impl GenericCommandState { } fn target(&self) -> Option { - match self.topic.name.split('/').collect::>()[..] { - [_, t1, t2, t3, t4, "cmd", _, _] => Some(format!("{t1}/{t2}/{t3}/{t4}")), - _ => None, - } + MqttSchema::get_entity_id(&self.topic) } pub fn operation(&self) -> Option { - extract_command_identifier(&self.topic.name).map(|(operation, _)| operation) + MqttSchema::get_operation_name(&self.topic) } pub fn cmd_id(&self) -> Option { - extract_command_identifier(&self.topic.name).map(|(_, cmd_id)| cmd_id) + MqttSchema::get_command_id(&self.topic) } pub fn is_init(&self) -> bool { @@ -279,15 +276,6 @@ impl GenericCommandState { } } -fn extract_command_identifier(topic: &str) -> Option<(String, String)> { - match topic.split('/').collect::>()[..] { - [_, _, _, _, _, "cmd", operation, cmd_id] => { - Some((operation.to_string(), cmd_id.to_string())) - } - _ => None, - } -} - impl GenericStateUpdate { pub fn empty_payload() -> Value { json!({})