regulators: Implement i2c_write_bit action

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

Signed-off-by: Shawn McCarney <shawnmm@us.ibm.com>
Change-Id: I3e056580da98ab89a13667077cb87cbd063630c9
diff --git a/phosphor-regulators/src/actions/i2c_write_bit_action.cpp b/phosphor-regulators/src/actions/i2c_write_bit_action.cpp
new file mode 100644
index 0000000..ee146ac
--- /dev/null
+++ b/phosphor-regulators/src/actions/i2c_write_bit_action.cpp
@@ -0,0 +1,72 @@
+/**
+ * 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_bit_action.hpp"
+
+#include "action_error.hpp"
+#include "i2c_interface.hpp"
+
+#include <exception>
+#include <ios>
+#include <sstream>
+
+namespace phosphor::power::regulators
+{
+
+bool I2CWriteBitAction::execute(ActionEnvironment& environment)
+{
+    try
+    {
+        // Read value of device register
+        uint8_t registerValue{0x00};
+        i2c::I2CInterface& interface = getI2CInterface(environment);
+        interface.read(reg, registerValue);
+
+        // Write bit to register value
+        if (value == 0)
+        {
+            // Clear bit within register value
+            registerValue &= ~(0x01 << position);
+        }
+        else
+        {
+            // Set bit within register value
+            registerValue |= (0x01 << position);
+        }
+
+        // Write modified value to device register
+        interface.write(reg, registerValue);
+    }
+    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 I2CWriteBitAction::toString() const
+{
+    std::ostringstream ss;
+    ss << "i2c_write_bit: { register: 0x" << std::hex << std::uppercase
+       << static_cast<uint16_t>(reg) << ", position: " << std::dec
+       << static_cast<uint16_t>(position)
+       << ", value: " << static_cast<uint16_t>(value) << " }";
+    return ss.str();
+}
+
+} // namespace phosphor::power::regulators
diff --git a/phosphor-regulators/src/actions/i2c_write_bit_action.hpp b/phosphor-regulators/src/actions/i2c_write_bit_action.hpp
new file mode 100644
index 0000000..dea4ba7
--- /dev/null
+++ b/phosphor-regulators/src/actions/i2c_write_bit_action.hpp
@@ -0,0 +1,153 @@
+/**
+ * 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 <stdexcept>
+#include <string>
+
+namespace phosphor::power::regulators
+{
+
+/**
+ * @class I2CWriteBitAction
+ *
+ * Writes a bit to a device register.  Communicates with the device directly
+ * using the I2C interface.
+ *
+ * Implements the i2c_write_bit action in the JSON config file.
+ */
+class I2CWriteBitAction : public I2CAction
+{
+  public:
+    // Specify which compiler-generated methods we want
+    I2CWriteBitAction() = delete;
+    I2CWriteBitAction(const I2CWriteBitAction&) = delete;
+    I2CWriteBitAction(I2CWriteBitAction&&) = delete;
+    I2CWriteBitAction& operator=(const I2CWriteBitAction&) = delete;
+    I2CWriteBitAction& operator=(I2CWriteBitAction&&) = delete;
+    virtual ~I2CWriteBitAction() = 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 position Bit position.  Must be in the range 0-7.  Bit 0 is the
+     *                 least significant bit.
+     * @param value Bit value to write.  Must be 0 or 1.
+     */
+    explicit I2CWriteBitAction(uint8_t reg, uint8_t position, uint8_t value) :
+        reg{reg}, position{position}, value{value}
+    {
+        if (position > 7)
+        {
+            throw std::invalid_argument{
+                "Invalid bit position: " +
+                std::to_string(static_cast<unsigned>(position))};
+        }
+
+        if (value > 1)
+        {
+            throw std::invalid_argument{
+                "Invalid bit value: " +
+                std::to_string(static_cast<unsigned>(value))};
+        }
+    }
+
+    /**
+     * Executes this action.
+     *
+     * Writes a bit to a device register using the I2C interface.
+     *
+     * The device register, bit position, and bit value 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 bit position.
+     *
+     * Value is in the range 0-7.  Bit 0 is the least significant bit.
+     *
+     * @return bit position
+     */
+    uint8_t getPosition() const
+    {
+        return position;
+    }
+
+    /**
+     * Returns the bit value to write.
+     *
+     * Value is 0 or 1.
+     *
+     * @return bit value
+     */
+    uint8_t getValue() const
+    {
+        return value;
+    }
+
+    /**
+     * 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};
+
+    /**
+     * Bit position.  Must be in the range 0-7.  Bit 0 is the least significant
+     * bit.
+     */
+    const uint8_t position{0};
+
+    /**
+     * Bit value to write.  Must be 0 or 1.
+     */
+    const uint8_t value{0};
+};
+
+} // namespace phosphor::power::regulators
diff --git a/phosphor-regulators/src/meson.build b/phosphor-regulators/src/meson.build
index 556c65b..d9734c3 100644
--- a/phosphor-regulators/src/meson.build
+++ b/phosphor-regulators/src/meson.build
@@ -10,6 +10,7 @@
     'actions/i2c_compare_bit_action.cpp',
     'actions/i2c_compare_byte_action.cpp',
     'actions/i2c_compare_bytes_action.cpp',
+    'actions/i2c_write_bit_action.cpp',
     'actions/i2c_write_byte_action.cpp',
     'actions/i2c_write_bytes_action.cpp'
 ]
