Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

C8y mapping of entity registration messages #2266

Merged
merged 13 commits into from
Sep 27, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -369,7 +369,7 @@ define_tedge_config! {

/// Set of MQTT topics the Cumulocity mapper should subscribe to
#[tedge_config(example = "te/+/+/+/+/a/+,te/+/+/+/+/m/+,te/+/+/+/+/e/+")]
#[tedge_config(default(value = "te/+/+/+/+/m/+,te/+/+/+/+/e/+,te/+/+/+/+/a/+,tedge/health/+,tedge/health/+/+"))]
#[tedge_config(default(value = "te/+/+/+/+,te/+/+/+/+/m/+,te/+/+/+/+/e/+,te/+/+/+/+/a/+,tedge/health/+,tedge/health/+/+"))]
topics: TemplatesSet,

enable: {
Expand Down
22 changes: 18 additions & 4 deletions crates/core/c8y_api/src/json_c8y.rs
Original file line number Diff line number Diff line change
Expand Up @@ -319,8 +319,8 @@ impl C8yAlarm {
fn convert_source(entity: &EntityMetadata) -> Option<SourceInfo> {
match entity.r#type {
EntityType::MainDevice => None,
EntityType::ChildDevice => Some(make_c8y_source_fragment(&entity.entity_id.clone())),
EntityType::Service => Some(make_c8y_source_fragment(&entity.entity_id.clone())),
EntityType::ChildDevice => Some(make_c8y_source_fragment(entity.external_id.as_ref())),
EntityType::Service => Some(make_c8y_source_fragment(entity.external_id.as_ref())),
}
}

Expand Down Expand Up @@ -415,6 +415,7 @@ mod tests {
use serde_json::json;
use tedge_api::alarm::ThinEdgeAlarm;
use tedge_api::alarm::ThinEdgeAlarmData;
use tedge_api::entity_store::EntityExternalId;
use tedge_api::entity_store::EntityRegistrationMessage;
use tedge_api::event::ThinEdgeEventData;
use tedge_api::mqtt_topics::EntityTopicId;
Expand Down Expand Up @@ -774,7 +775,8 @@ mod tests {
)]
fn check_alarm_translation(tedge_alarm: ThinEdgeAlarm, expected_c8y_alarm: C8yAlarm) {
let main_device = EntityRegistrationMessage::main_device("test-main".into());
let mut entity_store = EntityStore::with_main_device(main_device).unwrap();
let mut entity_store =
EntityStore::with_main_device(main_device, dummy_external_id_mapper).unwrap();

let child_registration = EntityRegistrationMessage::new(&Message::new(
&Topic::new_unchecked("te/device/external_source//"),
Expand All @@ -801,7 +803,8 @@ mod tests {
};

let main_device = EntityRegistrationMessage::main_device("test-main".into());
let entity_store = EntityStore::with_main_device(main_device).unwrap();
let entity_store =
EntityStore::with_main_device(main_device, dummy_external_id_mapper).unwrap();

match C8yAlarm::try_from(&tedge_alarm, &entity_store).unwrap() {
C8yAlarm::Create(value) => {
Expand All @@ -810,4 +813,15 @@ mod tests {
C8yAlarm::Clear(_) => panic!("Must be C8yAlarm::Create"),
};
}

fn dummy_external_id_mapper(
entity_topic_id: &EntityTopicId,
_main_device_xid: &EntityExternalId,
) -> EntityExternalId {
entity_topic_id
.to_string()
.trim_end_matches('/')
.replace('/', ":")
.into()
}
}
43 changes: 43 additions & 0 deletions crates/core/c8y_api/src/smartrest/inventory.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
//! This module provides some helper functions to create SmartREST messages
//! that can be used to create various managed objects in Cumulocity inventory.
use crate::smartrest::topic::publish_topic_from_ancestors;
use mqtt_channel::Message;

/// Create a SmartREST message for creating a child device under the given ancestors.
/// The provided ancestors list must contain all the parents of the given device
/// starting from its immediate parent device.
pub fn child_device_creation_message(
child_id: &str,
device_name: Option<&str>,
device_type: Option<&str>,
ancestors: &[String],
) -> Message {
Message::new(
&publish_topic_from_ancestors(ancestors),
format!(
"101,{},{},{}",
child_id,
device_name.unwrap_or(child_id),
device_type.unwrap_or("thin-edge.io-child")
),
)
}

/// Create a SmartREST message for creating a service on device.
/// The provided ancestors list must contain all the parents of the given service
/// starting from its immediate parent device.
pub fn service_creation_message(
service_id: &str,
service_name: &str,
service_type: &str,
service_status: &str,
ancestors: &[String],
) -> Message {
Message::new(
&publish_topic_from_ancestors(ancestors),
format!(
"102,{},{},{},{}",
service_id, service_type, service_name, service_status
),
)
}
1 change: 1 addition & 0 deletions crates/core/c8y_api/src/smartrest/mod.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
pub mod alarm;
pub mod error;
pub mod inventory;
pub mod message;
pub mod operations;
pub mod smartrest_deserializer;
Expand Down
48 changes: 36 additions & 12 deletions crates/core/c8y_api/src/smartrest/topic.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ impl C8yTopic {
match entity.r#type {
EntityType::MainDevice => Some(C8yTopic::upstream_topic()),
EntityType::ChildDevice | EntityType::Service => {
Self::ChildSmartRestResponse(entity.entity_id.clone())
Self::ChildSmartRestResponse(entity.external_id.clone().into())
.to_topic()
.ok()
}
Expand Down Expand Up @@ -103,17 +103,6 @@ impl From<C8yTopic> for TopicFilter {
}
}

// FIXME this From conversion is error prone as this can only be used for responses.
impl From<&EntityMetadata> for C8yTopic {
fn from(value: &EntityMetadata) -> Self {
match value.r#type {
EntityType::MainDevice => Self::SmartRestResponse,
EntityType::ChildDevice => Self::ChildSmartRestResponse(value.entity_id.clone()),
EntityType::Service => Self::SmartRestResponse, // TODO how services are handled by c8y?
}
}
}

impl From<&C8yAlarm> for C8yTopic {
fn from(value: &C8yAlarm) -> Self {
match value {
Expand Down Expand Up @@ -164,10 +153,35 @@ impl TryFrom<Topic> for MapperSubscribeTopic {
}
}

/// Generates the SmartREST topic to publish to, for a given managed object
/// from the list of external IDs of itself and all its parents.
///
/// The parents are appended in the reverse order,
/// starting from the main device at the end of the list.
/// The main device itself is represented by the root topic c8y/s/us,
/// with the rest of the children appended to it at each topic level.
///
/// # Examples
///
/// - `["main"]` -> `c8y/s/us`
/// - `["child1", "main"]` -> `c8y/s/us/child1`
/// - `["child2", "child1", "main"]` -> `c8y/s/us/child1/child2`
pub fn publish_topic_from_ancestors(ancestors: &[String]) -> Topic {
albinsuresh marked this conversation as resolved.
Show resolved Hide resolved
let mut target_topic = SMARTREST_PUBLISH_TOPIC.to_string();
for ancestor in ancestors.iter().rev().skip(1) {
// Skipping the last ancestor as it is the main device represented by the root topic itself
target_topic.push('/');
target_topic.push_str(ancestor);
}

Topic::new_unchecked(&target_topic)
}

#[cfg(test)]
mod tests {
use super::*;
use std::convert::TryInto;
use test_case::test_case;

#[test]
fn convert_c8y_topic_to_str() {
Expand Down Expand Up @@ -211,4 +225,14 @@ mod tests {
let error: Result<C8yTopic, TopicError> = Topic::new("test").unwrap().try_into();
assert!(error.is_err());
}

#[test_case(&["main"], "c8y/s/us")]
#[test_case(&["foo"], "c8y/s/us")]
#[test_case(&["child1", "main"], "c8y/s/us/child1")]
#[test_case(&["child3", "child2", "child1", "main"], "c8y/s/us/child1/child2/child3")]
fn topic_from_ancestors(ancestors: &[&str], topic: &str) {
let ancestors: Vec<String> = ancestors.iter().map(|v| v.to_string()).collect();
let nested_child_topic = publish_topic_from_ancestors(&ancestors);
assert_eq!(nested_child_topic, Topic::new_unchecked(topic));
}
}
Loading