psutils: Add new functions to  AEI Updater class

The following functions handle the critical stages of firmware update,
including validation, reading, preparation, and reboot verification.
Error handling and logging are incorporated to isolate issues during the
update.

getFirmwarePath()
Retrieves the firmware file path from the image directory. Uses
getFWFilenamePath to fetch the path. Logs an error if the firmware path
is not found and returns an empty string otherwise returns firmware
path.

isFirmwareFileValid()
Validates the firmware file at the given path using validateFWFile.
Ensure the firmware file exists and meets requirements before proceeding
with the update. Logs an error if validation fails.

openFirmwareFile()
Opens the firmware file at the specified path for reading in binary
mode. Logs an error if the file cannot be opened.

readFirmwareBlock()
Reads a block of data from the firmware file.Uses readFirmwareBytes to
read the specified number of bytes.

prepareCommandBlock()
Prepares a command block for writing firmware data to the PSU. Adds
metadata, data, and a CRC8 checksum. Packages firmware data in a format
suitable for I2C transmission.

ispReboot()
Sends a reboot command to the status register to apply new firmware.

ispReadRebootStatus()
Reads the reboot status from ISP, returns true for success otherwise
false.

Tested:
- Validated that the firmware path retrieves the correct file.
- A validation error is logged when the file is empty or path is
  incorrect.
- Removed read permission on the firmware file and verified that an
  error was logged.
- Verify the block of data read as specified in the specification.
- Printed the command block and verified that the command and data are
  ready to be sent to the PSU via I2C.
- Downloaded the firmware and verified that the command block, ISP
  reboot and reboot status are working as expected.

Change-Id: I097b4aeefc0967d5591b8fb6aefb3c600c9f77f8
Signed-off-by: Faisal Awada <faisal@us.ibm.com>
diff --git a/tools/power-utils/aei_updater.cpp b/tools/power-utils/aei_updater.cpp
index 0567ac9..064258e 100644
--- a/tools/power-utils/aei_updater.cpp
+++ b/tools/power-utils/aei_updater.cpp
@@ -25,13 +25,15 @@
 
 #include <phosphor-logging/lg2.hpp>
 
+#include <fstream>
+
 namespace aeiUpdater
 {
 constexpr uint8_t MAX_RETRIES = 0x02;    // Constants for retry limits
 
 constexpr int ISP_STATUS_DELAY = 1200;   // Delay for ISP status check (1.2s)
 constexpr int MEM_WRITE_DELAY = 5000;    // Memory write delay (5s)
-constexpr int MEM_STRETCH_DELAY = 50;    // Delay between writes (50ms)
+constexpr int MEM_STRETCH_DELAY = 10;    // Delay between writes (10ms)
 constexpr int MEM_COMPLETE_DELAY = 2000; // Delay before completion (2s)
 constexpr int REBOOT_DELAY = 8000;       // Delay for reboot (8s)
 
@@ -70,6 +72,8 @@
 constexpr uint8_t B_ISP_MODE = 0x40;          // ISP mode
 constexpr uint8_t B_ISP_MODE_CHKSUM_GOOD = 0x41; // ISP mode  & good checksum.
 constexpr uint8_t B_PRGM_BUSY = 0x80;            // Write operation in progress.
+constexpr uint8_t SUCCESSFUL_ISP_REBOOT_STATUS = 0x0; // Successful ISP reboot
+                                                      // status
 
 using namespace phosphor::logging;
 namespace util = phosphor::power::util;
@@ -112,7 +116,7 @@
     catch (const std::exception& e)
     {
         // Log failure if I2C write fails.
-        lg2::error("I2C write failed: {ERROR}", "ERROR", e.what());
+        lg2::error("I2C write failed: {ERROR}", "ERROR", e);
         return false;
     }
 }
@@ -141,7 +145,7 @@
         {
             // Log I2C error with each retry attempt.
             lg2::error("I2C error during ISP mode write/read: {ERROR}", "ERROR",
-                       e.what());
+                       e);
         }
     }
     lg2::error("Failed to set ISP Mode");
@@ -172,10 +176,114 @@
     {
         // Log any errors encountered during reset sequence.
         lg2::error("I2C Read/Write error during ISP reset: {ERROR}", "ERROR",
-                   e.what());
+                   e);
     }
     lg2::error("Failed to reset ISP Status");
     return false;
 }
 
