blob: 45bb024fd2c14291d10c21c1a9ac4fecc50e3dd7 [file] [log] [blame]
Lei YUab1327c2019-11-04 16:53:39 +08001#pragma once
2
3#include "i2c_interface.hpp"
4
5namespace i2c
6{
7
8class I2CDevice : public I2CInterface
9{
10 private:
11 I2CDevice() = delete;
12
Lei YU9af82a52019-11-06 14:51:22 +080013 /** @brief Constructor
14 *
15 * Construct I2CDevice object from the bus id and device address
16 *
17 * @param[in] busId - The i2c bus ID
18 * @param[in] devAddr - The device address of the I2C device
19 */
20 explicit I2CDevice(uint8_t busId, uint8_t devAddr) :
21 busId(busId), devAddr(devAddr)
Lei YUab1327c2019-11-04 16:53:39 +080022 {
Lei YU9af82a52019-11-06 14:51:22 +080023 busStr = "/dev/i2c-" + std::to_string(busId);
24 open();
Lei YUab1327c2019-11-04 16:53:39 +080025 }
26
Lei YU9af82a52019-11-06 14:51:22 +080027 /** @brief Open the i2c device */
28 void open();
29
30 /** @brief Close the i2c device */
31 void close();
32
33 /** @brief The I2C bus ID */
34 uint8_t busId;
35
36 /** @brief The i2c device address in the bus */
37 uint8_t devAddr;
38
39 /** @brief The file descriptor of the opened i2c device */
40 int fd;
41
42 /** @brief The i2c bus path in /dev */
43 std::string busStr;
44
Lei YUab1327c2019-11-04 16:53:39 +080045 public:
Lei YU9af82a52019-11-06 14:51:22 +080046 ~I2CDevice()
47 {
48 close();
49 }
Lei YUab1327c2019-11-04 16:53:39 +080050
51 /** @copydoc I2CInterface::read(uint8_t&) */
52 void read(uint8_t& data) override;
53
54 /** @copydoc I2CInterface::read(uint8_t,uint8_t&) */
55 void read(uint8_t addr, uint8_t& data) override;
56
57 /** @copydoc I2CInterface::read(uint8_t,uint16_t&) */
58 void read(uint8_t addr, uint16_t& data) override;
59
60 /** @copydoc I2CInterface::read(uint8_t,uint8_t&,uint8_t*) */
61 void read(uint8_t addr, uint8_t& size, uint8_t* data) override;
62
63 /** @copydoc I2CInterface::write(uint8_t) */
64 void write(uint8_t data) override;
65
66 /** @copydoc I2CInterface::write(uint8_t,uint8_t) */
67 void write(uint8_t addr, uint8_t data) override;
68
69 /** @copydoc I2CInterface::write(uint8_t,uint16_t) */
70 void write(uint8_t addr, uint16_t data) override;
71
72 /** @copydoc I2CInterface::write(uint8_t,uint8_t,const uint8_t*) */
73 void write(uint8_t addr, uint8_t size, const uint8_t* data) override;
74
75 /** @brief Create an I2CInterface instance
76 *
77 * @param[in] busId - The i2c bus ID
78 * @param[in] devAddr - The device address of the i2c
79 *
80 * @return The unique_ptr holding the I2CInterface
81 */
82 static std::unique_ptr<I2CInterface> create(uint8_t busId, uint8_t devAddr);
83};
84
85} // namespace i2c