修改该了关于info信息为json内部管理 该项目只适用于windows或linux 修改了c++及相应的rust代码 不适用于arm

This commit is contained in:
xin
2025-06-17 17:02:35 +08:00
parent a500813e45
commit ae30c24a8f
10 changed files with 464 additions and 218 deletions

View File

@ -20,8 +20,6 @@ struct IRIS_Time_Struct
}; };
``` ```
## 2.根文件结构 ## 2.根文件结构
数去分为4个区域分别是 高光谱数据SpectralData、高光谱元数据(SpectralInfo)、其他信息(Other)、图片信息(Image) 数去分为4个区域分别是 高光谱数据SpectralData、高光谱元数据(SpectralInfo)、其他信息(Other)、图片信息(Image)
@ -70,6 +68,69 @@ struct IRIS_Time_Struct
3、 波长信息 如果提供的是波长系数 则用json保存 存储结构是 sensor_id--wevainfo--a[0],a[1],a[2],a[3] 如果是波长数组 则用0x03保存 json中可以用IS_Weave_ARR来标识波长信息在0x03中 3、 波长信息 如果提供的是波长系数 则用json保存 存储结构是 sensor_id--wevainfo--a[0],a[1],a[2],a[3] 如果是波长数组 则用0x03保存 json中可以用IS_Weave_ARR来标识波长信息在0x03中
4、元数据还应包含环境数据 Environment 信息 至少包含日期Date和Time 信息 4、元数据还应包含环境数据 Environment 信息 至少包含日期Date和Time 信息
多json分散存储
```json
{
"info_type": "devinfo",
"sensor_id": "is30002",
"bandnum": 2048,
"wave_coeff": {
"a1": 0.0,
"a2": 0.0,
"a3": 400,
"a4": 1.0
}
}
```
一个json包含所有
```json
{
"info_type": "infolist", // infolist 标识该json存储了多个info
"info_number":3, // 必须
"info_list": [
{
"info_type": "devinfo", // info类型为设备信息 // 必须
"sensor_id": "is30002", // 必须
"bandnum": 2048, // 必须
"wave_coeff": {
"a1": 0.0, // 必须
"a2": 0.0, // 必须
"a3": 400, // 必须
"a4": 1.0 // 必须
}
},
{
"info_type": "environment", // info类型为环境信息 必须
"date": "2000-01-00 00:00:00", // 必须
//下面可选
"humidity":90.0,
"temperature":35.0 ,
"gps":{
"latitude":115.01,
"longitude": 39.01,
"altitude": 100.0
},
},
{
"info_type": "devinfo", // 0 for device info
"sensor_id": "is20001",
"bandnum": 512,
"wave_coeff": {
"a1": 0,
"a2": 0.0,
"a3":390,
"a4": 4
}
}
]
}
```
##2.2 高光谱数据 ##2.2 高光谱数据

View File