+std::string AeiUpdater::getFirmwarePath()
+{
+    const std::string fspath =
+        updater::internal::getFWFilenamePath(getImageDir());
+    if (fspath.empty())
+    {
+        lg2::error("Firmware file path not found");
+    }
+    return fspath;
+}
+
+bool AeiUpdater::isFirmwareFileValid(const std::string& fspath)
+{
+    if (!updater::internal::validateFWFile(fspath))
+    {
+        lg2::error("Firmware validation failed");
+        return false;
+    }
+    return true;
+}
+
+std::unique_ptr<std::ifstream>
+    AeiUpdater::openFirmwareFile(const std::string& fspath)
+{
+    auto inputFile = updater::internal::openFirmwareFile(fspath);
+    if (!inputFile)
+    {
+        lg2::error("Failed to open firmware file");
+    }
+    return inputFile;
+}
+
+std::vector<uint8_t> AeiUpdater::readFirmwareBlock(std::ifstream& file,
+                                                   const size_t& bytesToRead)
+{
+    auto block = updater::internal::readFirmwareBytes(file, bytesToRead);
+    return block;
+}
+
+std::vector<uint8_t>
+    AeiUpdater::prepareCommandBlock(const std::vector<uint8_t>& dataBlockRead)
+{
+    std::vector<uint8_t> cmdBlockWrite = {ISP_MEMORY_REGISTER,
+                                          BLOCK_WRITE_SIZE};
+
+    cmdBlockWrite.insert(cmdBlockWrite.end(), byteSwappedIndex.begin(),
+                         byteSwappedIndex.end());
+    cmdBlockWrite.insert(cmdBlockWrite.end(), dataBlockRead.begin(),
+                         dataBlockRead.end());
+
+    // Resize to ensure it matches BLOCK_WRITE_SIZE + 1 and append CRC
+    if (cmdBlockWrite.size() != BLOCK_WRITE_SIZE + 1)
+    {
+        cmdBlockWrite.resize(BLOCK_WRITE_SIZE + 1, 0xFF);
+    }
+    cmdBlockWrite.push_back(updater::internal::calculateCRC8(cmdBlockWrite));
+    // Remove the F9 and byte count
+    cmdBlockWrite.erase(cmdBlockWrite.begin(), cmdBlockWrite.begin() + 2);
+
+    return cmdBlockWrite;
+}
+
+void AeiUpdater::ispReboot()
+{
+    updater::internal::delay(
+        MEM_COMPLETE_DELAY); // Delay before starting the reboot process
+
+    try
+    {
+        // Write reboot command to the status register
+        i2cInterface->write(STATUS_REGISTER, CMD_BOOT_PWR);
+
+        updater::internal::delay(
+            REBOOT_DELAY); // Add delay after writing reboot command
+    }
+    catch (const std::exception& e)
+    {
+        lg2::error("I2C write error during reboot: {ERROR}", "ERROR", e);
+    }
+}
+
+bool AeiUpdater::ispReadRebootStatus()
+{
+    try
+    {
+        // Read from the status register to verify reboot
+        uint8_t data = 1; // Initialize data to a non-zero value
+        i2cInterface->read(STATUS_REGISTER, data);
+
+        uint8_t status = SUCCESSFUL_ISP_REBOOT_STATUS;
+        // If the reboot was successful, the read data should be 0
+        if (data == status)
+        {
+            lg2::info("ISP Status Reboot successful.");
+            return true;
+        }
+    }
+    catch (const std::exception& e)
+    {
+        lg2::error("I2C read error during reboot attempt: {ERROR}", "ERROR", e);
+    }
+    return false;
+}
+
 } // namespace aeiUpdater
diff --git a/tools/power-utils/aei_updater.hpp b/tools/power-utils/aei_updater.hpp
index 1b872b6..de5ca5c 100644
--- a/tools/power-utils/aei_updater.hpp
+++ b/tools/power-utils/aei_updater.hpp
@@ -53,7 +53,7 @@
     /**
      * @brief Initiates the firmware update process.
      *
-     * @return int Status code 0 for success or 1 for failure.
+     * @return Status code 0 for success or 1 for failure.
      */
     int doUpdate() override;
 
@@ -61,25 +61,82 @@
     /**
      * @brief Writes an ISP (In-System Programming) key to initiate the update.
      *
-     * @return bool True if successful, false otherwise.
+     * @return True if successful, false otherwise.
      */
     bool writeIspKey();
 
     /**
      * @brief Writes the mode required for ISP to start firmware programming.
      *
-     * @return bool True if successful, false otherwise.
+     * @return True if successful, false otherwise.
      */
     bool writeIspMode();
 
     /**
      * @brief Resets the ISP status to prepare for a firmware update.
      *
-     * @return bool True if successful, false otherwise.
+     * @return True if successful, false otherwise.
      */
     bool writeIspStatusReset();
 
     /**
+     * @brief Retrieves the path to the firmware file.
+     *
+     * @return The file path of the firmware.
+     */
+    std::string getFirmwarePath();
+
+    /**
+     * @brief Validates the firmware file.
+     *
+     * @param fspath The file path to validate.
+     * @return True if the file is valid, false otherwise.
+     */
+    bool isFirmwareFileValid(const std::string& fspath);
+
+    /**
+     * @brief Opens a firmware file in binary mode.
+     *
+     * @param fspath The path to the firmware file.
+     * @return A file stream to read the firmware
+     * file.
+     */
+    std::unique_ptr<std::ifstream> openFirmwareFile(const std::string& fspath);
+
+    /**
+     * @brief Reads a block of firmware data from the file.
+     *
+     * @param file The input file stream from which to read data.
+     * @param bytesToRead The number of bytes to read.
+     * @return A vector containing the firmware block.
+     */
+    std::vector<uint8_t> readFirmwareBlock(std::ifstream& file,
+                                           const size_t& bytesToRead);
+
+    /**
+     * @brief Prepares an ISP_MEMORY  command block by processing the firmware
+     * data block.
+     *
+     * @param dataBlockRead The firmware data block read from the file.
+     * @return The prepared command block.
+     */
+    std::vector<uint8_t>
+        prepareCommandBlock(const std::vector<uint8_t>& dataBlockRead);
+
+    /**
+     * @brief Initiates a reboot of the ISP to apply new firmware.
+     */
+    void ispReboot();
+
+    /**
+     * @brief Reads the reboot status from the ISP.
+     *
+     * @return True if the reboot status indicates success, false
+     * otherwise.
+     */
+    bool ispReadRebootStatus();
+
+    /**
      * @brief Pointer to the I2C interface for communication
      *
      * This pointer is not owned by the class. The caller is responsible for