regulators: Implement i2c_write_byte action

Implement the i2c_write_byte action in the JSON config file.  See
i2c_write_byte.md for more information about this action.

Signed-off-by: Shawn McCarney <shawnmm@us.ibm.com>
Change-Id: I37fb9b81ee6d9e7fc226787a3242f389b8903714
diff --git a/phosphor-regulators/src/actions/i2c_write_byte_action.cpp b/phosphor-regulators/src/actions/i2c_write_byte_action.cpp
new file mode 100644
index 0000000..2657178
--- /dev/null
+++ b/phosphor-regulators/src/actions/i2c_write_byte_action.cpp
@@ -0,0 +1,71 @@
+/**
+ * Copyright © 2020 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_write_byte_action.hpp"
+
+#include "action_error.hpp"
+#include "i2c_interface.hpp"
+
+#include <exception>
+#include <ios>
+#include <sstream>
+
+namespace phosphor::power::regulators
+{
+
+bool I2CWriteByteAction::execute(ActionEnvironment& environment)
+{
+    try
+    {
+        i2c::I2CInterface& interface = getI2CInterface(environment);
+        uint8_t valueToWrite;
+        if (mask == 0xFF)
+        {
+            valueToWrite = value;
+        }
+        else
+        {
+            // Read current value of device register
+            uint8_t currentValue{0x00};
+            interface.read(reg, currentValue);
+
+            // Combine value to write with current value
+            valueToWrite = (value & mask) | (currentValue & (~mask));
+        }
+
+        // Write value to device register
+        interface.write(reg, valueToWrite);
+    }
+    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 I2CWriteByteAction::toString() const
+{
+    std::ostringstream ss;
+    ss << "i2c_write_byte: { register: 0x" << std::hex << std::uppercase
+       << static_cast<uint16_t>(reg) << ", value: 0x"
+       << static_cast<uint16_t>(value) << ", mask: 0x"
+       << static_cast<uint16_t>(mask) << " }";
+    return ss.str();
+}
+
+} // namespace phosphor::power::regulators
diff --git a/phosphor-regulators/src/actions/i2c_write_byte_action.hpp b/phosphor-regulators/src/actions/i2c_write_byte_action.hpp
new file mode 100644
index 0000000..99ea154
--- /dev/null
+++ b/phosphor-regulators/src/actions/i2c_write_byte_action.hpp
@@ -0,0 +1,139 @@
+/**
+ * Copyright © 2020 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 <string>
+
+namespace phosphor::power::regulators
+{
+
+/**
+ * @class I2CWriteByteAction
+ *
+ * Writes a byte to a device register.  Communicates with the device directly
+ * using the I2C interface.
+ *
+ * Implements the i2c_write_byte action in the JSON config file.
+ */
+class I2CWriteByteAction : public I2CAction
+{
+  public:
+    // Specify which compiler-generated methods we want
+    I2CWriteByteAction() = delete;
+    I2CWriteByteAction(const I2CWriteByteAction&) = delete;
+    I2CWriteByteAction(I2CWriteByteAction&&) = delete;
+    I2CWriteByteAction& operator=(const I2CWriteByteAction&) = delete;
+    I2CWriteByteAction& operator=(I2CWriteByteAction&&) = delete;
+    virtual ~I2CWriteByteAction() = default;
+
+    /**
+     * Constructor.
+     *
+     * @param reg Device register address.  Note: named 'reg' because 'register'
+     *            is a reserved keyword.
+     * @param value Byte value to write.
+     * @param mask Bit mask.  Specifies which bits to write within the byte
+     *             value.  Only the bits with a value of 1 in the mask will be
+     *             written.
+     */
+    explicit I2CWriteByteAction(uint8_t reg, uint8_t value,
+                                uint8_t mask = 0xFF) :
+        reg{reg},
+        value{value}, mask{mask}
+    {
+    }
+
+    /**
+     * Executes this action.
+     *
+     * Writes a byte to a device register using the I2C interface.
+     *
+     * The device register, byte value, and mask (if any) were specified in the
+     * constructor.
+     *
+     * The device is obtained from the specified action environment.
+     *
+     * Throws an exception if an error occurs.
+     *
+     * @param environment action execution environment
+     * @return true
+     */
+    virtual bool execute(ActionEnvironment& environment) override;
+
+    /**
+     * Returns the device register address.
+     *
+     * @return register address
+     */
+    uint8_t getRegister() const
+    {
+        return reg;
+    }
+
+    /**
+     * Returns the byte value to write.
+     *
+     * @return value to write
+     */
+    uint8_t getValue() const
+    {
+        return value;
+    }
+
+    /**
+     * Returns the bit mask.
+     *
+     * Specifies which bits to write within the byte value.  Only the bits with
+     * a value of 1 in the mask will be written.
+     *
+     * @return bit mask
+     */
+    uint8_t getMask() const
+    {
+        return mask;
+    }
+
+    /**
+     * 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{0x00};
+
+    /**
+     * Byte value to write.
+     */
+    const uint8_t value{0x00};
+
+    /**
+     * Bit mask.  Specifies which bits to write within the byte value.  Only the
+     * bits with a value of 1 in the mask will be written.
+     */
+    const uint8_t mask{0xFF};
+};
+
+} // namespace phosphor::power::regulators
diff --git a/phosphor-regulators/src/meson.build b/phosphor-regulators/src/meson.build
index 2cc8347..b5bb9f4 100644
--- a/phosphor-regulators/src/meson.build
+++ b/phosphor-regulators/src/meson.build
@@ -9,7 +9,8 @@
     'actions/if_action.cpp',
     'actions/i2c_compare_bit_action.cpp',
     'actions/i2c_compare_byte_action.cpp',