@ -1,4 +1,4 @@
use crate::{read, structures::{ImageInfo, OneIRISData, OtherInfo, SpectralData, SpectralInfo, TimeStruct, DATA_TYPE_FLOAT64}, write}; use crate::{read, structures::{ImageInfo, OneIRISData, SpectralData, TimeStruct, DATA_TYPE_FLOAT64}, write};
use std::{io::{Cursor, Write}, vec}; use std::{io::{Cursor, Write}, vec};
pub fn spectral_data_roundtrip() { pub fn spectral_data_roundtrip() {
@ -30,45 +30,7 @@ pub fn spectral_data_roundtrip() {
println!("Roundtrip test passed successfully!"); println!("Roundtrip test passed successfully!");
} }
pub fn spectral_info_roundtrip() {
// Create sample spectral info
let mut info = SpectralInfo::new();
info.sensor_id = "SENSOR-001".to_string();
info.wave_coeff = [400.0, 0.5, 0.01, 0.001];
// Write to buffer
let mut buffer = Vec::new();
write::write_spectral_info(&info, &mut buffer).unwrap();
// Read back from buffer
let mut reader = Cursor::new(buffer);
let read_info = read::read_spectral_info(&mut reader).unwrap();
// Verify roundtrip
assert_eq!(info.sensor_id, read_info.sensor_id);
assert_eq!(info.wave_coeff, read_info.wave_coeff);
println!("Spectral info roundtrip test passed successfully!");
}
pub fn other_info_roundtrip() {
// Create sample other info
let mut info = OtherInfo::new();
info.info_type = 1;
info.data = vec![1, 2, 3, 4, 5];
// Write to buffer
let mut buffer = Vec::new();
write::write_other_info(&info, &mut buffer).unwrap();
// Read back from buffer
let mut reader = Cursor::new(buffer);
let read_info = read::read_other_info(&mut reader).unwrap();
// Verify roundtrip
assert_eq!(info.info_type, read_info.info_type);
assert_eq!(info.data, read_info.data);
println!("Other info roundtrip test passed successfully!");
}
pub fn image_info_roundtrip() { pub fn image_info_roundtrip() {
// Create sample image info // Create sample image info
@ -104,8 +66,7 @@ pub fn read_iris_file_example() {
// test_data.spectral_data_section.push(spectral); // test_data.spectral_data_section.push(spectral);
// Write to a temporary file // Write to a temporary file
let path = "iris_data_example.iris";
// let path = "output_iris_data.iris";
// { // {
// let file = std::fs::File::create(path).unwrap(); // let file = std::fs::File::create(path).unwrap();
// let mut writer = std::io::BufWriter::new(file); // let mut writer = std::io::BufWriter::new(file);
@ -124,6 +85,8 @@ pub fn read_iris_file_example() {
// } // }
// Now read it back // Now read it back
let path = "output_iris_data1.iris";
// let path = "output_iris_data.iris";
let mut read=match read::read_iris_file(path) { let mut read=match read::read_iris_file(path) {
Ok(data) => { Ok(data) => {
println!("Successfully read IRIS file:"); println!("Successfully read IRIS file:");
@ -146,6 +109,11 @@ pub fn read_iris_file_example() {
OneIRISData::new() OneIRISData::new()
} }
}; };
let spectralinfonum = read.spectral_info_section.len();
for info in &read.spectral_info_section {
println!("{}",info)
}
let mut aaa=read.spectral_data_section[2].Get_Spectral_Data(); let mut aaa=read.spectral_data_section[2].Get_Spectral_Data();
let mut bbb =vec![0f64; 256]; let mut bbb =vec![0f64; 256];
//随机生成一些数据 //随机生成一些数据
@ -157,5 +125,5 @@ pub fn read_iris_file_example() {
println!("Spectral Data Length: {}", ccc.len()); println!("Spectral Data Length: {}", ccc.len());
write::wirte_iris_data(&read, "output_iris_data1.iris").unwrap(); write::wirte_iris_data(&read, "output_iris_data2.iris").unwrap();
} }

View File

@ -3,7 +3,7 @@ pub mod read;
pub mod write; pub mod write;
pub mod examples; pub mod examples;
pub use structures::{TimeStruct, SpectralData, SpectralInfo, OtherInfo, ImageInfo, OneIRISData}; pub use structures::{TimeStruct, SpectralData, ImageInfo, OneIRISData};
pub use read::{read_time, read_spectral_data, read_spectral_info, read_other_info, read_image_info, read_iris_file}; pub use read::{read_time, read_spectral_data, read_image_info, read_iris_file};
pub use write::*; pub use write::*;
pub use examples::{spectral_data_roundtrip, spectral_info_roundtrip}; pub use examples::{spectral_data_roundtrip};

View File

@ -1,7 +1,5 @@
use iris_rust::examples::{ use iris_rust::examples::{
spectral_data_roundtrip, spectral_data_roundtrip,
spectral_info_roundtrip,
other_info_roundtrip,
image_info_roundtrip, image_info_roundtrip,
read_iris_file_example read_iris_file_example
}; };

View File

@ -1,7 +1,8 @@
use std::io::{Read, Result, BufReader}; use std::io::{Read, Result, BufReader};
use std::fs::File; use std::fs::File;
use std::convert::TryInto; use std::convert::TryInto;
use super::structures::{TimeStruct, SpectralData, SpectralInfo, OtherInfo, ImageInfo, OneIRISData}; use super::structures::{TimeStruct, SpectralData, ImageInfo, OneIRISData};
use serde_json::Value; use serde_json::Value;
pub fn read_time<R: Read>(reader: &mut R) -> Result<TimeStruct> { pub fn read_time<R: Read>(reader: &mut R) -> Result<TimeStruct> {
let mut buffer = [0u8; 10]; // Corrected buffer size to 10 bytes let mut buffer = [0u8; 10]; // Corrected buffer size to 10 bytes
@ -19,24 +20,7 @@ pub fn read_time<R: Read>(reader: &mut R) -> Result<TimeStruct> {
}) })
} }
pub fn read_spectral_info<R: Read>(reader: &mut R) -> Result<SpectralInfo> {
let mut info = SpectralInfo::new();
// Read sensor ID
let mut sensor_buf = [0u8; 50];
reader.read_exact(&mut sensor_buf)?;
info.sensor_id = String::from_utf8_lossy(&sensor_buf).trim_end_matches('\0').to_string();
info.sensor_id = remove_after_null_split_once( info.sensor_id);
// Read wave coefficients
for i in 0..4 {
let mut float_buf = [0u8; 8];
reader.read_exact(&mut float_buf)?;
info.wave_coeff[i] = f64::from_le_bytes(float_buf);
}
Ok(info)
}
pub fn read_image_info<R: Read>(reader: &mut R) -> Result<ImageInfo> { pub fn read_image_info<R: Read>(reader: &mut R) -> Result<ImageInfo> {
let mut info = ImageInfo::new(); let mut info = ImageInfo::new();
@ -127,14 +111,79 @@ pub fn read_iris_file(path: &str) -> Result<OneIRISData> {
continue; // Skip this entry if parsing fails continue; // Skip this entry if parsing fails
} }
}; // Handle parsing error gracefully }; // Handle parsing error gracefully
//判断json["info_type"]是否存在
if !json.get("info_type").is_some() {
eprintln!("JSON does not contain 'info_type': {}", json_string);
continue; // Skip this entry if "info_type" is missing
}
/* {
"info_type": "infolist", // 0 for device info
"info_number":3,
"info_list": [
{
"info_type": "devinfo", // 0 for device info
"sensor_id": "is30002",
"bandnum": 2048,
"wave_coeff": {
"a1": 0.0,
"a2": 0.0,
"a3": 400,
"a4": 1.0
}
},
{
"info_type": "environment", // 1 for gain info
"date": "2000-01-00 00:00:00",
//下面可选
"humidity":90.0,
"temperature":35.0 ,
"gps":{
"latitude":115.01,
"longitude": 39.01,
"altitude": 100.0
},
},
{
"info_type": "devinfo", // 0 for device info
"sensor_id": "is20001",
"bandnum": 512,
"wave_coeff": {
"a1": 0,
"a2": 0.0,
"a3":390,
"a4": 4
}
}
]
} */
//如果info_type是infolist 则需要逐个解析
if json.get("info_type").and_then(Value::as_str) == Some("infolist") {
let info_number = json.get("info_number").and_then(Value::as_u64).unwrap_or(0) as usize;
for i in 0 ..info_number{
//将对应的info加入到data中
if let Some(info) = json.get("info_list").and_then(|list| list.get(i)) {
data.push(info.clone());
}
}
continue; // Skip the rest of the loop for this entry
}
data.push(json);
//println!("Parsed JSON: {:?}", json); //println!("Parsed JSON: {:?}", json);
let mut data_entry = SpectralInfo::new(); // let mut data_entry = SpectralInfo::new();
data_entry.sensor_id = json.get("SensorId").and_then(Value::as_str).unwrap_or_default().to_string(); // data_entry.sensor_id = json.get("SensorId").and_then(Value::as_str).unwrap_or_default().to_string();
data_entry.wave_coeff[0]=json["WaveCoeff"]["a1"].as_f64().unwrap_or(0.0); // data_entry.wave_coeff[0]=json["WaveCoeff"]["a1"].as_f64().unwrap_or(0.0);
data_entry.wave_coeff[1]=json["WaveCoeff"]["a2"].as_f64().unwrap_or(0.0); // data_entry.wave_coeff[1]=json["WaveCoeff"]["a2"].as_f64().unwrap_or(0.0);
data_entry.wave_coeff[2]=json["WaveCoeff"]["a3"].as_f64().unwrap_or(0.0); // data_entry.wave_coeff[2]=json["WaveCoeff"]["a3"].as_f64().unwrap_or(0.0);
data_entry.wave_coeff[3]=json["WaveCoeff"]["a4"].as_f64().unwrap_or(0.0); // data_entry.wave_coeff[3]=json["WaveCoeff"]["a4"].as_f64().unwrap_or(0.0);
data.push(data_entry); // data.push(data_entry);
// Parse JSON string // Parse JSON string
@ -151,7 +200,25 @@ pub fn read_iris_file(path: &str) -> Result<OneIRISData> {
let count = read_section_count(&mut reader)?; let count = read_section_count(&mut reader)?;
let mut data = Vec::with_capacity(count); let mut data = Vec::with_capacity(count);
for _ in 0..count { for _ in 0..count {
data.push(read_other_info(&mut reader)?); let mut tempbuffer = [0u8; 3]; // Adjust size as needed
reader.read_exact(&mut tempbuffer)?;
let lenth = u16::from_le_bytes([tempbuffer[0], tempbuffer[1]]) as usize;
let info_type = u8::from_le_bytes([tempbuffer[2]]);
let mut tempvector = vec![0u8; lenth];
reader.read_exact(&mut tempvector)?;
// Convert to String
let json_string = String::from_utf8(tempvector).unwrap_or_default();
let json_string = json_string.trim_end_matches('\0').to_string();
//print!("JSON String: {}", json_string);
let json: Value = match serde_json::from_str(&json_string) {
Ok(json) => json,
Err(e) => {
eprintln!("Error parsing JSON: {}", e);
continue; // Skip this entry if parsing fails
}
}; // Handle parsing error gracefully
data.push(json);
} }
iris_data.other_info_section = data; iris_data.other_info_section = data;
}, },
@ -185,25 +252,25 @@ fn read_section_count<R: Read>(reader: &mut R) -> Result<usize> {
Ok(u16::from_le_bytes(count_buf) as usize) Ok(u16::from_le_bytes(count_buf) as usize)
} }
pub fn read_other_info<R: Read>(reader: &mut R) -> Result<OtherInfo> { // pub fn read_other_info<R: Read>(reader: &mut R) -> Result<OtherInfo> {
let mut info = OtherInfo::new(); // let mut info = OtherInfo::new();
// Read info type // // Read info type
let mut type_buf = [0u8; 1]; // let mut type_buf = [0u8; 1];
reader.read_exact(&mut type_buf)?; // reader.read_exact(&mut type_buf)?;
info.info_type = type_buf[0]; // info.info_type = type_buf[0];
// Read data length // // Read data length
let mut len_buf = [0u8; 8]; // let mut len_buf = [0u8; 8];
reader.read_exact(&mut len_buf)?; // reader.read_exact(&mut len_buf)?;
let data_len = u64::from_le_bytes(len_buf) as usize; // let data_len = u64::from_le_bytes(len_buf) as usize;
// Read data // // Read data
info.data.resize(data_len, 0); // info.data.resize(data_len, 0);
reader.read_exact(&mut info.data)?; // reader.read_exact(&mut info.data)?;
Ok(info) // Ok(info)
} // }
fn remove_after_null_split_once(s: String) -> String { fn remove_after_null_split_once(s: String) -> String {
if let Some((before_null, _after_null)) = s.split_once('\0') { if let Some((before_null, _after_null)) = s.split_once('\0') {
// 返回 \0 之前的部分 // 返回 \0 之前的部分

View File

@ -13,12 +13,15 @@ pub const Target_Spectral_Type_DN:u8 = 0x00;
pub const Target_Spectral_Type_Rad:u8 = 0x01; pub const Target_Spectral_Type_Rad:u8 = 0x01;
pub const Target_Spectral_Type_Ref:u8 = 0x02; pub const Target_Spectral_Type_Ref:u8 = 0x02;
pub const Target_Spectral_Type_IRad:u8 = 0x03; pub const Target_Spectral_Type_IRad:u8 = 0x03;
pub const Target_Spectral_Type_CaliFile:u8 = 0x04; pub const Target_Spectral_Type_CaliFile_Gain:u8 = 0x04;
pub const Target_Spectral_Type_FlatRef:u8 = 0x05; pub const Target_Spectral_Type_FlatRef:u8 = 0x05;
pub const Target_Spectral_Type_DarkDN:u8 = 0x06; pub const Target_Spectral_Type_DarkDN:u8 = 0x06;
pub const Target_Spectral_Type_FlatDN:u8 = 0x07; pub const Target_Spectral_Type_FlatDN:u8 = 0x07;
pub const Target_LAMP_VALUE_SCALED:u8 = 0x08;
use serde_json::json;
#[derive(Debug, Clone, PartialEq)] #[derive(Debug, Clone, PartialEq)]
@ -293,26 +296,26 @@ impl SpectralData {
} }
} }
#[derive(Debug, Clone, PartialEq)] // #[derive(Debug, Clone, PartialEq)]
pub struct OtherInfo { // pub struct OtherInfo {
pub info_type: u8, // pub info_type: u8,
pub data: Vec<u8>, // Assuming the data is variable length // pub data: Vec<u8>, // Assuming the data is variable length
} // }
impl OtherInfo { // impl OtherInfo {
pub fn new() -> Self { // pub fn new() -> Self {
OtherInfo { // OtherInfo {
info_type: 0, // info_type: 0,
data: Vec::new(), // data: Vec::new(),
} // }
} // }
} // }
#[derive(Debug, Clone, PartialEq)] #[derive(Debug, Clone, PartialEq)]
pub struct OneIRISData { pub struct OneIRISData {
pub spectral_data_section: Vec<SpectralData>, pub spectral_data_section: Vec<SpectralData>,
pub spectral_info_section: Vec<SpectralInfo>, pub spectral_info_section: Vec<serde_json::Value>, // Using serde_json::Value for flexibility
pub other_info_section: Vec<OtherInfo>, pub other_info_section: Vec<serde_json::Value>,
pub image_info_section: Vec<ImageInfo>, pub image_info_section: Vec<ImageInfo>,
} }
@ -327,20 +330,21 @@ impl OneIRISData {
} }
} }
#[derive(Debug, Clone, PartialEq)] // #[derive(Debug, Clone, PartialEq)]
pub struct SpectralInfo { // pub struct SpectralInfo {
pub sensor_id: String, // pub sensor_id: String,
pub wave_coeff: [f64; 4], // pub wave_coeff: [f64; 4],
}
// }
impl SpectralInfo { // impl SpectralInfo {
pub fn new() -> Self { // pub fn new() -> Self {
SpectralInfo { // SpectralInfo {
sensor_id: String::new(), // sensor_id: String::new(),
wave_coeff: [0.0; 4], // wave_coeff: [0.0; 4],
} // }
} // }
} // }
#[derive(Debug, Clone, PartialEq)] #[derive(Debug, Clone, PartialEq)]
pub struct ImageInfo { pub struct ImageInfo {
@ -384,19 +388,19 @@ mod tests {
assert!(data.spectral_data.is_empty()); assert!(data.spectral_data.is_empty());
} }
#[test] // #[test]
fn test_spectral_info() { // fn test_spectral_info() {
let info = SpectralInfo::new(); // let info = SpectralInfo::new();
assert_eq!(info.sensor_id, ""); // assert_eq!(info.sensor_id, "");
assert_eq!(info.wave_coeff, [0.0; 4]); // assert_eq!(info.wave_coeff, [0.0; 4]);
} // }
#[test] // #[test]
fn test_other_info() { // fn test_other_info() {
let info = OtherInfo::new(); // let info = OtherInfo::new();
assert_eq!(info.info_type, 0); // assert_eq!(info.info_type, 0);
assert!(info.data.is_empty()); // assert!(info.data.is_empty());
} // }
#[test] #[test]
fn test_image_info() { fn test_image_info() {

View File

@ -3,9 +3,9 @@ use std::io::{self, Write, Result};
use std::vec; use std::vec;
use serde_json::json; use serde_json::json;
use crate::write; // use crate::write;
use super::structures::{TimeStruct, SpectralData, SpectralInfo, OtherInfo, ImageInfo,OneIRISData}; use super::structures::{TimeStruct, SpectralData, ImageInfo,OneIRISData};
// Internal writer functions remain the same // Internal writer functions remain the same
fn write_time<W: Write>(time: &TimeStruct, writer: &mut W) -> Result<()> { fn write_time<W: Write>(time: &TimeStruct, writer: &mut W) -> Result<()> {
@ -20,19 +20,6 @@ fn write_time<W: Write>(time: &TimeStruct, writer: &mut W) -> Result<()> {
Ok(()) Ok(())
} }
pub fn write_spectral_info<W: Write>(info: &SpectralInfo, writer: &mut W) -> Result<()> {
// Write sensor ID
let mut sensor_buf = [0u8; 50];
sensor_buf[..info.sensor_id.len().min(49)].copy_from_slice(info.sensor_id.as_bytes());
writer.write_all(&sensor_buf)?;
// Write wave coefficients
for coeff in &info.wave_coeff {
writer.write_all(&coeff.to_le_bytes())?;
}
Ok(())
}
pub fn write_image_info<W: Write>(info: &ImageInfo, writer: &mut W) -> Result<()> { pub fn write_image_info<W: Write>(info: &ImageInfo, writer: &mut W) -> Result<()> {
// Write data length // Write data length
@ -57,17 +44,6 @@ pub fn write_image_info<W: Write>(info: &ImageInfo, writer: &mut W) -> Result<()
} }
pub fn write_other_info<W: Write>(info: &OtherInfo, writer: &mut W) -> Result<()> {
// Write info type
writer.write_all(&[info.info_type])?;
// Write data length
writer.write_all(&(info.data.len() as u64).to_le_bytes())?;
// Write data
writer.write_all(&info.data)?;
Ok(())
}
pub fn write_spectral_data<W: Write>(data: &SpectralData, writer: &mut W) -> Result<()> { pub fn write_spectral_data<W: Write>(data: &SpectralData, writer: &mut W) -> Result<()> {
// Write fixed-size fields // Write fixed-size fields
@ -82,7 +58,7 @@ pub fn write_spectral_data<W: Write>(data: &SpectralData, writer: &mut W) -> Res
sensor_buf[..data.sensor_id.len().min(49)].copy_from_slice(sensor_id_bytes[0..sensor_id_bytes.len().min(49)].as_ref()); sensor_buf[..data.sensor_id.len().min(49)].copy_from_slice(sensor_id_bytes[0..sensor_id_bytes.len().min(49)].as_ref());
writer.write_all(&sensor_buf)?; writer.write_all(&sensor_buf)?;
writer.write_all(&[data.fiber_id])?; writer.write_all(&[data.fiber_id])?;
write_time(&data.collection_time, writer)?; write_time(&data.collection_time, writer)?;
writer.write_all(&data.exposure.to_le_bytes())?; writer.write_all(&data.exposure.to_le_bytes())?;
writer.write_all(&data.gain.to_le_bytes())?; writer.write_all(&data.gain.to_le_bytes())?;
@ -140,7 +116,7 @@ pub fn caculate_image_info_length(data: &Vec<ImageInfo>) -> u64 {
} }
pub fn cacluate_other_info_length(data: &Vec<OtherInfo>) -> (Vec<u8>, u64) { pub fn cacluate_other_info_length(data: &Vec<serde_json::Value>) -> (Vec<u8>, u64) {
let mut lenth: u64 = 0; let mut lenth: u64 = 0;
let mut vecback= Vec::new(); let mut vecback= Vec::new();
if data.is_empty() { if data.is_empty() {
@ -157,7 +133,7 @@ pub fn cacluate_other_info_length(data: &Vec<OtherInfo>) -> (Vec<u8>, u64) {
(vecback, lenth) (vecback, lenth)
} }
pub fn caculate_spectral_info_length(data: &Vec<SpectralInfo>) -> (Vec<u8>, u64) { pub fn caculate_spectral_info_length(data: &Vec<serde_json::Value>) -> (Vec<u8>, u64) {
let mut lenth: u64 = 0; let mut lenth: u64 = 0;
let mut vecback= Vec::new(); let mut vecback= Vec::new();
if data.is_empty() { if data.is_empty() {
@ -175,15 +151,7 @@ pub fn caculate_spectral_info_length(data: &Vec<SpectralInfo>) -> (Vec<u8>, u64)
lenth+=2; lenth+=2;
lenth+=1; lenth+=1;
let mut lenthofthisinfo:u16=0; let mut lenthofthisinfo:u16=0;
let json=json!({ let json=info;
"SensorId": info.sensor_id,
"WaveCoeff": {
"a1": info.wave_coeff[0],
"a2": info.wave_coeff[1],
"a3": info.wave_coeff[2],
"a4": info.wave_coeff[3]
}
});
let json_string = serde_json::to_string(&json).unwrap(); let json_string = serde_json::to_string(&json).unwrap();
let json_bytes = json_string.as_bytes(); let json_bytes = json_string.as_bytes();
lenthofthisinfo= json_bytes.len() as u16+1; lenthofthisinfo= json_bytes.len() as u16+1;

View File

@ -21,13 +21,13 @@ uint64_t get_Sepctral_Info_to_Byte(Sepctral_Info_Section_Data_Struct *sepctralin
} }
for (size_t i = 0; i < number_of_spectral_info; i++) for (size_t i = 0; i < number_of_spectral_info; i++)
{ {
json j; json j=sepctralinfo->SepctralInfoAddressList[i].Info;
std::string SensorId=sepctralinfo->SepctralInfoAddressList[i].SensorId; // std::string SensorId=sepctralinfo->SepctralInfoAddressList[i].SensorId;
j["SensorId"] =SensorId; // j["SensorId"] =SensorId;
j["WaveCoeff"]["a1"] = sepctralinfo->SepctralInfoAddressList[i].WaveCoeff[0]; // j["WaveCoeff"]["a1"] = sepctralinfo->SepctralInfoAddressList[i].WaveCoeff[0];
j["WaveCoeff"]["a2"] =sepctralinfo->SepctralInfoAddressList[i].WaveCoeff[1]; // j["WaveCoeff"]["a2"] =sepctralinfo->SepctralInfoAddressList[i].WaveCoeff[1];
j["WaveCoeff"]["a3"] = sepctralinfo->SepctralInfoAddressList[i].WaveCoeff[2]; // j["WaveCoeff"]["a3"] = sepctralinfo->SepctralInfoAddressList[i].WaveCoeff[2];
j["WaveCoeff"]["a4"] = sepctralinfo->SepctralInfoAddressList[i].WaveCoeff[3]; // j["WaveCoeff"]["a4"] = sepctralinfo->SepctralInfoAddressList[i].WaveCoeff[3];
std::string json_str = j.dump(); std::string json_str = j.dump();
uint16_t json_length = strlen(json_str.c_str())+1; uint16_t json_length = strlen(json_str.c_str())+1;
@ -83,9 +83,9 @@ uint64_t get_Other_Info_to_Byte(Other_Info_Section_Data_Struct *otherdata,uint8_
} }
for (size_t i = 0; i < number_of_spectral_info; i++) for (size_t i = 0; i < number_of_spectral_info; i++)
{ {
json j; json j=otherdata->OtherInfoAddressList[i].Info;
uint8_t Type=otherdata->OtherInfoAddressList[i].Type; // uint8_t Type=otherdata->OtherInfoAddressList[i].Type;
j["Type"] =Type; // j["Type"] =Type;
// j["WaveCoeff"]["a1"] = otherdata->SepctralInfoAddressList[i].WaveCoeff[0]; // j["WaveCoeff"]["a1"] = otherdata->SepctralInfoAddressList[i].WaveCoeff[0];
// j["WaveCoeff"]["a2"] =otherdata->SepctralInfoAddressList[i].WaveCoeff[1]; // j["WaveCoeff"]["a2"] =otherdata->SepctralInfoAddressList[i].WaveCoeff[1];
// j["WaveCoeff"]["a3"] = otherdata->SepctralInfoAddressList[i].WaveCoeff[2]; // j["WaveCoeff"]["a3"] = otherdata->SepctralInfoAddressList[i].WaveCoeff[2];
@ -126,16 +126,83 @@ uint64_t get_Other_Info_to_Byte(Other_Info_Section_Data_Struct *otherdata,uint8_
} }
One_Spectral_Info_Struct Get_spectral_info_from_byte(uint8_t *buffer, size_t length) { One_Spectral_Info_Struct *Get_spectral_info_from_byte(uint8_t *buffer, size_t length,int &spectral_info_number) {
One_Spectral_Info_Struct retstruct; One_Spectral_Info_Struct *retstruct=nullptr;
std::string json_str(reinterpret_cast<char*>(buffer), length-1); std::string json_str(reinterpret_cast<char*>(buffer), length-1);
json j = json::parse(json_str, nullptr, false); json j = json::parse(json_str, nullptr, false);
std::string sensor_id = j["SensorId"].get<std::string>(); //打印json
strcpy(retstruct.SensorId,sensor_id.c_str() ); // std::cout<<"Read JSON string: " << json_str << std::endl;
retstruct.WaveCoeff[0] = j["WaveCoeff"]["a1"].get<double>(); //std::cout << j.dump(4) << std::endl; // 打印JSON对象
retstruct.WaveCoeff[1] = j["WaveCoeff"]["a2"].get<double>(); /* {
retstruct.WaveCoeff[2] = j["WaveCoeff"]["a3"].get<double>(); "info_type": "infolist", // 0 for device info
retstruct.WaveCoeff[3] = j["WaveCoeff"]["a4"].get<double>(); "info_number":3,
"info_list": [
{
"info_type": "devinfo", // 0 for device info
"sensor_id": "is30002",
"bandnum": 2048,
"wave_coeff": {
"a1": 0.0,
"a2": 0.0,
"a3": 400,
"a4": 1.0
}
},
{
"info_type": "environment", // 1 for gain info
"date": "2000-01-00 00:00:00",
//下面可选
"humidity":90.0,
"temperature":35.0 ,
"gps":{
"latitude":115.01,
"longitude": 39.01,
"altitude": 100.0
},
},
{
"info_type": "devinfo", // 0 for device info
"sensor_id": "is20001",
"bandnum": 512,
"wave_coeff": {
"a1": 0,
"a2": 0.0,
"a3":390,
"a4": 4
}
}
]
} */
//如果 info_type 为 infolist 则表示为光谱信息列表 需要一个一个处理
if (!j.is_object() || !j.contains("info_type")) {
spectral_info_number=0;
return nullptr; // 返回空指针表示解析失败
}
if (j["info_type"]=="infolist") {
int info_number = j["info_number"].get<int>();
spectral_info_number= info_number;
retstruct = new One_Spectral_Info_Struct[info_number];
for (int iii=0;iii<info_number;iii++) {
retstruct[iii].Info = j["info_list"][iii];
}
return retstruct;
}
retstruct=new One_Spectral_Info_Struct[1];
retstruct->Info=j;
spectral_info_number=1;
// std::string sensor_id = j["SensorId"].get<std::string>();
// strcpy(retstruct.SensorId,sensor_id.c_str() );
// retstruct.WaveCoeff[0] = j["WaveCoeff"]["a1"].get<double>();
// retstruct.WaveCoeff[1] = j["WaveCoeff"]["a2"].get<double>();
// retstruct.WaveCoeff[2] = j["WaveCoeff"]["a3"].get<double>();
// retstruct.WaveCoeff[3] = j["WaveCoeff"]["a4"].get<double>();
return retstruct; return retstruct;
} }

View File

@ -94,29 +94,69 @@ void IRIS_DATA_example() {
strcpy(tempspectradata3.Name, "IS2_IRIS_Spectral_Data"); // 光谱数据名称 strcpy(tempspectradata3.Name, "IS2_IRIS_Spectral_Data"); // 光谱数据名称
///光谱信息区域构造 ///光谱信息区域构造
mydata.SepctralInfoSection.SectionContent.SepctralInfoNumber = 3; mydata.SepctralInfoSection.SectionContent.SepctralInfoNumber = 1;
mydata.SepctralInfoSection.SectionContent.SepctralInfoAddressList = new One_Spectral_Info_Struct[3]; mydata.SepctralInfoSection.SectionContent.SepctralInfoAddressList = new One_Spectral_Info_Struct[1];
//第一个光谱仪的信息 //第一个光谱仪的信息
One_Spectral_Info_Struct &tempspectralinfo=mydata.SepctralInfoSection.SectionContent.SepctralInfoAddressList[0]; One_Spectral_Info_Struct &tempspectralinfo=mydata.SepctralInfoSection.SectionContent.SepctralInfoAddressList[0];
strcpy(tempspectralinfo.SensorId, "HH3_IRIS"); tempspectralinfo.Info = json::object(); // 初始化为一个空的JSON对象
tempspectralinfo.WaveCoeff[0] = 0.1; tempspectralinfo.Info["info_type"] = "infolist"; // 设置info_type为infolist
tempspectralinfo.WaveCoeff[1] = 0.2; tempspectralinfo.Info["info_number"] = 3; // 设置光谱信息数量
tempspectralinfo.WaveCoeff[2] = 0.3; tempspectralinfo.Info["info_list"] = json::array(); // 初始化为一个空的JSON数组
tempspectralinfo.WaveCoeff[3] = 0.4; // 添加光谱信息到info_list
//第二个光谱仪的信息 tempspectralinfo.Info["info_list"].push_back({
One_Spectral_Info_Struct &tempspectralinfo1=mydata.SepctralInfoSection.SectionContent.SepctralInfoAddressList[1]; {"info_type","devinfo"},
strcpy(tempspectralinfo1.SensorId, "IS3_IRIS"); {"sensor_id", "HH3_IRIS"},
tempspectralinfo1.WaveCoeff[0] = 0.5; {"bandnum", 2000},
tempspectralinfo1.WaveCoeff[1] = 0.6; {"wave_coeff", {
tempspectralinfo1.WaveCoeff[2] = 0.7; {"a1", 0.1},
tempspectralinfo1.WaveCoeff[3] = 0.8; {"a2", 1230.2},
//第三个光谱仪的信息 {"a3", 0.3},
One_Spectral_Info_Struct &tempspectralinfo2=mydata.SepctralInfoSection.SectionContent.SepctralInfoAddressList[2]; {"a4", 0.4}
strcpy(tempspectralinfo2.SensorId, "IS2_IRIS"); }}
tempspectralinfo2.WaveCoeff[0] = 0.9; });
tempspectralinfo2.WaveCoeff[1] = 1.0; tempspectralinfo.Info["info_list"].push_back({
tempspectralinfo2.WaveCoeff[2] = 1.1; {"info_type","devinfo"},
tempspectralinfo2.WaveCoeff[3] = 1.2; {"sensor_id", "IS3_IRIS"},
{"bandnum", 500},
{"wave_coeff", {
{"a1", 0.5},
{"a2", 0.6},
{"a3", 1230.7},
{"a4", 0.8}
}}
});
tempspectralinfo.Info["info_list"].push_back({
{"info_type","devinfo"},
{"sensor_id", "IS2_IRIS"},
{"bandnum", 500},
{"wave_coeff", {
{"a1", 0.9},
{"a2", 1.0},
{"a3", 1.1},
{"a4", 1.2}
}}
});
// //输出info
std::cout << tempspectralinfo.Info.dump(4) << std::endl; // 打印JSON对象
// strcpy(tempspectralinfo.SensorId, "HH3_IRIS");
// tempspectralinfo.WaveCoeff[0] = 0.1;
// tempspectralinfo.WaveCoeff[1] = 0.2;
// tempspectralinfo.WaveCoeff[2] = 0.3;
// tempspectralinfo.WaveCoeff[3] = 0.4;
// //第二个光谱仪的信息
// One_Spectral_Info_Struct &tempspectralinfo1=mydata.SepctralInfoSection.SectionContent.SepctralInfoAddressList[1];
// strcpy(tempspectralinfo1.SensorId, "IS3_IRIS");
// tempspectralinfo1.WaveCoeff[0] = 0.5;
// tempspectralinfo1.WaveCoeff[1] = 0.6;
// tempspectralinfo1.WaveCoeff[2] = 0.7;
// tempspectralinfo1.WaveCoeff[3] = 0.8;
// //第三个光谱仪的信息
// One_Spectral_Info_Struct &tempspectralinfo2=mydata.SepctralInfoSection.SectionContent.SepctralInfoAddressList[2];
// strcpy(tempspectralinfo2.SensorId, "IS2_IRIS");
// tempspectralinfo2.WaveCoeff[0] = 0.9;
// tempspectralinfo2.WaveCoeff[1] = 1.0;
// tempspectralinfo2.WaveCoeff[2] = 1.1;
// tempspectralinfo2.WaveCoeff[3] = 1.2;
///其他信息区域构造 ///其他信息区域构造
@ -138,6 +178,11 @@ void IRIS_DATA_example() {
// 调用写入函数 // 调用写入函数
write_IRIS_DATA_Struct_EMB(&mydata, "iris_data_example.iris", *File_control_ptr); write_IRIS_DATA_Struct_EMB(&mydata, "iris_data_example.iris", *File_control_ptr);
One_IRIS_DATA_Struct mydata2= Get_One_IRIS_DATA_From_File("iris_data_example.iris", *File_control_ptr); One_IRIS_DATA_Struct mydata2= Get_One_IRIS_DATA_From_File("iris_data_example.iris", *File_control_ptr);
int numberofspectralinfo = mydata2.SepctralInfoSection.SectionContent.SepctralInfoNumber;
// for (int iii=0;iii<numberofspectralinfo;iii++) {
// std::cout << mydata2.SepctralInfoSection.SectionContent.SepctralInfoAddressList[iii].Info.dump(4) << std::endl; // 打印JSON对象
// }
// delete [] mydata2.SepctralInfoSection.SectionContent.SepctralInfoAddressList;
Destroy_IRIS_DATA_Struct(mydata2); Destroy_IRIS_DATA_Struct(mydata2);
Destroy_IRIS_DATA_Struct(mydata); Destroy_IRIS_DATA_Struct(mydata);
@ -440,8 +485,10 @@ One_IRIS_DATA_Struct Get_One_IRIS_DATA_From_File(std::string Filepath, MyfileCon
memcpy(&number_of_spectral_info, readbuffer, 2); // 读取光谱信息数量 memcpy(&number_of_spectral_info, readbuffer, 2); // 读取光谱信息数量
spectral_info_content.SepctralInfoNumber= number_of_spectral_info; // 设置光谱信息数量 spectral_info_content.SepctralInfoNumber= number_of_spectral_info; // 设置光谱信息数量
spectral_info_content.SepctralInfoAddressList= new One_Spectral_Info_Struct[number_of_spectral_info]; // 创建光谱信息数组 spectral_info_content.SepctralInfoAddressList= new One_Spectral_Info_Struct[number_of_spectral_info]; // 创建光谱信息数组
int indexofnowinfo=0;
int number_of_spectral_info_real=0; // Initialize the number of spectral info
for (int32_t j=0;j<number_of_spectral_info;j++) { for (int32_t j=0;j<number_of_spectral_info;j++) {
One_Spectral_Info_Struct &one_spectral_info = spectral_info_content.SepctralInfoAddressList[j]; One_Spectral_Info_Struct &one_spectral_info = spectral_info_content.SepctralInfoAddressList[indexofnowinfo];
uint16_t lenth_of_this_spectral_info=0; uint16_t lenth_of_this_spectral_info=0;
uint8_t type_of_spectral_info=0; uint8_t type_of_spectral_info=0;
lenth_in_section+= File_control.Read_data(&readbuffer, 3); // Read the spectral info section lenth_in_section+= File_control.Read_data(&readbuffer, 3); // Read the spectral info section
@ -449,19 +496,66 @@ One_IRIS_DATA_Struct Get_One_IRIS_DATA_From_File(std::string Filepath, MyfileCon
type_of_spectral_info = readbuffer[2]; // 读取光谱信息类型 type_of_spectral_info = readbuffer[2]; // 读取光谱信息类型
lenth_in_section+=File_control.Read_data(&readbuffer, lenth_of_this_spectral_info); // Read the spectral info section lenth_in_section+=File_control.Read_data(&readbuffer, lenth_of_this_spectral_info); // Read the spectral info section
if (type_of_spectral_info == 0x00) { if (type_of_spectral_info == 0x00) {
one_spectral_info= Get_spectral_info_from_byte(readbuffer,lenth_of_this_spectral_info); int specnumber=0;
One_Spectral_Info_Struct *aaa= Get_spectral_info_from_byte(readbuffer,lenth_of_this_spectral_info,specnumber);
if (specnumber==0) {
}else {
if (specnumber==1) {
one_spectral_info=*aaa;
}
if (specnumber>1) {
One_Spectral_Info_Struct *temp_spectral_info=nullptr;
if (indexofnowinfo>0) {
temp_spectral_info=new One_Spectral_Info_Struct[indexofnowinfo];
for (int iii=0;iii<specnumber;iii++) {
temp_spectral_info[iii]=aaa[iii];
}
}
delete [] spectral_info_content.SepctralInfoAddressList; // Free the allocated array
number_of_spectral_info_real=number_of_spectral_info_real+specnumber-1; // Update the number of spectral info
spectral_info_content.SepctralInfoAddressList = new One_Spectral_Info_Struct[number_of_spectral_info_real+1]; // Reallocate the array
//
for (int iii=0;iii<indexofnowinfo;iii++) {
spectral_info_content.SepctralInfoAddressList[iii]=temp_spectral_info[iii];
}
for (int iii=0;iii<specnumber;iii++) {
spectral_info_content.SepctralInfoAddressList[iii+indexofnowinfo]=aaa[iii];
spectral_info_content.SepctralInfoAddressList[iii+indexofnowinfo].Info=aaa[iii].Info;
}
// delete[] spectral_info_content.SepctralInfoAddressList;
indexofnowinfo+=specnumber-1; // Update the index of current info
if (temp_spectral_info!=nullptr) {
delete [] temp_spectral_info; // Free the temporary array
}
}
}
if (aaa!=nullptr) {
delete []aaa;
}
} }
delete [] readbuffer; // 释放之前的读取缓冲区 delete [] readbuffer; // 释放之前的读取缓冲区
readbuffer = nullptr; // 释放后将指针设置为nullptr readbuffer = nullptr; // 释放后将指针设置为nullptr
indexofnowinfo++;
number_of_spectral_info_real++;
} }
spectral_info_content.SepctralInfoNumber= number_of_spectral_info_real;
if (lenth_in_section!= SectionLength) { if (lenth_in_section!= SectionLength) {
// Handle error: not all data was read // Handle error: not all data was read
delete[] spectral_info_content.SepctralInfoAddressList; // Free the allocated array delete[] spectral_info_content.SepctralInfoAddressList; // Free the allocated array
spectral_info_content.SepctralInfoAddressList = nullptr; // Reset the pointer to nullptr spectral_info_content.SepctralInfoAddressList = nullptr; // Reset the pointer to nullptr
return Create_IRIS_DATA_Struct(); // Return an empty struct return Create_IRIS_DATA_Struct(); // Return an empty struct
} }
//delete[] spectral_info_content.SepctralInfoAddressList;
break; break;
} }
case OTHER_SECTION: { case OTHER_SECTION: {
@ -538,7 +632,7 @@ One_IRIS_DATA_Struct Get_One_IRIS_DATA_From_File(std::string Filepath, MyfileCon
} }
File_control.close_file(); // Close the file after reading all sections File_control.close_file(); // Close the file after reading all sections
// delete [] Retrun_Data.SepctralInfoSection.SectionContent.SepctralInfoAddressList;
return Retrun_Data; // Return the populated One_IRIS_DATA_Struct return Retrun_Data; // Return the populated One_IRIS_DATA_Struct
} }
@ -562,10 +656,19 @@ void Destroy_IRIS_DATA_Struct(One_IRIS_DATA_Struct &iris_data) {
if (iris_data.SepctralInfoSection.SectionContent.SepctralInfoNumber !=0) { if (iris_data.SepctralInfoSection.SectionContent.SepctralInfoNumber !=0) {
int16_t numberforclear = iris_data.SepctralInfoSection.SectionContent.SepctralInfoNumber; int16_t numberforclear = iris_data.SepctralInfoSection.SectionContent.SepctralInfoNumber;
for (int16_t i=0;i<numberforclear;i++) { for (int16_t i=0;i<numberforclear;i++) {
//打印info
// std::cout<< "Spectral Info " << i << ": " << std::endl;
// std::cout << iris_data.SepctralInfoSection.SectionContent.SepctralInfoAddressList[i].Info.dump(4) << std::endl; // 打印JSON对象
//清空info
// iris_data.SepctralInfoSection.SectionContent.SepctralInfoAddressList[i].Info.clear(); // 清空info
// No dynamic memory allocation in One_Spectral_Info_Struct, so no need to free anything // No dynamic memory allocation in One_Spectral_Info_Struct, so no need to free anything
} }
if (iris_data.SepctralInfoSection.SectionContent.SepctralInfoAddressList!=nullptr)
delete[] iris_data.SepctralInfoSection.SectionContent.SepctralInfoAddressList; // Free the spectral info address list if (iris_data.SepctralInfoSection.SectionContent.SepctralInfoAddressList!=nullptr) {
delete [] iris_data.SepctralInfoSection.SectionContent.SepctralInfoAddressList; // Free the spectral info address list
}
// Free the spectral info address list
iris_data.SepctralInfoSection.SectionContent.SepctralInfoAddressList = nullptr; // Reset the pointer to nullptr iris_data.SepctralInfoSection.SectionContent.SepctralInfoAddressList = nullptr; // Reset the pointer to nullptr
iris_data.SepctralInfoSection.SectionContent.SepctralInfoNumber=0; iris_data.SepctralInfoSection.SectionContent.SepctralInfoNumber=0;
iris_data.SepctralInfoSection.SectionLength=0; iris_data.SepctralInfoSection.SectionLength=0;

View File

@ -1,10 +1,21 @@
#ifndef IRIS_DEFFINE_H #ifndef IRIS_DEFFINE_H
#define IRIS_DEFFINE_H #define IRIS_DEFFINE_H
#define NOTARM
#ifdef NOTARM
#include"json/json.hpp"
using json = nlohmann::json;
#include "iostream"
#endif
#include <cstdint> // For uint8_t, uint16_t, uint32_t, uint64_t, int8_t #include <cstdint> // For uint8_t, uint16_t, uint32_t, uint64_t, int8_t
#include <stddef.h> // For size_t #include <stddef.h> // For size_t
#include <string> // For std::string #include <string> // For std::string
//结构体内存1字节对齐 //结构体内存1字节对齐
#pragma pack(1) #pragma pack(1)
@ -127,8 +138,7 @@ typedef struct Sepctral_Data_Section_Struct
// 下面结构体应通过转换成json在进行存储 读取时亦然 // 下面结构体应通过转换成json在进行存储 读取时亦然
typedef struct One_Spectral_Info_Struct{ typedef struct One_Spectral_Info_Struct{
char SensorId[50]; // 传感器ID json Info; // 光谱信息内容
double WaveCoeff[4]; // 波长系数
} One_Spectral_Info_Struct; } One_Spectral_Info_Struct;
typedef struct Sepctral_Info_Section_Data_Struct typedef struct Sepctral_Info_Section_Data_Struct
@ -146,7 +156,7 @@ typedef struct Sepctral_Info_Section_Struct
///////////////////////////////// 其他信息结构相关定义 ///////////////////////////////// ///////////////////////////////// 其他信息结构相关定义 /////////////////////////////////
typedef struct One_Other_Info_Struct{ typedef struct One_Other_Info_Struct{
uint8_t Type; // 信息类型; // 数据地址 (pointer to data) json Info; // 信息类型; // 数据地址 (pointer to data)
} One_Other_Info_Struct; } One_Other_Info_Struct;
typedef struct Other_Info_Section_Data_Struct typedef struct Other_Info_Section_Data_Struct
@ -215,6 +225,6 @@ uint64_t get_Sepctral_Info_to_Byte(Sepctral_Info_Section_Data_Struct *sepctralin
uint64_t get_Other_Info_to_Byte(Other_Info_Section_Data_Struct *otherdata,uint8_t **retbuffer); uint64_t get_Other_Info_to_Byte(Other_Info_Section_Data_Struct *otherdata,uint8_t **retbuffer);
One_IRIS_DATA_Struct Get_One_IRIS_DATA_From_File(std::string Filepath, MyfileControl_Struct File_control); One_IRIS_DATA_Struct Get_One_IRIS_DATA_From_File(std::string Filepath, MyfileControl_Struct File_control);
VSDLL_EXPORTS void IRIS_DATA_example(); VSDLL_EXPORTS void IRIS_DATA_example();
One_Spectral_Info_Struct Get_spectral_info_from_byte(uint8_t *buffer, size_t length); One_Spectral_Info_Struct *Get_spectral_info_from_byte(uint8_t *buffer, size_t length,int &spectral_info_number);
void Destroy_IRIS_DATA_Struct(One_IRIS_DATA_Struct &iris_data); void Destroy_IRIS_DATA_Struct(One_IRIS_DATA_Struct &iris_data);
#endif // IRIS_DEFFINE_H #endif // IRIS_DEFFINE_H