regulators: Implement i2c_capture_bytes action

Implement the new i2c_capture_bytes action in the JSON configuration
file.

Create gtests to test the new class.

Signed-off-by: Shawn McCarney <shawnmm@us.ibm.com>
Change-Id: Ie43e147a0a076090729871140bb5889c74323d19
diff --git a/phosphor-regulators/src/actions/i2c_capture_bytes_action.cpp b/phosphor-regulators/src/actions/i2c_capture_bytes_action.cpp
new file mode 100644
index 0000000..728daeb
--- /dev/null
+++ b/phosphor-regulators/src/actions/i2c_capture_bytes_action.cpp
@@ -0,0 +1,78 @@
+/**
+ * Copyright © 2021 IBM Corporation
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include "i2c_capture_bytes_action.hpp"
+
+#include "action_error.hpp"
+#include "i2c_interface.hpp"
+
+#include <exception>
+#include <ios>
+#include <sstream>
+
+namespace phosphor::power::regulators
+{
+
+bool I2CCaptureBytesAction::execute(ActionEnvironment& environment)
+{
+    try
+    {
+        // Read device register values.  Use I2C mode where the number of bytes
+        // to read is explicitly specified.
+        i2c::I2CInterface& interface = getI2CInterface(environment);
+        uint8_t size{count}; // byte count parameter is input/output
+        uint8_t values[UINT8_MAX];
+        interface.read(reg, size, values, i2c::I2CInterface::Mode::I2C);
+
+        // Build additional error data key
+        std::ostringstream kss;
+        kss << environment.getDeviceID() << "_register_0x" << std::hex
+            << std::uppercase << static_cast<uint16_t>(reg);
+        std::string key = kss.str();
+
+        // Build additional error data value
+        std::ostringstream vss;
+        vss << "[ " << std::hex << std::uppercase;
+        for (unsigned int i = 0; i < count; ++i)
+        {
+            vss << ((i > 0) ? ", " : "") << "0x"
+                << static_cast<uint16_t>(values[i]);
+        }
+        vss << " ]";
+        std::string value = vss.str();
+
+        // Store additional error data in action environment
+        environment.addAdditionalErrorData(key, value);
+    }
+    catch (const i2c::I2CException& e)
+    {
+        // Nest I2CException within an ActionError so caller will have both the
+        // low level I2C error information and the action information
+        std::throw_with_nested(ActionError(*this));
+    }
+    return true;
+}
+
+std::string I2CCaptureBytesAction::toString() const
+{
+    std::ostringstream ss;
+    ss << "i2c_capture_bytes: { register: 0x" << std::hex << std::uppercase
+       << static_cast<uint16_t>(reg) << ", count: " << std::dec
+       << static_cast<uint16_t>(count) << " }";
+    return ss.str();
+}
+
+} // namespace phosphor::power::regulators
diff --git a/phosphor-regulators/src/actions/i2c_capture_bytes_action.hpp b/phosphor-regulators/src/actions/i2c_capture_bytes_action.hpp
new file mode 100644
index 0000000..c17e191
--- /dev/null
+++ b/phosphor-regulators/src/actions/i2c_capture_bytes_action.hpp
@@ -0,0 +1,125 @@
+/**
+ * Copyright © 2021 IBM Corporation
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+#pragma once
+
+#include "action_environment.hpp"
+#include "i2c_action.hpp"
+
+#include <cstdint>
+#include <stdexcept>
+#include <string>
+
+namespace phosphor::power::regulators
+{
+
+/**
+ * @class I2CCaptureBytesAction
+ *
+ * Captures device register bytes to be stored in an error log.  Communicates
+ * with the device directly using the I2C interface.
+ *
+ * Implements the i2c_capture_bytes action in the JSON config file.
+ */
+class I2CCaptureBytesAction : public I2CAction
+{
+  public:
+    // Specify which compiler-generated methods we want
+    I2CCaptureBytesAction() = delete;
+    I2CCaptureBytesAction(const I2CCaptureBytesAction&) = delete;
+    I2CCaptureBytesAction(I2CCaptureBytesAction&&) = delete;
+    I2CCaptureBytesAction& operator=(const I2CCaptureBytesAction&) = delete;
+    I2CCaptureBytesAction& operator=(I2CCaptureBytesAction&&) = delete;
+    virtual ~I2CCaptureBytesAction() = default;
+
+    /**
+     * Constructor.
+     *
+     * Throws an exception if any of the input parameters are invalid.
+     *
+     * @param reg Device register address.  Note: named 'reg' because 'register'
+     *            is a reserved keyword.
+     * @param count Number of bytes to read from the device register.
+     */
+    explicit I2CCaptureBytesAction(uint8_t reg, uint8_t count) :
+        reg{reg}, count{count}
+    {
+        if (count < 1)
+        {
+            throw std::invalid_argument{"Invalid byte count: Less than 1"};
+        }
+    }
+
+    /**
+     * Executes this action.
+     *
+     * Reads one or more bytes from a device register using the I2C interface.
+     * The resulting values are stored as additional error data in the specified
+     * action environment.
+     *
+     * All of the bytes will be read in a single I2C operation.
+     *
+     * The device register was specified in the constructor.
+     *
+     * The device is obtained from the action environment.
+     *
+     * Throws an exception if an error occurs.
+     *
+     * @param environment action execution environment
+     * @return true
+     */
+    virtual bool execute(ActionEnvironment& environment) override;
+
+    /**
+     * Returns the number of bytes to read from the device register.
+     *
+     * @return byte count
+     */
+    uint8_t getCount() const
+    {
+        return count;
+    }
+
+    /**
+     * Returns the device register address.
+     *
+     * @return register address
+     */
+    uint8_t getRegister() const
+    {
+        return reg;
+    }
+
+    /**
+     * Returns a string description of this action.
+     *
+     * @return description of action
+     */
+    virtual std::string toString() const override;
+
+  private:
+    /**
+     * Device register address.  Note: named 'reg' because 'register' is a
+     * reserved keyword.
+     */
+    const uint8_t reg;
+
+    /**
+     * Number of bytes to read from the device register.
+     */
+    const uint8_t count;
+};
+
+} // namespace phosphor::power::regulators
diff --git a/phosphor-regulators/src/meson.build b/phosphor-regulators/src/meson.build
index 9c289ae..d9ba765 100644
--- a/phosphor-regulators/src/meson.build
+++ b/phosphor-regulators/src/meson.build
@@ -29,6 +29,7 @@
     'actions/compare_presence_action.cpp',
     'actions/compare_vpd_action.cpp',
     'actions/if_action.cpp',
