use deku::{deku_derive, DekuContainerRead, DekuError, DekuReader}; use std::{ffi::CString, fmt, path::Path, ptr}; use thiserror::Error; use crate::{ bindings::{SSV_InitLIB2, SSV_LireConfig, SSV_TermLIB}, types::{common::read_from_buffer, configuration::Configuration}, }; use num_enum::FromPrimitive; #[derive(Error, Debug)] pub struct SesamVitaleError { code: u16, } #[derive(Debug, Eq, PartialEq, FromPrimitive)] #[repr(u16)] enum SSVIntError { CPSNotInserted = 61441, #[num_enum(catch_all)] NotImplemented(u16), } #[cfg(test)] mod tests { use super::*; #[test] fn test_sesam_vitale_error() { let int_error = SSVIntError::from(61441); assert_eq!(int_error, SSVIntError::CPSNotInserted); let int_error = SSVIntError::from(123); assert_eq!(int_error, SSVIntError::NotImplemented(123)); println!("{:?}", int_error); } } #[derive(Error, Debug)] enum SSVError { #[error("Erreur standard de la librairie SSV")] SSVStandard, // #[error("Erreur de parsing")] // Parsing(#[from] ParsingError), #[error("Erreur inattendue de la librairie SSV (TMP)")] SSVUnknownTmp, } impl fmt::Display for SesamVitaleError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "Got error code {} from SSV_LireConfig", self.code) } } pub fn init_library(sesam_ini_path: &Path) -> Result<(), SesamVitaleError> { // TODO: better error handling let path_str = sesam_ini_path.to_str().unwrap(); let path_ptr = CString::new(path_str).expect("failed to create cstring"); let exit_code: u16 = unsafe { SSV_InitLIB2(path_ptr.as_ptr()) }; if exit_code != 0 { let error = SesamVitaleError { code: exit_code }; return Err(error); }; Ok(()) } pub fn close_library() -> Result<(), SesamVitaleError> { let exit_code: u16 = unsafe { SSV_TermLIB() }; if exit_code != 0 { let error = SesamVitaleError { code: exit_code }; return Err(error); }; Ok(()) } pub fn read_config() -> Result { let mut buffer_ptr: *mut libc::c_void = ptr::null_mut(); let mut size: libc::size_t = 0; let buffer_ptr_ptr: *mut *mut libc::c_void = &mut buffer_ptr; let size_ptr: *mut libc::size_t = &mut size; // Need to add proper error handling -> return a result with error code pointing to an error // enum let exit_code: u16 = unsafe { SSV_LireConfig(buffer_ptr_ptr, size_ptr) }; if exit_code != 0 { let error = SesamVitaleError { code: exit_code }; return Err(error); }; let buffer: &[u8] = unsafe { std::slice::from_raw_parts(buffer_ptr as *const u8, size) }; // TODO: Improve error handling let configuration: Configuration = read_from_buffer(buffer).unwrap(); // TODO: Call library function for memory delocating unsafe { libc::free(buffer_ptr) }; Ok(configuration) }