-    'actions/i2c_compare_bytes_action.cpp'
+    'actions/i2c_compare_bytes_action.cpp',
+    'actions/i2c_write_byte_action.cpp'
 ]
 
 phosphor_regulators_library = static_library(
diff --git a/phosphor-regulators/test/actions/i2c_write_byte_action_tests.cpp b/phosphor-regulators/test/actions/i2c_write_byte_action_tests.cpp
new file mode 100644
index 0000000..1a858e3
--- /dev/null
+++ b/phosphor-regulators/test/actions/i2c_write_byte_action_tests.cpp
@@ -0,0 +1,278 @@
+/**
+ * Copyright © 2020 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_interface.hpp"
+#include "i2c_write_byte_action.hpp"
+#include "id_map.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::A;
+using ::testing::Return;
+using ::testing::SetArgReferee;
+using ::testing::Throw;
+using ::testing::TypedEq;
+
+TEST(I2CWriteByteActionTests, Constructor)
+{
+    // Test where mask is not specified
+    {
+        I2CWriteByteAction action{0x7C, 0x0A};
+        EXPECT_EQ(action.getRegister(), 0x7C);
+        EXPECT_EQ(action.getValue(), 0x0A);
+        EXPECT_EQ(action.getMask(), 0xFF);
+    }
+
+    // Test where mask is specified
+    {
+        I2CWriteByteAction action{0xA0, 0xD6, 0xC3};
+        EXPECT_EQ(action.getRegister(), 0xA0);
+        EXPECT_EQ(action.getValue(), 0xD6);
+        EXPECT_EQ(action.getMask(), 0xC3);
+    }
+}
+
+TEST(I2CWriteByteActionTests, Execute)
+{
+    // Test where works: Mask not specified
+    try
+    {
+        // Create mock I2CInterface
+        std::unique_ptr<i2c::MockedI2CInterface> i2cInterface =
+            std::make_unique<i2c::MockedI2CInterface>();
+        EXPECT_CALL(*i2cInterface, isOpen).Times(1).WillOnce(Return(true));
+        EXPECT_CALL(*i2cInterface, read(A<uint8_t>(), A<uint8_t&>())).Times(0);
+        EXPECT_CALL(*i2cInterface,
+                    write(TypedEq<uint8_t>(0x7C), TypedEq<uint8_t>(0x0A)))
+            .Times(1);
+
+        // Create Device, IDMap, and ActionEnvironment
+        Device device{"reg1", true, "/system/chassis/motherboard/reg1",
+                      std::move(i2cInterface)};
+        IDMap idMap{};
+        idMap.addDevice(device);
+        ActionEnvironment env{idMap, "reg1"};
+
+        I2CWriteByteAction action{0x7C, 0x0A};
+        EXPECT_EQ(action.execute(env), true);
+    }
+    catch (...)
+    {
+        ADD_FAILURE() << "Should not have caught exception.";
+    }
+
+    // Test where works: Mask specified
+    try
+    {
+        // Create mock I2CInterface: read() returns value 0x69
+        std::unique_ptr<i2c::MockedI2CInterface> i2cInterface =
+            std::make_unique<i2c::MockedI2CInterface>();
+        EXPECT_CALL(*i2cInterface, isOpen).Times(1).WillOnce(Return(true));
+        EXPECT_CALL(*i2cInterface, read(0xA0, A<uint8_t&>()))
+            .Times(1)
+            .WillOnce(SetArgReferee<1>(0x69));
+        EXPECT_CALL(*i2cInterface,
+                    write(TypedEq<uint8_t>(0xA0), TypedEq<uint8_t>(0xEA)))
+            .Times(1);
+
+        // Create Device, IDMap, and ActionEnvironment
+        Device device{"reg1", true, "/system/chassis/motherboard/reg1",
+                      std::move(i2cInterface)};
+        IDMap idMap{};
+        idMap.addDevice(device);
+        ActionEnvironment env{idMap, "reg1"};
+
+        // Value to write       : 0xD6 = 1101 0110
+        // Mask                 : 0xC3 = 1100 0011
+        // Current value        : 0x69 = 0110 1001
+        // Value to write & mask: 0xC2 = 1100 0010
+        // ~Mask                : 0x3C = 0011 1100
+        // Current value & ~mask: 0x28 = 0010 1000
+        // Final value to write : 0xEA = 1110 1010
+        I2CWriteByteAction action{0xA0, 0xD6, 0xC3};
+        EXPECT_EQ(action.execute(env), true);
+    }
+    catch (...)
+    {
+        ADD_FAILURE() << "Should not have caught exception.";
+    }
+
+    // Test where fails: Getting I2CInterface fails
+    try
+    {
+        // Create IDMap and ActionEnvironment
+        IDMap idMap{};
+        ActionEnvironment env{idMap, "reg1"};
+
+        I2CWriteByteAction action{0x7C, 0x0A};
+        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 \"reg1\"");
+    }
+    catch (...)
+    {
+        ADD_FAILURE() << "Should not have caught exception.";
+    }
+
+    // Test where fails: Reading byte 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(0xA0, A<uint8_t&>()))
+            .Times(1)
+            .WillOnce(Throw(
+                i2c::I2CException{"Failed to read byte", "/dev/i2c-1", 0x70}));
+        EXPECT_CALL(*i2cInterface, write(A<uint8_t>(), A<uint8_t>())).Times(0);
+
+        // Create Device, IDMap, and ActionEnvironment
+        Device device{"reg1", true, "/system/chassis/motherboard/reg1",
+                      std::move(i2cInterface)};
+        IDMap idMap{};
+        idMap.addDevice(device);
+        ActionEnvironment env{idMap, "reg1"};
+
+        I2CWriteByteAction action{0xA0, 0xD6, 0xC3};
+        action.execute(env);
+        ADD_FAILURE() << "Should not have reached this line.";
+    }
+    catch (const ActionError& e)
+    {
+        EXPECT_STREQ(e.what(), "ActionError: i2c_write_byte: { register: "
+                               "0xA0, value: 0xD6, mask: 0xC3 }");
+        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 byte: bus /dev/i2c-1, addr 0x70");
+        }
+        catch (...)
+        {
+            ADD_FAILURE() << "Should not have caught exception.";
+        }
+    }
+    catch (...)
+    {
+        ADD_FAILURE() << "Should not have caught exception.";
+    }
+
+    // Test where fails: Writing byte fails
+    try
+    {
+        // Create mock I2CInterface: write() 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(A<uint8_t>(), A<uint8_t&>())).Times(0);
+        EXPECT_CALL(*i2cInterface,
+                    write(TypedEq<uint8_t>(0x7C), TypedEq<uint8_t>(0x1A)))
+            .Times(1)
+            .WillOnce(Throw(
+                i2c::I2CException{"Failed to write byte", "/dev/i2c-1", 0x70}));
+
+        // Create Device, IDMap, and ActionEnvironment
+        Device device{"reg1", true, "/system/chassis/motherboard/reg1",
+                      std::move(i2cInterface)};
+        IDMap idMap{};
+        idMap.addDevice(device);
+        ActionEnvironment env{idMap, "reg1"};
+
+        I2CWriteByteAction action{0x7C, 0x1A};
+        action.execute(env);
+        ADD_FAILURE() << "Should not have reached this line.";
+    }
+    catch (const ActionError& e)
+    {
+        EXPECT_STREQ(e.what(), "ActionError: i2c_write_byte: { register: "
+                               "0x7C, value: 0x1A, mask: 0xFF }");
+        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 write byte: bus "
+                                    "/dev/i2c-1, addr 0x70");
+        }
+        catch (...)
+        {
+            ADD_FAILURE() << "Should not have caught exception.";
+        }
+    }
+    catch (...)
+    {
+        ADD_FAILURE() << "Should not have caught exception.";
+    }
+}
+
+TEST(I2CWriteByteActionTests, GetRegister)
+{
+    I2CWriteByteAction action{0x7C, 0xDE};
+    EXPECT_EQ(action.getRegister(), 0x7C);
+}
+
+TEST(I2CWriteByteActionTests, GetValue)
+{
+    I2CWriteByteAction action{0xA0, 0x03, 0x47};
+    EXPECT_EQ(action.getValue(), 0x03);
+}
+
+TEST(I2CWriteByteActionTests, GetMask)
+{
+    // Test where mask is not specified
+    {
+        I2CWriteByteAction action{0x7C, 0xDE};
+        EXPECT_EQ(action.getMask(), 0xFF);
+    }
+
+    // Test where mask is specified
+    {
+        I2CWriteByteAction action{0xA0, 0x03, 0x47};
+        EXPECT_EQ(action.getMask(), 0x47);
+    }
+}
+
+TEST(I2CWriteByteActionTests, ToString)
+{
+    I2CWriteByteAction action{0x7C, 0xDE, 0xFB};
+    EXPECT_EQ(action.toString(),
+              "i2c_write_byte: { register: 0x7C, value: 0xDE, mask: 0xFB }");
+}
diff --git a/phosphor-regulators/test/meson.build b/phosphor-regulators/test/meson.build
index 9e2b5bc..f6a351c 100644
--- a/phosphor-regulators/test/meson.build
+++ b/phosphor-regulators/test/meson.build
@@ -17,6 +17,7 @@
     'actions/i2c_compare_bit_action_tests.cpp',
     'actions/i2c_compare_byte_action_tests.cpp',
     'actions/i2c_compare_bytes_action_tests.cpp',
+    'actions/i2c_write_byte_action_tests.cpp',
     'actions/if_action_tests.cpp',
     'actions/not_action_tests.cpp',
     'actions/or_action_tests.cpp',