use super::*;
use a2lfile::A2lObject;
use a2lfile::A2lObjectName;
#[allow(unused_imports)]
use log::{debug, error, info, trace, warn};
impl Registry {
pub(crate) fn load_a2lfile(&mut self, a2l_file: &a2lfile::A2lFile) -> Result<(), RegistryError> {
registry_load_a2lfile(self, a2l_file)
}
}
fn get_value_type_from_datatype(datatype: a2lfile::DataType) -> McValueType {
match datatype {
a2lfile::DataType::Ubyte => McValueType::Ubyte,
a2lfile::DataType::Sbyte => McValueType::Sbyte,
a2lfile::DataType::Uword => McValueType::Uword,
a2lfile::DataType::Sword => McValueType::Sword,
a2lfile::DataType::Ulong => McValueType::Ulong,
a2lfile::DataType::Slong => McValueType::Slong,
a2lfile::DataType::AUint64 => McValueType::Ulonglong,
a2lfile::DataType::AInt64 => McValueType::Slonglong,
a2lfile::DataType::Float32Ieee => McValueType::Float32Ieee,
a2lfile::DataType::Float64Ieee => McValueType::Float64Ieee,
_ => {
error!("Unknown datatype: {:?}", datatype);
McValueType::Ubyte
}
}
}
fn get_value_type_from_record_layout(s: &str) -> McValueType {
match s {
"__UBYTE_Z" => McValueType::Ubyte,
"__SBYTE_Z" => McValueType::Sbyte,
"__UWORD_Z" => McValueType::Uword,
"__SWORD_Z" => McValueType::Sword,
"__ULONG_Z" => McValueType::Ulong,
"__SLONG_Z" => McValueType::Slong,
"__A_UINT64_Z" => McValueType::Ulonglong,
"__A_INT64_Z" => McValueType::Slonglong,
"__FLOAT32_IEEE" => McValueType::Float32Ieee,
"__FLOAT64_IEEE" => McValueType::Float64Ieee,
"_SBYTE" => McValueType::Sbyte,
"_SLONG" => McValueType::Slong,
"_SWORD" => McValueType::Sword,
"_UBYTE" => McValueType::Ubyte,
"_ULONG" => McValueType::Ulong,
"_UWORD" => McValueType::Uword,
"U8" => McValueType::Ubyte,
"U16" => McValueType::Uword,
"U32" => McValueType::Ulong,
"U64" => McValueType::Ulonglong,
"S8" => McValueType::Sbyte,
"S16" => McValueType::Sword,
"S32" => McValueType::Slong,
"S64" => McValueType::Slonglong,
"I8" => McValueType::Sbyte,
"I16" => McValueType::Sword,
"I32" => McValueType::Slong,
"I64" => McValueType::Slonglong,
"F32" => McValueType::Float32Ieee,
"F64" => McValueType::Float64Ieee,
"BOOL" => McValueType::Bool,
"A_U8" => McValueType::Ubyte,
"A_U16" => McValueType::Uword,
"A_U32" => McValueType::Ulong,
"A_U64" => McValueType::Ulonglong,
"A_S8" => McValueType::Sbyte,
"A_S16" => McValueType::Sword,
"A_S32" => McValueType::Slong,
"A_S64" => McValueType::Slonglong,
"A_I8" => McValueType::Sbyte,
"A_I16" => McValueType::Sword,
"A_I32" => McValueType::Slong,
"A_I64" => McValueType::Slonglong,
"A_F32" => McValueType::Float32Ieee,
"A_F64" => McValueType::Float64Ieee,
"VALUE_UBYTE" => McValueType::Ubyte,
"VALUE_SBYTE" => McValueType::Sbyte,
"VALUE_UWORD" => McValueType::Uword,
"VALUE_SWORD" => McValueType::Sword,
"VALUE_ULONG" => McValueType::Ulong,
"VALUE_SLONG" => McValueType::Slong,
"VALUE_A_UINT64" => McValueType::Ulonglong,
"VALUE_A_INT64" => McValueType::Slonglong,
"VALUE_FLOAT32_IEEE" => McValueType::Float32Ieee,
"VALUE_FLOAT64_IEEE" => McValueType::Float64Ieee,
_ => {
warn!("Unknown predefined record layout name '{}'", s);
McValueType::Ubyte
}
}
}
fn get_enum_unit(compu_method: &a2lfile::CompuMethod, module: &a2lfile::Module) -> Option<String> {
let table_name = &compu_method.compu_tab_ref.as_ref()?.conversion_table;
let compu_vtab = module.compu_vtab.get(table_name)?;
if compu_vtab.value_pairs.is_empty() {
return None;
}
let mut unit = String::new();
for pair in &compu_vtab.value_pairs {
if pair.in_val.fract() != 0.0 || pair.in_val.abs() > 9007199254740992.0 || pair.out_val.contains('"') {
return None;
}
if !unit.is_empty() {
unit.push(' ');
}
#[allow(clippy::cast_possible_truncation)] let in_val = pair.in_val as i64;
unit.push_str(&format!(r#"{} "{}""#, in_val, pair.out_val));
}
Some(unit)
}
fn get_conversion(conversion: &str, module: &a2lfile::Module) -> (Option<f64>, Option<f64>, Option<String>) {
if conversion != "NO_COMPU_METHOD" && conversion != "IDENTITY" {
let opt_compu_method = module.compu_method.get(conversion);
if let Some(compu_method) = opt_compu_method {
let name = compu_method.get_name();
match compu_method.conversion_type {
a2lfile::ConversionType::Identical => (None, None, None),
a2lfile::ConversionType::Linear => {
let Some(coeffs_linear) = compu_method.coeffs_linear.as_ref() else {
warn!("Compu method {}: COEFFS_LINEAR missing, conversion ignored", name);
return (None, None, None);
};
(Some(coeffs_linear.a), Some(coeffs_linear.b), None)
}
a2lfile::ConversionType::RatFunc => {
let Some(coeffs) = compu_method.coeffs.as_ref() else {
warn!("Compu method {}: COEFFS missing, conversion ignored", name);
return (None, None, None);
};
if coeffs.f != 0.0 && coeffs.d == 0.0 && coeffs.e == 0.0 && coeffs.a == 0.0 {
(Some(coeffs.b / coeffs.f), Some(coeffs.c), None)
} else {
debug!("RatFunc conversion not supported: {:?}", coeffs);
(None, None, None)
}
}
a2lfile::ConversionType::TabVerb => {
if name == "BOOL" {
(None, None, None) } else {
let enum_unit = get_enum_unit(compu_method, module);
if enum_unit.is_none() {
debug!("Compu method {}: COMPU_VTAB not found or not supported", name);
}
(None, None, enum_unit)
}
}
_ => {
debug!("Compu method not supported: {:?}", compu_method.conversion_type);
(None, None, None)
}
}
} else {
error!("Compu method not found: {}", conversion);
(None, None, None)
}
} else {
(None, None, None)
}
}
fn get_event_id_from_ifdata(if_data_vec: &Vec<a2lfile::IfData>) -> Option<u16> {
for ifdata in if_data_vec {
let Some(decoded_ifdata) = aml_ifdata::A2mlVector::load_from_ifdata(ifdata) else {
continue;
};
if let Some(xcp) = decoded_ifdata.xcp {
if let Some(daq_event) = xcp.daq_event {
if let Some(fixed_event_list) = daq_event.fixed_event_list {
if let Some(event) = fixed_event_list.event.first() {
return Some(event.item);
}
warn!("IF_DATA XCP: empty FIXED_EVENT_LIST ignored");
}
if let Some(event_lists) = daq_event.variable {
if let Some(default_event_list) = event_lists.default_event_list {
if let Some(event) = default_event_list.event.first() {
return Some(event.item);
}
warn!("IF_DATA XCP: empty DEFAULT_EVENT_LIST ignored");
}
}
}
}
}
None
}
fn new_mc_address_from_a2l(_registry: &Registry, addr: u32, addr_ext: u8, event_id: Option<u16>, convert: bool) -> McAddress {
debug!("Get address {:08X} ext {} event_id {:?}", addr, addr_ext, event_id);
if !convert {
if let Some(event_id) = event_id {
McAddress::new_a2l_with_event(event_id, addr, addr_ext)
} else {
McAddress::new_a2l(addr, addr_ext)
}
} else {
unimplemented!(
"Address conversion from A2L to calseg_rel, event_rel/dyn/abs not implemented yet, this is highly dependent on the specific address encoding scheme used in the A2L file, currently only raw A2L address representation is supported"
);
}
}
fn get_matrix_dim(matrix_dim: Option<&a2lfile::MatrixDim>) -> (u16, u16) {
if let Some(m) = matrix_dim {
if m.dim_list.len() >= 3 {
error!("Matrix dimension {} >2 is not supported", m.dim_list.len());
(1, 1)
} else if m.dim_list.len() >= 2 {
(m.dim_list[0], m.dim_list[1])
} else if m.dim_list.len() == 1 {
(m.dim_list[0], 1)
} else {
(1, 1)
}
} else {
(1, 1)
}
}
#[allow(clippy::too_many_arguments)]
fn update_typedef_field(
registry: &mut Registry,
typedef_name: &str,
object_type: McObjectType,
value_type: McValueType,
matrix_dim: Option<&a2lfile::MatrixDim>,
comment: &String,
min: f64,
max: f64,
unit: Option<&String>,
factor: Option<f64>,
offset: Option<f64>,
) {
for typedef in registry.typedef_list.iter_mut() {
for field in typedef.fields.iter_mut() {
if let McValueType::TypeDef(type_name) = field.dim_type.value_type {
if type_name == typedef_name {
field.dim_type.value_type = value_type;
let dim = get_matrix_dim(matrix_dim);
field.dim_type.x_dim = Some(dim.0);
field.dim_type.y_dim = Some(dim.1);
let mc_support_data = McSupportData::new(object_type)
.set_comment(comment)
.set_min(Some(min))
.set_max(Some(max))
.set_factor(factor)
.set_offset(offset)
.set_unit(unit);
field.mc_support_data = mc_support_data;
log::debug!("Update typedef component {} with type {}", field.name, typedef_name);
}
}
}
}
}
fn registry_load_a2lfile(registry: &mut Registry, a2l_file: &a2lfile::A2lFile) -> Result<(), RegistryError> {
let mut relative_segment_addressing: bool = false; let mut convert_a2l_address: bool = false;
info!("Load A2L file into registry:");
if let Some(a2l_version) = a2l_file.asap2_version.as_ref() {
debug!(" A2l Version: {}.{}", a2l_version.version_no, a2l_version.upgrade_no);
debug!(" AML Version: {:?}", a2l_file.a2ml_version);
} else {
error!("A2l Version not found");
return Err(RegistryError::A2l("A2l Version not found".to_string()));
}
debug!(" Projectname: {}", a2l_file.project.name);
debug!(" Project description: {}", a2l_file.project.long_identifier);
if let Some(header) = a2l_file.project.header.as_ref() {
debug!(" Header comment: {}", header.comment);
if let Some(header_version) = header.version.as_ref() {
debug!(" Header version: {}", header_version.version_identifier);
}
if let Some(project_no) = header.project_no.as_ref() {
debug!(" Header project number: {}", project_no.project_number);
if project_no.project_number.starts_with("XCPLITE__") {
if project_no.project_number == "XCPLITE__ACSDD" {
relative_segment_addressing = false; convert_a2l_address = false; info!("XCPlite A2L detected, {} addressing mode", project_no.project_number);
} else if project_no.project_number == "XCPLITE__CASDD" {
relative_segment_addressing = true; convert_a2l_address = false; info!("XCPlite A2L detected, {} addressing mode", project_no.project_number);
} else {
error!(
"Unsupported XCPLITE addressing sheme, project number {}, supported are XCPLITE__ACSDD and XCPLITE__CASDD",
project_no.project_number
);
}
} else {
warn!("A2L file has not been written by xcp-lite, XCPlite (ACSDD or CASDD),or xcpclient, this is not a generic A2L reader, use at your own risk");
}
}
};
debug!(" Modulename: {}", a2l_file.project.module[0].get_name());
registry
.application
.set_info(a2l_file.project.name.clone(), format!("created from a2lfile project {}", a2l_file.project.name), 0);
let module = &a2l_file.project.module[0];
for if_data in &module.if_data {
let decoded_ifdata = if if_data.ifdata_valid {
aml_ifdata::A2mlVector::load_from_ifdata(if_data)
} else {
None
};
let Some(decoded_ifdata) = decoded_ifdata else {
warn!(
"IF_DATA in line {} does not match the built-in A2ML specification and is ignored, events defined in it are missing",
if_data.get_line()
);
continue;
};
if let Some(xcp) = decoded_ifdata.xcp {
if let Some(daq) = xcp.daq {
for e in daq.event {
info!("Event found in IF_DATA XCP: {} - {}", e.event_channel_name, e.event_channel_number);
if let Err(e) = registry.event_list.add_event(McEvent::new(e.event_channel_name, 0, e.event_channel_number, 0)) {
warn!("Failed to add event: {}", e);
}
}
}
}
}
if let Some(mod_par) = &module.mod_par {
if let Some(epk) = &mod_par.epk {
let version_epk = epk.identifier.clone();
let version_addr = if !mod_par.addr_epk.is_empty() { mod_par.addr_epk[0].address } else { 0 };
debug!("Set EPK: {} {:08X}", version_epk, version_addr);
if version_epk == crate::EPK_SEG_NAME && version_addr == 0x80000000 {
info!("XCPlite EPK '{}' detected with segment relative address", version_epk);
}
registry.application.set_version(version_epk, version_addr);
}
for (number, m) in mod_par.memory_segment.iter().enumerate() {
let Ok(number) = u8::try_from(number) else {
warn!("More than 256 memory segments, remaining segments skipped");
break;
};
let name = m.get_name().to_string();
let addr_ext = 0; let addr = m.address;
let size = m.size;
let mut index = number as u16; if relative_segment_addressing {
let i = ((addr >> 16) & 0x7FFF) as u16; index = i;
}
let res = registry.cal_seg_list.add_a2l_cal_seg(name, index, Some(number), addr_ext, addr, size);
match res {
Ok(_) => {}
Err(e) => {
warn!("Failed to add calibration segment: {}", e);
}
}
}
}
for characteristic in &module.characteristic {
let name = characteristic.get_name().to_string();
let value_type = get_value_type_from_record_layout(&characteristic.deposit);
let conversion = &characteristic.conversion;
let (factor, offset, enum_unit) = get_conversion(conversion, module);
let (x_dim, y_dim) = get_matrix_dim(characteristic.matrix_dim.as_ref());
let object_type: McObjectType = McObjectType::Characteristic;
match characteristic.characteristic_type {
a2lfile::CharacteristicType::Cuboid | a2lfile::CharacteristicType::Cube4 | a2lfile::CharacteristicType::Cube5 => {
warn!("Characteristic {} skipped, type {:?} not supported", name, characteristic.characteristic_type);
continue;
}
_ => {}
}
let mut mc_support_data = McSupportData::new(object_type)
.set_comment(characteristic.long_identifier.clone())
.set_min(Some(characteristic.lower_limit))
.set_max(Some(characteristic.upper_limit))
.set_factor(factor)
.set_offset(offset);
if let Some(u) = enum_unit {
mc_support_data = mc_support_data.set_unit(u);
} else if let Some(u) = characteristic.phys_unit.as_ref() {
mc_support_data = mc_support_data.set_unit(u.unit.clone());
}
if !characteristic.axis_descr.is_empty() {
if let Some(r) = characteristic.axis_descr[0].axis_pts_ref.as_ref() {
let s = r.axis_points.clone();
mc_support_data = mc_support_data.set_x_axis_ref(Some(s));
if characteristic.axis_descr.len() > 1 {
if let Some(r) = characteristic.axis_descr[1].axis_pts_ref.as_ref() {
let s = r.axis_points.clone();
mc_support_data = mc_support_data.set_y_axis_ref(Some(s));
}
}
}
}
let dim_type = McDimType::new(value_type, x_dim, y_dim);
let event_id = get_event_id_from_ifdata(&characteristic.if_data);
if let Some(event_id) = event_id {
info!("Characteristic {} has event id {}", name, event_id);
}
let addr_ext = characteristic.ecu_address_extension.as_ref().map(|a| a.extension).unwrap_or(0);
let Ok(addr_ext) = u8::try_from(addr_ext) else {
warn!("Characteristic {} skipped, address extension {} out of range", name, addr_ext);
continue;
};
let addr = characteristic.address;
let address = new_mc_address_from_a2l(registry, addr, addr_ext, event_id, convert_a2l_address);
let res = registry.instance_list.add_instance(name, dim_type, mc_support_data, address);
match res {
Ok(_) => {}
Err(e) => {
warn!("Failed to add characteristic instance: {}", e);
}
}
}
for measurement in &module.measurement {
let name = measurement.get_name().to_string();
let _read_write = measurement.read_write.is_some();
let datatype = measurement.datatype;
let lower_limit = measurement.lower_limit;
let upper_limit = measurement.upper_limit;
let _display_identifier = &measurement.display_identifier;
let _resolution = measurement.resolution;
let conversion = &measurement.conversion;
let phys_unit = &measurement.phys_unit;
let (factor, offset, enum_unit) = get_conversion(conversion, module);
let matrix_dim = &measurement.matrix_dim;
let (x_dim, y_dim) = get_matrix_dim(matrix_dim.as_ref());
let object_type: McObjectType = McObjectType::Measurement;
let value_type = get_value_type_from_datatype(datatype);
let mut mc_support_data = McSupportData::new(object_type)
.set_comment(measurement.long_identifier.clone())
.set_min(Some(lower_limit))
.set_max(Some(upper_limit))
.set_factor(factor)
.set_offset(offset);
if let Some(u) = enum_unit {
mc_support_data = mc_support_data.set_unit(u);
} else if let Some(u) = phys_unit.as_ref() {
mc_support_data = mc_support_data.set_unit(u.unit.clone());
}
let dim_type = McDimType::new(value_type, x_dim, y_dim);
let event_id = get_event_id_from_ifdata(&measurement.if_data);
if event_id.is_none() {
warn!("Measurement {} has no event id", name);
}
let addr = if let Some(a) = measurement.ecu_address.as_ref() { a.address } else { 0 };
let addr_ext = measurement.ecu_address_extension.as_ref().map(|a| a.extension).unwrap_or(0);
let Ok(addr_ext) = u8::try_from(addr_ext) else {
warn!("Measurement {} skipped, address extension {} out of range", name, addr_ext);
continue;
};
let address = new_mc_address_from_a2l(registry, addr, addr_ext, event_id, convert_a2l_address);
let unique_name = if registry.instance_list.get_instance(&name, object_type, None).is_some() {
if let Some(event_id) = event_id {
if let Some(event) = registry.event_list.find_event_id(event_id) {
warn!("Measurement instance name '{}' is not unique, using event name '{}' as prefix", name, event.name);
format!("{}.{}", event.name, name)
} else {
name
}
} else {
name
}
} else {
name
};
let res = registry.instance_list.add_instance(unique_name, dim_type, mc_support_data, address);
match res {
Ok(_) => {}
Err(e) => {
warn!("Failed to add measurement instance: {}", e);
}
}
}
for typedef in &module.typedef_structure {
let typedef_name = typedef.get_name().to_string();
let res = registry.add_typedef(typedef_name, typedef.total_size as usize);
match res {
Ok(_) => {}
Err(e) => {
warn!("Failed to add typedef: {}", e);
}
}
for field in &typedef.structure_component {
let typedef_name = typedef.get_name();
let field_name = field.get_name().to_string();
let matrix_dim = &field.matrix_dim;
let (x_dim, y_dim) = get_matrix_dim(matrix_dim.as_ref());
let Ok(offset) = u16::try_from(field.address_offset) else {
warn!("Typedef field {}.{} skipped, offset {} out of range", typedef_name, field_name, field.address_offset);
continue;
};
let value_type = McValueType::TypeDef(field.component_type.clone().into());
let mc_support_data = McSupportData::new(McObjectType::Unspecified);
let dim_type = McDimType::new(value_type, x_dim, y_dim);
let res = registry.add_typedef_field(typedef_name, field_name, dim_type, mc_support_data, offset);
match res {
Ok(_) => {}
Err(e) => {
warn!("Failed to add typedef field: {}", e);
}
}
}
}
for typedef in &module.typedef_measurement {
let name = typedef.get_name();
let conversion = &typedef.conversion;
let (factor, offset, enum_unit) = get_conversion(conversion, module);
let comment = &typedef.long_identifier;
let min = typedef.lower_limit;
let max = typedef.upper_limit;
let unit = enum_unit.as_ref().or(typedef.phys_unit.as_ref().map(|u| &u.unit));
let value_type = get_value_type_from_datatype(typedef.datatype);
update_typedef_field(
registry,
name,
McObjectType::Measurement,
value_type,
typedef.matrix_dim.as_ref(),
comment,
min,
max,
unit,
factor,
offset,
);
}
for typedef in &module.typedef_characteristic {
let name = typedef.get_name();
let conversion = &typedef.conversion;
let (factor, offset, enum_unit) = get_conversion(conversion, module);
let record_layout = &typedef.record_layout;
let comment = &typedef.long_identifier;
let min = typedef.lower_limit;
let max = typedef.upper_limit;
let unit = enum_unit.as_ref().or(typedef.phys_unit.as_ref().map(|u| &u.unit));
let value_type = get_value_type_from_record_layout(record_layout);
let _sub_type = typedef.characteristic_type; update_typedef_field(
registry,
name,
McObjectType::Characteristic,
value_type,
typedef.matrix_dim.as_ref(),
comment,
min,
max,
unit,
factor,
offset,
);
}
for typedef in &module.typedef_axis {
let name = typedef.get_name();
let conversion = &typedef.conversion;
let (factor, offset, enum_unit) = get_conversion(conversion, module);
let record_layout = &typedef.record_layout;
let comment = &typedef.long_identifier;
let min = typedef.lower_limit;
let max = typedef.upper_limit;
let unit = enum_unit.as_ref().or(typedef.phys_unit.as_ref().map(|u| &u.unit));
let value_type = get_value_type_from_record_layout(record_layout);
update_typedef_field(registry, name, McObjectType::Axis, value_type, None, comment, min, max, unit, factor, offset);
}
for instance in &module.instance {
let name = instance.get_name().to_string();
let matrix_dim = &instance.matrix_dim;
let (x_dim, y_dim) = if let Some(m) = matrix_dim.as_ref() {
if m.dim_list.len() >= 3 {
error!("Matrix dimension {} >2 is not supported", m.dim_list.len());
(1, 1)
} else if m.dim_list.len() >= 2 {
(m.dim_list[0], m.dim_list[1])
} else if m.dim_list.len() == 1 {
(m.dim_list[0], 1)
} else {
(1, 1)
}
} else {
(1, 1)
};
let event_id = get_event_id_from_ifdata(&instance.if_data);
let object_type: McObjectType = if event_id.is_none() { McObjectType::Characteristic } else { McObjectType::Measurement };
let comment = &instance.long_identifier;
let value_type = McValueType::TypeDef(instance.type_ref.clone().into());
let mc_support_data = McSupportData::new(object_type).set_comment(comment.clone());
let dim_type = McDimType::new(value_type, x_dim, y_dim);
let addr = instance.start_address;
let addr_ext = instance.ecu_address_extension.as_ref().map(|a| a.extension).unwrap_or(0);
let Ok(addr_ext) = u8::try_from(addr_ext) else {
warn!("Instance {} skipped, address extension {} out of range", name, addr_ext);
continue;
};
let address = new_mc_address_from_a2l(registry, addr, addr_ext, event_id, convert_a2l_address);
let res = registry.instance_list.add_instance(name, dim_type, mc_support_data, address);
match res {
Ok(_) => {}
Err(e) => {
warn!("Failed to add typedef instance: {}", e);
}
}
}
Ok(())
}