+    'actions/i2c_capture_bytes_action.cpp',
     'actions/i2c_compare_bit_action.cpp',
     'actions/i2c_compare_byte_action.cpp',
     'actions/i2c_compare_bytes_action.cpp',
diff --git a/phosphor-regulators/test/actions/i2c_capture_bytes_action_tests.cpp b/phosphor-regulators/test/actions/i2c_capture_bytes_action_tests.cpp
new file mode 100644
index 0000000..f806a09
--- /dev/null
+++ b/phosphor-regulators/test/actions/i2c_capture_bytes_action_tests.cpp
@@ -0,0 +1,235 @@
+/**
+ * Copyright © 2021 IBM Corporation
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+#include "action_environment.hpp"
+#include "action_error.hpp"
+#include "device.hpp"
+#include "i2c_capture_bytes_action.hpp"
+#include "i2c_interface.hpp"
+#include "id_map.hpp"
+#include "mock_services.hpp"
+#include "mocked_i2c_interface.hpp"
+
+#include <cstdint>
+#include <memory>
+#include <stdexcept>
+#include <string>
+#include <utility>
+
+#include <gmock/gmock.h>
+#include <gtest/gtest.h>
+
+using namespace phosphor::power::regulators;
+
+using ::testing::NotNull;
+using ::testing::Return;
+using ::testing::SetArrayArgument;
+using ::testing::Throw;
+using ::testing::TypedEq;
+
+TEST(I2CCaptureBytesActionTests, Constructor)
+{
+    // Test where works
+    try
+    {
+        I2CCaptureBytesAction action{0x2A, 2};
+        EXPECT_EQ(action.getRegister(), 0x2A);
+        EXPECT_EQ(action.getCount(), 2);
+    }
+    catch (...)
+    {
+        ADD_FAILURE() << "Should not have caught exception.";
+    }
+
+    // Test where fails: Count < 1
+    try
+    {
+        I2CCaptureBytesAction action{0x2A, 0};
+        ADD_FAILURE() << "Should not have reached this line.";
+    }
+    catch (const std::invalid_argument& e)
+    {
+        EXPECT_STREQ(e.what(), "Invalid byte count: Less than 1");
+    }
+    catch (...)
+    {
+        ADD_FAILURE() << "Should not have caught exception.";
+    }
+}
+
+TEST(I2CCaptureBytesActionTests, Execute)
+{
+    // Test where works: One byte captured
+    try
+    {
+        // Create mock I2CInterface: read() returns value 0xD7
+        std::unique_ptr<i2c::MockedI2CInterface> i2cInterface =
+            std::make_unique<i2c::MockedI2CInterface>();
+        uint8_t values[] = {0xD7};
+        EXPECT_CALL(*i2cInterface, isOpen).Times(1).WillOnce(Return(true));
+        EXPECT_CALL(*i2cInterface, read(0xA0, TypedEq<uint8_t&>(1), NotNull(),
+                                        i2c::I2CInterface::Mode::I2C))
+            .Times(1)
+            .WillOnce(SetArrayArgument<2>(values, values + 1));
+
+        // Create Device, IDMap, MockServices, and ActionEnvironment
+        Device device{
+            "vdd1", true,
+            "/xyz/openbmc_project/inventory/system/chassis/motherboard/vdd1",
+            std::move(i2cInterface)};
+        IDMap idMap{};
+        idMap.addDevice(device);
+        MockServices services{};
+        ActionEnvironment env{idMap, "vdd1", services};
+
+        I2CCaptureBytesAction action{0xA0, 1};
+        EXPECT_EQ(action.execute(env), true);
+        EXPECT_EQ(env.getAdditionalErrorData().size(), 1);
+        EXPECT_EQ(env.getAdditionalErrorData().at("vdd1_register_0xA0"),
+                  "[ 0xD7 ]");
+    }
+    catch (...)
+    {
+        ADD_FAILURE() << "Should not have caught exception.";
+    }
+
+    // Test where works: Multiple bytes captured
+    try
+    {
+        // Create mock I2CInterface: read() returns values 0x56, 0x14, 0xDA
+        std::unique_ptr<i2c::MockedI2CInterface> i2cInterface =
+            std::make_unique<i2c::MockedI2CInterface>();
+        uint8_t values[] = {0x56, 0x14, 0xDA};
+        EXPECT_CALL(*i2cInterface, isOpen).Times(1).WillOnce(Return(true));
+        EXPECT_CALL(*i2cInterface, read(0x7C, TypedEq<uint8_t&>(3), NotNull(),
+                                        i2c::I2CInterface::Mode::I2C))
+            .Times(1)
+            .WillOnce(SetArrayArgument<2>(values, values + 3));
+
+        // Create Device, IDMap, MockServices, and ActionEnvironment
+        Device device{
+            "vdd1", true,
+            "/xyz/openbmc_project/inventory/system/chassis/motherboard/vdd1",
+            std::move(i2cInterface)};
+        IDMap idMap{};
+        idMap.addDevice(device);
+        MockServices services{};
+        ActionEnvironment env{idMap, "vdd1", services};
+
+        I2CCaptureBytesAction action{0x7C, 3};
+        EXPECT_EQ(action.execute(env), true);
+        EXPECT_EQ(env.getAdditionalErrorData().size(), 1);
+        EXPECT_EQ(env.getAdditionalErrorData().at("vdd1_register_0x7C"),
+                  "[ 0x56, 0x14, 0xDA ]");
+    }
+    catch (...)
+    {
+        ADD_FAILURE() << "Should not have caught exception.";
+    }
+
+    // Test where fails: Getting I2CInterface fails
+    try
+    {
+        // Create IDMap, MockServices, and ActionEnvironment
+        IDMap idMap{};
+        MockServices services{};
+        ActionEnvironment env{idMap, "vdd1", services};
+
+        I2CCaptureBytesAction action{0x7C, 2};
+        action.execute(env);
+        ADD_FAILURE() << "Should not have reached this line.";
+    }
+    catch (const std::invalid_argument& e)
+    {
+        EXPECT_STREQ(e.what(), "Unable to find device with ID \"vdd1\"");
+    }
+    catch (...)
+    {
+        ADD_FAILURE() << "Should not have caught exception.";
+    }
+
+    // Test where fails: Reading bytes fails
+    try
+    {
+        // Create mock I2CInterface: read() throws an I2CException
+        std::unique_ptr<i2c::MockedI2CInterface> i2cInterface =
+            std::make_unique<i2c::MockedI2CInterface>();
+        EXPECT_CALL(*i2cInterface, isOpen).Times(1).WillOnce(Return(true));
+        EXPECT_CALL(*i2cInterface, read(0x7C, TypedEq<uint8_t&>(2), NotNull(),
+                                        i2c::I2CInterface::Mode::I2C))
+            .Times(1)
+            .WillOnce(Throw(i2c::I2CException{"Failed to read i2c block data",
+                                              "/dev/i2c-1", 0x70}));
+
+        // Create Device, IDMap, MockServices, and ActionEnvironment
+        Device device{
+            "vdd1", true,
+            "/xyz/openbmc_project/inventory/system/chassis/motherboard/vdd1",
+            std::move(i2cInterface)};
+        IDMap idMap{};
+        idMap.addDevice(device);
+        MockServices services{};
+        ActionEnvironment env{idMap, "vdd1", services};
+
+        I2CCaptureBytesAction action{0x7C, 2};
+        action.execute(env);
+        ADD_FAILURE() << "Should not have reached this line.";
+    }
+    catch (const ActionError& e)
+    {
+        EXPECT_STREQ(
+            e.what(),
+            "ActionError: i2c_capture_bytes: { register: 0x7C, count: 2 }");
+        try
+        {
+            // Re-throw inner I2CException
+            std::rethrow_if_nested(e);
+            ADD_FAILURE() << "Should not have reached this line.";
+        }
+        catch (const i2c::I2CException& ie)
+        {
+            EXPECT_STREQ(ie.what(),
+                         "I2CException: Failed to read i2c block data: bus "
+                         "/dev/i2c-1, addr 0x70");
+        }
+        catch (...)
+        {
+            ADD_FAILURE() << "Should not have caught exception.";
+        }
+    }
+    catch (...)
+    {
+        ADD_FAILURE() << "Should not have caught exception.";
+    }
+}
+
+TEST(I2CCaptureBytesActionTests, GetCount)
+{
+    I2CCaptureBytesAction action{0xA0, 3};
+    EXPECT_EQ(action.getCount(), 3);
+}
+
+TEST(I2CCaptureBytesActionTests, GetRegister)
+{
+    I2CCaptureBytesAction action{0xA0, 3};
+    EXPECT_EQ(action.getRegister(), 0xA0);
+}
+
+TEST(I2CCaptureBytesActionTests, ToString)
+{
+    I2CCaptureBytesAction action{0xA0, 3};
+    EXPECT_EQ(action.toString(),
+              "i2c_capture_bytes: { register: 0xA0, count: 3 }");
+}
diff --git a/phosphor-regulators/test/meson.build b/phosphor-regulators/test/meson.build
index 57200a4..f036dbb 100644
--- a/phosphor-regulators/test/meson.build
+++ b/phosphor-regulators/test/meson.build
@@ -33,6 +33,7 @@
     'actions/compare_presence_action_tests.cpp',
     'actions/compare_vpd_action_tests.cpp',
     'actions/i2c_action_tests.cpp',
+    'actions/i2c_capture_bytes_action_tests.cpp',
     'actions/i2c_compare_bit_action_tests.cpp',
     'actions/i2c_compare_byte_action_tests.cpp',
     'actions/i2c_compare_bytes_action_tests.cpp',