1 /**
2  * Copyright © 2020 IBM Corporation
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #include "i2c_write_bit_action.hpp"
18 
19 #include "action_error.hpp"
20 #include "i2c_interface.hpp"
21 
22 #include <exception>
23 #include <ios>
24 #include <sstream>
25 
26 namespace phosphor::power::regulators
27 {
28 
execute(ActionEnvironment & environment)29 bool I2CWriteBitAction::execute(ActionEnvironment& environment)
30 {
31     try
32     {
33         // Read value of device register
34         uint8_t registerValue{0x00};
35         i2c::I2CInterface& interface = getI2CInterface(environment);
36         interface.read(reg, registerValue);
37 
38         // Write bit to register value
39         if (value == 0)
40         {
41             // Clear bit within register value
42             registerValue &= ~(0x01 << position);
43         }
44         else
45         {
46             // Set bit within register value
47             registerValue |= (0x01 << position);
48         }
49 
50         // Write modified value to device register
51         interface.write(reg, registerValue);
52     }
53     catch (const i2c::I2CException& e)
54     {
55         // Nest I2CException within an ActionError so caller will have both the
56         // low level I2C error information and the action information
57         std::throw_with_nested(ActionError(*this));
58     }
59     return true;
60 }
61 
toString() const62 std::string I2CWriteBitAction::toString() const
63 {
64     std::ostringstream ss;
65     ss << "i2c_write_bit: { register: 0x" << std::hex << std::uppercase
66        << static_cast<uint16_t>(reg) << ", position: " << std::dec
67        << static_cast<uint16_t>(position)
68        << ", value: " << static_cast<uint16_t>(value) << " }";
69     return ss.str();
70 }
71 
72 } // namespace phosphor::power::regulators
73