diff --git a/phosphor-regulators/test/actions/i2c_write_bit_action_tests.cpp b/phosphor-regulators/test/actions/i2c_write_bit_action_tests.cpp
new file mode 100644
index 0000000..cefc948
--- /dev/null
+++ b/phosphor-regulators/test/actions/i2c_write_bit_action_tests.cpp
@@ -0,0 +1,303 @@
+/**
+ * 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_bit_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(I2CWriteBitActionTests, Constructor)
+{
+    // Test where works
+    try
+    {
+        I2CWriteBitAction action{0x7C, 2, 0};
+        EXPECT_EQ(action.getRegister(), 0x7C);
+        EXPECT_EQ(action.getPosition(), 2);
+        EXPECT_EQ(action.getValue(), 0);
+    }
+    catch (...)
+    {
+        ADD_FAILURE() << "Should not have caught exception.";
+    }
+
+    // Test where fails: Invalid bit position > 7
+    try
+    {
+        I2CWriteBitAction action{0x7C, 8, 0};
+        ADD_FAILURE() << "Should not have reached this line.";
+    }
+    catch (const std::invalid_argument& e)
+    {
+        EXPECT_STREQ(e.what(), "Invalid bit position: 8");
+    }
+    catch (...)
+    {
+        ADD_FAILURE() << "Should not have caught exception.";
+    }
+
+    // Test where fails: Invalid bit value > 1
+    try
+    {
+        I2CWriteBitAction action{0x7C, 2, 2};
+        ADD_FAILURE() << "Should not have reached this line.";
+    }
+    catch (const std::invalid_argument& e)
+    {
+        EXPECT_STREQ(e.what(), "Invalid bit value: 2");
+    }
+    catch (...)
+    {
+        ADD_FAILURE() << "Should not have caught exception.";
+    }
+}
+
+TEST(I2CWriteBitActionTests, Execute)
+{
+    // Test where works: Value is 0
+    try
+    {
+        // Create mock I2CInterface: read() returns value 0xB6
+        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>(0xB6));
+        EXPECT_CALL(*i2cInterface,
+                    write(TypedEq<uint8_t>(0xA0), TypedEq<uint8_t>(0x96)))
+            .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"};
+
+        // Register value    : 0xB6 = 1011 0110
+        // 0 in position 5   : 0x00 = --0- ----
+        // New register value: 0x96 = 1001 0110
+        I2CWriteBitAction action{0xA0, 5, 0};
+        EXPECT_EQ(action.execute(env), true);
+    }
+    catch (...)
+    {
+        ADD_FAILURE() << "Should not have caught exception.";
+    }
+
+    // Test where works: Value is 1
+    try
+    {
+        // Create mock I2CInterface: read() returns value 0x96
+        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, A<uint8_t&>()))
+            .Times(1)
+            .WillOnce(SetArgReferee<1>(0x96));
+        EXPECT_CALL(*i2cInterface,
+                    write(TypedEq<uint8_t>(0x7C), TypedEq<uint8_t>(0xB6)))
+            .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"};
+
+        // Register value    : 0x96 = 1001 0110
+        // 1 in position 5   : 0x20 = 0010 0000
+        // New register value: 0xB6 = 1011 0110
+        I2CWriteBitAction action{0x7C, 5, 1};
+        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"};
+
+        I2CWriteBitAction action{0x7C, 5, 1};
+        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(0x7C, 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"};
+
+        I2CWriteBitAction action{0x7C, 5, 1};
+        action.execute(env);
+        ADD_FAILURE() << "Should not have reached this line.";
+    }
+    catch (const ActionError& e)
+    {
+        EXPECT_STREQ(e.what(), "ActionError: i2c_write_bit: { register: "
+                               "0x7C, position: 5, value: 1 }");
+        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: read() returns value 0xB6, 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(0xA0, A<uint8_t&>()))
+            .Times(1)
+            .WillOnce(SetArgReferee<1>(0xB6));
+        EXPECT_CALL(*i2cInterface,
+                    write(TypedEq<uint8_t>(0xA0), TypedEq<uint8_t>(0x96)))
+            .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"};
+
+        // Register value    : 0xB6 = 1011 0110
+        // 0 in position 5   : 0x00 = --0- ----
+        // New register value: 0x96 = 1001 0110
+        I2CWriteBitAction action{0xA0, 5, 0};
+        action.execute(env);
+        ADD_FAILURE() << "Should not have reached this line.";
+    }
+    catch (const ActionError& e)
+    {
+        EXPECT_STREQ(e.what(), "ActionError: i2c_write_bit: { register: "
+                               "0xA0, position: 5, value: 0 }");
+        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(I2CWriteBitActionTests, GetRegister)
+{
+    I2CWriteBitAction action{0x7C, 5, 1};
+    EXPECT_EQ(action.getRegister(), 0x7C);
+}
+
+TEST(I2CWriteBitActionTests, GetPosition)
+{
+    I2CWriteBitAction action{0x7C, 5, 1};
+    EXPECT_EQ(action.getPosition(), 5);
+}
+
+TEST(I2CWriteBitActionTests, GetValue)
+{
+    I2CWriteBitAction action{0x7C, 5, 1};
+    EXPECT_EQ(action.getValue(), 1);
+}
+
+TEST(I2CWriteBitActionTests, ToString)
+{
+    I2CWriteBitAction action{0x7C, 5, 1};
+    EXPECT_EQ(action.toString(),
+              "i2c_write_bit: { register: 0x7C, position: 5, value: 1 }");
+}
diff --git a/phosphor-regulators/test/meson.build b/phosphor-regulators/test/meson.build
index 0dc4c56..707bc83 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_bit_action_tests.cpp',
     'actions/i2c_write_byte_action_tests.cpp',
     'actions/i2c_write_bytes_action_tests.cpp',
     'actions/if_action_tests.cpp',