Line data Source code
1 : // Copyright 2024 Accenture. 2 : 3 : #include "eeprom/EepromDriver.h" 4 : 5 : #include "bsp/Bsp.h" 6 : 7 : #include <sys/stat.h> 8 : 9 : #include <cstring> 10 : #include <fcntl.h> 11 : #include <unistd.h> 12 : 13 : namespace eeprom 14 : { 15 : 16 6 : bsp::BspReturnCode EepromDriver::init() 17 : { 18 6 : bool success = true; 19 6 : eepromFd = open(eepromFilePath.c_str(), O_RDWR | O_CREAT | O_EXCL, 0666); 20 6 : if (eepromFd != -1) 21 : { 22 1 : success = (chmod(eepromFilePath.c_str(), 0666) != -1) 23 1 : && (ftruncate(eepromFd, EEPROM_SIZE) != -1); 24 : 25 1 : if (success) 26 : { 27 : // Initialize file with 0xFF 28 1 : uint8_t buffer[EEPROM_SIZE]; 29 1 : memset(buffer, 0xFF, EEPROM_SIZE); 30 1 : ssize_t const written = ::write(eepromFd, buffer, EEPROM_SIZE); 31 1 : success = ((EEPROM_SIZE == written) && (fsync(eepromFd) == 0)); 32 : } 33 : 34 1 : if (!success) 35 : { 36 0 : close(eepromFd); 37 0 : eepromFd = -1; 38 : } 39 : } 40 5 : else if (EEXIST == errno) 41 : { 42 : // File already exists: open it without O_EXCL 43 5 : eepromFd = open(eepromFilePath.c_str(), O_RDWR); 44 5 : success = (-1 != eepromFd); 45 : } 46 : else 47 : { 48 : success = false; 49 : } 50 : 51 6 : if (!success) 52 : { 53 0 : return ::bsp::BSP_ERROR; 54 : } 55 : return ::bsp::BSP_OK; 56 : } 57 : 58 : bsp::BspReturnCode 59 5 : EepromDriver::write(uint32_t const address, uint8_t const* const buffer, uint32_t const length) 60 : { 61 8 : bool success 62 5 : = ((-1 != eepromFd) && (address < EEPROM_SIZE) && (length <= (EEPROM_SIZE - address))); 63 : 64 3 : success = (success && (lseek(eepromFd, address, SEEK_SET) != -1)); 65 3 : success = (success && (::write(eepromFd, buffer, length) == length)); 66 2 : success = (success && (fsync(eepromFd) == 0)); 67 : 68 3 : if (!success) 69 : { 70 3 : printf("Failed to write to EEPROM file\r\n"); 71 3 : return ::bsp::BSP_ERROR; 72 : } 73 : return ::bsp::BSP_OK; 74 : } 75 : 76 : bsp::BspReturnCode 77 5 : EepromDriver::read(uint32_t const address, uint8_t* const buffer, uint32_t const length) 78 : { 79 8 : bool success 80 5 : = ((-1 != eepromFd) && (address < EEPROM_SIZE) && (length <= (EEPROM_SIZE - address))); 81 : 82 3 : success = (success && (lseek(eepromFd, address, SEEK_SET) != -1)); 83 6 : success = (success && (::read(eepromFd, buffer, length) == length)); 84 : 85 3 : if (!success) 86 : { 87 3 : printf("Failed to read from EEPROM file\r\n"); 88 3 : return ::bsp::BSP_ERROR; 89 : } 90 : return ::bsp::BSP_OK; 91 : } 92 : 93 : } // namespace eeprom