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 #pragma once
17 
18 #include "action.hpp"
19 #include "action_environment.hpp"
20 #include "device.hpp"
21 #include "i2c_interface.hpp"
22 
23 namespace phosphor::power::regulators
24 {
25 
26 /**
27  * @class I2CAction
28  *
29  * Abstract base class for actions that communicate with a device using an I2C
30  * interface.
31  */
32 class I2CAction : public Action
33 {
34   public:
35     // Specify which compiler-generated methods we want
36     I2CAction() = default;
37     I2CAction(const I2CAction&) = delete;
38     I2CAction(I2CAction&&) = delete;
39     I2CAction& operator=(const I2CAction&) = delete;
40     I2CAction& operator=(I2CAction&&) = delete;
41     virtual ~I2CAction() = default;
42 
43   protected:
44     /**
45      * Returns the I2C interface to the current device within the specified
46      * action environment.
47      *
48      * Opens the interface if it was not already open.
49      *
50      * Throws an exception if an error occurs.
51      *
52      * @param environment action execution environment
53      * @return I2C interface to current device
54      */
getI2CInterface(ActionEnvironment & environment)55     i2c::I2CInterface& getI2CInterface(ActionEnvironment& environment)
56     {
57         // Get current device from action environment
58         Device& device = environment.getDevice();
59 
60         // Get I2C interface from device
61         i2c::I2CInterface& interface = device.getI2CInterface();
62 
63         // Open interface if necessary
64         if (!interface.isOpen())
65         {
66             interface.open();
67         }
68 
69         return interface;
70     }
71 };
72 
73 } // namespace phosphor::power::regulators
74