fwt_software/include/fgc/sensors/I2cBus.h

38 lines
1.0 KiB
C++

#pragma once
#include <cstdint>
#include <string>
#include <vector>
namespace fgc {
// Thin RAII wrapper around a Linux I2C device node (/dev/i2c-N), talking to
// one fixed slave address via the kernel i2c-dev ioctl interface. Generic
// (not sensor-specific) so any future I2C device reuses it.
class I2cBus {
public:
I2cBus(std::string device, uint8_t addr);
~I2cBus();
I2cBus(const I2cBus&) = delete;
I2cBus& operator=(const I2cBus&) = delete;
// Opens the device node and binds the slave address. Returns false on failure.
bool open();
void close();
bool isOpen() const { return fd_ >= 0; }
// Writes `tx`, then (if `rx` is non-empty) reads into it. Combined so a
// single call can do "write command, read reply". Returns false on any I/O
// error.
bool writeRead(const std::vector<uint8_t>& tx, std::vector<uint8_t>& rx);
bool write(const std::vector<uint8_t>& tx);
private:
std::string device_;
uint8_t addr_;
int fd_ = -1;
};
} // namespace fgc