]> git.sesse.net Git - pistorm/blob - i2c_updater/pi-i2c/src/i2c.cpp
Initial work on FPGA I2C programmer
[pistorm] / i2c_updater / pi-i2c / src / i2c.cpp
1 /* This Source Code Form is subject to the terms of the Mozilla Public
2  * License, v. 2.0. If a copy of the MPL was not distributed with this
3  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
4
5 #include "i2c.hpp"
6
7 #include <unistd.h>
8 #include <fcntl.h>
9 #include <sys/ioctl.h>
10 #include <linux/i2c-dev.h>
11 #include <stdexcept>
12
13 tI2c::tI2c(const std::string &Port)
14 {
15         // Open the I2C bus file handle
16         m_I2cHandle = open(Port.c_str(), O_RDWR);
17         if(m_I2cHandle < 0) {
18                 // TODO: check errno to see what went wrong
19                 throw std::runtime_error("Can't open the i2c bus\n");
20         }
21 }
22
23 bool tI2c::write(uint8_t ubAddr, const std::vector<uint8_t> &vData) {
24         if(ioctl(m_I2cHandle, I2C_SLAVE, ubAddr) < 0) {
25                 // NOTE: check errno to see what went wrong
26                 return false;
27         }
28
29         auto BytesWritten = ::write(m_I2cHandle, vData.data(), vData.size());
30         if(BytesWritten != ssize_t(vData.size())) {
31                 return false;
32         }
33
34         return true;
35 }
36
37 bool tI2c::read(uint8_t ubAddr, uint8_t *pDest, uint32_t ulReadSize) {
38         if(ioctl(m_I2cHandle, I2C_SLAVE, ubAddr) < 0) {
39                 // NOTE: check errno to see what went wrong
40                 return false;
41         }
42
43         auto BytesRead = ::read(m_I2cHandle, pDest, ulReadSize);
44         if(BytesRead != ssize_t(ulReadSize)) {
45                 return false;
46         }
47
48         return true;
49 }